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 dep_graph::DepGraph;
15 use hir::def_id::{CrateNum, DefIndex};
18 use middle::cstore::CrateStore;
19 use middle::dependency_format;
20 use session::search_paths::PathKind;
21 use session::config::DebugInfoLevel;
23 use util::nodemap::{FxHashMap, FxHashSet};
24 use util::common::duration_to_secs_str;
25 use mir::transform as mir_pass;
27 use syntax::ast::NodeId;
28 use errors::{self, DiagnosticBuilder};
29 use errors::emitter::{Emitter, EmitterWriter};
30 use syntax::json::JsonEmitter;
31 use syntax::feature_gate;
33 use syntax::parse::ParseSess;
34 use syntax::symbol::Symbol;
35 use syntax::{ast, codemap};
36 use syntax::feature_gate::AttributeType;
37 use syntax_pos::{Span, MultiSpan};
39 use rustc_back::PanicStrategy;
40 use rustc_back::target::Target;
41 use rustc_data_structures::flock;
44 use std::path::{Path, PathBuf};
45 use std::cell::{self, Cell, RefCell};
46 use std::collections::HashMap;
48 use std::ffi::CString;
52 use std::time::Duration;
60 // Represents the data associated with a compilation
61 // session for a single crate.
63 pub dep_graph: DepGraph,
64 pub target: config::Config,
66 pub opts: config::Options,
67 pub cstore: Rc<CrateStore>,
68 pub parse_sess: ParseSess,
69 // For a library crate, this is always none
70 pub entry_fn: RefCell<Option<(NodeId, Span)>>,
71 pub entry_type: Cell<Option<config::EntryFnType>>,
72 pub plugin_registrar_fn: Cell<Option<ast::NodeId>>,
73 pub derive_registrar_fn: Cell<Option<ast::NodeId>>,
74 pub default_sysroot: Option<PathBuf>,
75 // The name of the root source file of the crate, in the local file system.
76 // The path is always expected to be absolute. `None` means that there is no
78 pub local_crate_source_file: Option<PathBuf>,
79 pub working_dir: PathBuf,
80 pub lint_store: RefCell<lint::LintStore>,
81 pub lints: RefCell<lint::LintTable>,
82 /// Set of (LintId, span, message) tuples tracking lint (sub)diagnostics
83 /// that have been set once, but should not be set again, in order to avoid
84 /// redundantly verbose output (Issue #24690).
85 pub one_time_diagnostics: RefCell<FxHashSet<(lint::LintId, Span, String)>>,
86 pub plugin_llvm_passes: RefCell<Vec<String>>,
87 pub mir_passes: RefCell<mir_pass::Passes>,
88 pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
89 pub crate_types: RefCell<Vec<config::CrateType>>,
90 pub dependency_formats: RefCell<dependency_format::Dependencies>,
91 // The crate_disambiguator is constructed out of all the `-C metadata`
92 // arguments passed to the compiler. Its value together with the crate-name
93 // forms a unique global identifier for the crate. It is used to allow
94 // multiple crates with the same name to coexist. See the
95 // trans::back::symbol_names module for more information.
96 pub crate_disambiguator: RefCell<Symbol>,
97 pub features: RefCell<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 injected_panic_runtime: Cell<Option<CrateNum>>,
112 /// Map from imported macro spans (which consist of
113 /// the localized span for the macro body) to the
114 /// macro name and defintion span in the source crate.
115 pub imported_macro_spans: RefCell<HashMap<Span, (String, Span)>>,
117 incr_comp_session: RefCell<IncrCompSession>,
119 /// Some measurements that are being gathered during compilation.
120 pub perf_stats: PerfStats,
122 /// Data about code being compiled, gathered during compilation.
123 pub code_stats: RefCell<CodeStats>,
125 next_node_id: Cell<ast::NodeId>,
128 pub struct PerfStats {
129 // The accumulated time needed for computing the SVH of the crate
130 pub svh_time: Cell<Duration>,
131 // The accumulated time spent on computing incr. comp. hashes
132 pub incr_comp_hashes_time: Cell<Duration>,
133 // The number of incr. comp. hash computations performed
134 pub incr_comp_hashes_count: Cell<u64>,
135 // The number of bytes hashed when computing ICH values
136 pub incr_comp_bytes_hashed: Cell<u64>,
137 // The accumulated time spent on computing symbol hashes
138 pub symbol_hash_time: Cell<Duration>,
139 // The accumulated time spent decoding def path tables from metadata
140 pub decode_def_path_tables_time: Cell<Duration>,
144 pub fn local_crate_disambiguator(&self) -> Symbol {
145 *self.crate_disambiguator.borrow()
147 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
150 -> DiagnosticBuilder<'a> {
151 self.diagnostic().struct_span_warn(sp, msg)
153 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
157 -> DiagnosticBuilder<'a> {
158 self.diagnostic().struct_span_warn_with_code(sp, msg, code)
160 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
161 self.diagnostic().struct_warn(msg)
163 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
166 -> DiagnosticBuilder<'a> {
167 self.diagnostic().struct_span_err(sp, msg)
169 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
173 -> DiagnosticBuilder<'a> {
174 self.diagnostic().struct_span_err_with_code(sp, msg, code)
176 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
177 self.diagnostic().struct_err(msg)
179 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
182 -> DiagnosticBuilder<'a> {
183 self.diagnostic().struct_span_fatal(sp, msg)
185 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
189 -> DiagnosticBuilder<'a> {
190 self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
192 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
193 self.diagnostic().struct_fatal(msg)
196 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
197 panic!(self.diagnostic().span_fatal(sp, msg))
199 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) -> ! {
200 panic!(self.diagnostic().span_fatal_with_code(sp, msg, code))
202 pub fn fatal(&self, msg: &str) -> ! {
203 panic!(self.diagnostic().fatal(msg))
205 pub fn span_err_or_warn<S: Into<MultiSpan>>(&self, is_warning: bool, sp: S, msg: &str) {
207 self.span_warn(sp, msg);
209 self.span_err(sp, msg);
212 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
213 self.diagnostic().span_err(sp, msg)
215 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
216 self.diagnostic().span_err_with_code(sp, &msg, code)
218 pub fn err(&self, msg: &str) {
219 self.diagnostic().err(msg)
221 pub fn err_count(&self) -> usize {
222 self.diagnostic().err_count()
224 pub fn has_errors(&self) -> bool {
225 self.diagnostic().has_errors()
227 pub fn abort_if_errors(&self) {
228 self.diagnostic().abort_if_errors();
230 pub fn track_errors<F, T>(&self, f: F) -> Result<T, usize>
231 where F: FnOnce() -> T
233 let old_count = self.err_count();
235 let errors = self.err_count() - old_count;
242 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
243 self.diagnostic().span_warn(sp, msg)
245 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: &str) {
246 self.diagnostic().span_warn_with_code(sp, msg, code)
248 pub fn warn(&self, msg: &str) {
249 self.diagnostic().warn(msg)
251 pub fn opt_span_warn<S: Into<MultiSpan>>(&self, opt_sp: Option<S>, msg: &str) {
253 Some(sp) => self.span_warn(sp, msg),
254 None => self.warn(msg),
257 /// Delay a span_bug() call until abort_if_errors()
258 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
259 self.diagnostic().delay_span_bug(sp, msg)
261 pub fn note_without_error(&self, msg: &str) {
262 self.diagnostic().note_without_error(msg)
264 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
265 self.diagnostic().span_note_without_error(sp, msg)
267 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
268 self.diagnostic().span_unimpl(sp, msg)
270 pub fn unimpl(&self, msg: &str) -> ! {
271 self.diagnostic().unimpl(msg)
274 pub fn add_lint<S: Into<MultiSpan>>(&self,
275 lint: &'static lint::Lint,
280 self.lints.borrow_mut().add_lint(lint, id, sp, msg);
283 pub fn add_lint_diagnostic<M>(&self,
284 lint: &'static lint::Lint,
287 where M: lint::IntoEarlyLint,
289 self.lints.borrow_mut().add_lint_diagnostic(lint, id, msg);
292 pub fn reserve_node_ids(&self, count: usize) -> ast::NodeId {
293 let id = self.next_node_id.get();
295 match id.as_usize().checked_add(count) {
297 self.next_node_id.set(ast::NodeId::new(next));
299 None => bug!("Input too large, ran out of node ids!")
304 pub fn next_node_id(&self) -> NodeId {
305 self.reserve_node_ids(1)
307 pub fn diagnostic<'a>(&'a self) -> &'a errors::Handler {
308 &self.parse_sess.span_diagnostic
311 /// Analogous to calling `.span_note` on the given DiagnosticBuilder, but
312 /// deduplicates on lint ID, span, and message for this `Session` if we're
313 /// not outputting in JSON mode.
315 // FIXME: if the need arises for one-time diagnostics other than
316 // `span_note`, we almost certainly want to generalize this
317 // "check/insert-into the one-time diagnostics map, then set message if
318 // it's not already there" code to accomodate all of them
319 pub fn diag_span_note_once<'a, 'b>(&'a self,
320 diag_builder: &'b mut DiagnosticBuilder<'a>,
321 lint: &'static lint::Lint, span: Span, message: &str) {
322 match self.opts.error_format {
323 // when outputting JSON for tool consumption, the tool might want
325 config::ErrorOutputType::Json => {
326 diag_builder.span_note(span, &message);
329 let lint_id = lint::LintId::of(lint);
330 let id_span_message = (lint_id, span, message.to_owned());
331 let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
333 diag_builder.span_note(span, &message);
339 pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
340 self.parse_sess.codemap()
342 pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
343 pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
344 pub fn count_llvm_insns(&self) -> bool {
345 self.opts.debugging_opts.count_llvm_insns
347 pub fn time_llvm_passes(&self) -> bool {
348 self.opts.debugging_opts.time_llvm_passes
350 pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
351 pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
352 pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
353 pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
354 pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
355 pub fn print_llvm_passes(&self) -> bool {
356 self.opts.debugging_opts.print_llvm_passes
358 pub fn lto(&self) -> bool {
361 /// Returns the panic strategy for this compile session. If the user explicitly selected one
362 /// using '-C panic', use that, otherwise use the panic strategy defined by the target.
363 pub fn panic_strategy(&self) -> PanicStrategy {
364 self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
366 pub fn no_landing_pads(&self) -> bool {
367 self.opts.debugging_opts.no_landing_pads || self.panic_strategy() == PanicStrategy::Abort
369 pub fn unstable_options(&self) -> bool {
370 self.opts.debugging_opts.unstable_options
372 pub fn nonzeroing_move_hints(&self) -> bool {
373 self.opts.debugging_opts.enable_nonzeroing_move_hints
375 pub fn overflow_checks(&self) -> bool {
376 self.opts.cg.overflow_checks
377 .or(self.opts.debugging_opts.force_overflow_checks)
378 .unwrap_or(self.opts.debug_assertions)
381 pub fn must_not_eliminate_frame_pointers(&self) -> bool {
382 self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
383 !self.target.target.options.eliminate_frame_pointer
386 /// Returns the symbol name for the registrar function,
387 /// given the crate Svh and the function DefIndex.
388 pub fn generate_plugin_registrar_symbol(&self, svh: &Svh, index: DefIndex)
390 format!("__rustc_plugin_registrar__{}_{}", svh, index.as_usize())
393 pub fn generate_derive_registrar_symbol(&self,
395 index: DefIndex) -> String {
396 format!("__rustc_derive_registrar__{}_{}", svh, index.as_usize())
399 pub fn sysroot<'a>(&'a self) -> &'a Path {
400 match self.opts.maybe_sysroot {
401 Some (ref sysroot) => sysroot,
402 None => self.default_sysroot.as_ref()
403 .expect("missing sysroot and default_sysroot in Session")
406 pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
407 filesearch::FileSearch::new(self.sysroot(),
408 &self.opts.target_triple,
409 &self.opts.search_paths,
412 pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
413 filesearch::FileSearch::new(
415 config::host_triple(),
416 &self.opts.search_paths,
420 pub fn init_incr_comp_session(&self,
421 session_dir: PathBuf,
422 lock_file: flock::Lock) {
423 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
425 if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
426 bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
429 *incr_comp_session = IncrCompSession::Active {
430 session_directory: session_dir,
431 lock_file: lock_file,
435 pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
436 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
438 if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
439 bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
442 // Note: This will also drop the lock file, thus unlocking the directory
443 *incr_comp_session = IncrCompSession::Finalized {
444 session_directory: new_directory_path,
448 pub fn mark_incr_comp_session_as_invalid(&self) {
449 let mut incr_comp_session = self.incr_comp_session.borrow_mut();
451 let session_directory = match *incr_comp_session {
452 IncrCompSession::Active { ref session_directory, .. } => {
453 session_directory.clone()
455 _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
459 // Note: This will also drop the lock file, thus unlocking the directory
460 *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
461 session_directory: session_directory
465 pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
466 let incr_comp_session = self.incr_comp_session.borrow();
467 cell::Ref::map(incr_comp_session, |incr_comp_session| {
468 match *incr_comp_session {
469 IncrCompSession::NotInitialized => {
470 bug!("Trying to get session directory from IncrCompSession `{:?}`",
473 IncrCompSession::Active { ref session_directory, .. } |
474 IncrCompSession::Finalized { ref session_directory } |
475 IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
482 pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
483 if self.opts.incremental.is_some() {
484 Some(self.incr_comp_session_dir())
490 pub fn print_perf_stats(&self) {
491 println!("Total time spent computing SVHs: {}",
492 duration_to_secs_str(self.perf_stats.svh_time.get()));
493 println!("Total time spent computing incr. comp. hashes: {}",
494 duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
495 println!("Total number of incr. comp. hashes computed: {}",
496 self.perf_stats.incr_comp_hashes_count.get());
497 println!("Total number of bytes hashed for incr. comp.: {}",
498 self.perf_stats.incr_comp_bytes_hashed.get());
499 println!("Average bytes hashed per incr. comp. HIR node: {}",
500 self.perf_stats.incr_comp_bytes_hashed.get() /
501 self.perf_stats.incr_comp_hashes_count.get());
502 println!("Total time spent computing symbol hashes: {}",
503 duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
504 println!("Total time spent decoding DefPath tables: {}",
505 duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
509 pub fn build_session(sopts: config::Options,
510 dep_graph: &DepGraph,
511 local_crate_source_file: Option<PathBuf>,
512 registry: errors::registry::Registry,
513 cstore: Rc<CrateStore>)
515 build_session_with_codemap(sopts,
517 local_crate_source_file,
520 Rc::new(codemap::CodeMap::new()),
524 pub fn build_session_with_codemap(sopts: config::Options,
525 dep_graph: &DepGraph,
526 local_crate_source_file: Option<PathBuf>,
527 registry: errors::registry::Registry,
528 cstore: Rc<CrateStore>,
529 codemap: Rc<codemap::CodeMap>,
530 emitter_dest: Option<Box<Write + Send>>)
532 // FIXME: This is not general enough to make the warning lint completely override
533 // normal diagnostic warnings, since the warning lint can also be denied and changed
534 // later via the source code.
535 let can_print_warnings = sopts.lint_opts
537 .filter(|&&(ref key, _)| *key == "warnings")
538 .map(|&(_, ref level)| *level != lint::Allow)
541 let treat_err_as_bug = sopts.debugging_opts.treat_err_as_bug;
543 let emitter: Box<Emitter> = match (sopts.error_format, emitter_dest) {
544 (config::ErrorOutputType::HumanReadable(color_config), None) => {
545 Box::new(EmitterWriter::stderr(color_config,
546 Some(codemap.clone())))
548 (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
549 Box::new(EmitterWriter::new(dst,
550 Some(codemap.clone())))
552 (config::ErrorOutputType::Json, None) => {
553 Box::new(JsonEmitter::stderr(Some(registry), codemap.clone()))
555 (config::ErrorOutputType::Json, Some(dst)) => {
556 Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone()))
560 let diagnostic_handler =
561 errors::Handler::with_emitter(can_print_warnings,
565 build_session_(sopts,
567 local_crate_source_file,
573 pub fn build_session_(sopts: config::Options,
574 dep_graph: &DepGraph,
575 local_crate_source_file: Option<PathBuf>,
576 span_diagnostic: errors::Handler,
577 codemap: Rc<codemap::CodeMap>,
578 cstore: Rc<CrateStore>)
580 let host = match Target::search(config::host_triple()) {
583 panic!(span_diagnostic.fatal(&format!("Error loading host specification: {}", e)));
586 let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
587 let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
588 let default_sysroot = match sopts.maybe_sysroot {
590 None => Some(filesearch::get_or_default_sysroot())
593 // Make the path absolute, if necessary
594 let local_crate_source_file = local_crate_source_file.map(|path|
595 if path.is_absolute() {
598 env::current_dir().unwrap().join(&path)
603 dep_graph: dep_graph.clone(),
609 // For a library crate, this is always none
610 entry_fn: RefCell::new(None),
611 entry_type: Cell::new(None),
612 plugin_registrar_fn: Cell::new(None),
613 derive_registrar_fn: Cell::new(None),
614 default_sysroot: default_sysroot,
615 local_crate_source_file: local_crate_source_file,
616 working_dir: env::current_dir().unwrap(),
617 lint_store: RefCell::new(lint::LintStore::new()),
618 lints: RefCell::new(lint::LintTable::new()),
619 one_time_diagnostics: RefCell::new(FxHashSet()),
620 plugin_llvm_passes: RefCell::new(Vec::new()),
621 mir_passes: RefCell::new(mir_pass::Passes::new()),
622 plugin_attributes: RefCell::new(Vec::new()),
623 crate_types: RefCell::new(Vec::new()),
624 dependency_formats: RefCell::new(FxHashMap()),
625 crate_disambiguator: RefCell::new(Symbol::intern("")),
626 features: RefCell::new(feature_gate::Features::new()),
627 recursion_limit: Cell::new(64),
628 type_length_limit: Cell::new(1048576),
629 next_node_id: Cell::new(NodeId::new(1)),
630 injected_allocator: Cell::new(None),
631 injected_panic_runtime: Cell::new(None),
632 imported_macro_spans: RefCell::new(HashMap::new()),
633 incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
634 perf_stats: PerfStats {
635 svh_time: Cell::new(Duration::from_secs(0)),
636 incr_comp_hashes_time: Cell::new(Duration::from_secs(0)),
637 incr_comp_hashes_count: Cell::new(0),
638 incr_comp_bytes_hashed: Cell::new(0),
639 symbol_hash_time: Cell::new(Duration::from_secs(0)),
640 decode_def_path_tables_time: Cell::new(Duration::from_secs(0)),
642 code_stats: RefCell::new(CodeStats::new()),
650 /// Holds data on the current incremental compilation session, if there is one.
652 pub enum IncrCompSession {
653 // This is the state the session will be in until the incr. comp. dir is
656 // This is the state during which the session directory is private and can
659 session_directory: PathBuf,
660 lock_file: flock::Lock,
662 // This is the state after the session directory has been finalized. In this
663 // state, the contents of the directory must not be modified any more.
665 session_directory: PathBuf,
667 // This is an error state that is reached when some compilation error has
668 // occurred. It indicates that the contents of the session directory must
669 // not be used, since they might be invalid.
670 InvalidBecauseOfErrors {
671 session_directory: PathBuf,
675 fn init_llvm(sess: &Session) {
677 // Before we touch LLVM, make sure that multithreading is enabled.
679 static INIT: Once = Once::new();
680 static mut POISONED: bool = false;
682 if llvm::LLVMStartMultithreaded() != 1 {
683 // use an extra bool to make sure that all future usage of LLVM
684 // cannot proceed despite the Once not running more than once.
688 configure_llvm(sess);
692 bug!("couldn't enable multi-threaded LLVM");
697 unsafe fn configure_llvm(sess: &Session) {
698 let mut llvm_c_strs = Vec::new();
699 let mut llvm_args = Vec::new();
702 let mut add = |arg: &str| {
703 let s = CString::new(arg).unwrap();
704 llvm_args.push(s.as_ptr());
707 add("rustc"); // fake program name
708 if sess.time_llvm_passes() { add("-time-passes"); }
709 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
711 for arg in &sess.opts.cg.llvm_args {
716 llvm::LLVMInitializePasses();
718 llvm::initialize_available_targets();
720 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
724 pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
725 let emitter: Box<Emitter> = match output {
726 config::ErrorOutputType::HumanReadable(color_config) => {
727 Box::new(EmitterWriter::stderr(color_config,
730 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
732 let handler = errors::Handler::with_emitter(true, false, emitter);
733 handler.emit(&MultiSpan::new(), msg, errors::Level::Fatal);
734 panic!(errors::FatalError);
737 pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
738 let emitter: Box<Emitter> = match output {
739 config::ErrorOutputType::HumanReadable(color_config) => {
740 Box::new(EmitterWriter::stderr(color_config,
743 config::ErrorOutputType::Json => Box::new(JsonEmitter::basic()),
745 let handler = errors::Handler::with_emitter(true, false, emitter);
746 handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
749 // Err(0) means compilation was stopped, but no errors were found.
750 // This would be better as a dedicated enum, but using try! is so convenient.
751 pub type CompileResult = Result<(), usize>;
753 pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
763 pub fn bug_fmt(file: &'static str, line: u32, args: fmt::Arguments) -> ! {
764 // this wrapper mostly exists so I don't have to write a fully
765 // qualified path of None::<Span> inside the bug!() macro defintion
766 opt_span_bug_fmt(file, line, None::<Span>, args);
771 pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
774 args: fmt::Arguments) -> ! {
775 opt_span_bug_fmt(file, line, Some(span), args);
778 fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
781 args: fmt::Arguments) -> ! {
782 tls::with_opt(move |tcx| {
783 let msg = format!("{}:{}: {}", file, line, args);
785 (Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
786 (Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
787 (None, _) => panic!(msg)