1 // Copyright 2012-2015 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 use rustc::hir::{self, map as hir_map};
12 use rustc::hir::lowering::lower_crate;
13 use rustc::ich::Fingerprint;
14 use rustc_data_structures::stable_hasher::StableHasher;
16 use rustc::session::{Session, CompileResult};
17 use rustc::session::CompileIncomplete;
18 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
19 use rustc::session::search_paths::PathKind;
21 use rustc::middle::{self, dependency_format, stability, reachable};
22 use rustc::middle::privacy::AccessLevels;
23 use rustc::mir::transform::{MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED, Passes};
24 use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
26 use rustc::util::common::{ErrorReported, time};
27 use rustc::util::nodemap::NodeSet;
28 use rustc_allocator as allocator;
29 use rustc_borrowck as borrowck;
30 use rustc_incremental::{self, IncrementalHashesMap};
31 use rustc_resolve::{MakeGlobMap, Resolver};
32 use rustc_metadata::creader::CrateLoader;
33 use rustc_metadata::cstore::{self, CStore};
34 use rustc_trans::back::{link, write};
35 use rustc_trans as trans;
36 use rustc_typeck as typeck;
38 use rustc_plugin::registry::Registry;
39 use rustc_plugin as plugin;
40 use rustc_passes::{ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
41 use rustc_const_eval::{self, check_match};
42 use super::Compilation;
47 use std::ffi::{OsString, OsStr};
49 use std::io::{self, Write};
51 use std::path::{Path, PathBuf};
53 use syntax::{ast, diagnostics, visit};
55 use syntax::ext::base::ExtCtxt;
56 use syntax::parse::{self, PResult};
57 use syntax::symbol::Symbol;
58 use syntax::util::node_count::NodeCounter;
61 use arena::DroplessArena;
65 pub fn compile_input(sess: &Session,
68 outdir: &Option<PathBuf>,
69 output: &Option<PathBuf>,
70 addl_plugins: Option<Vec<String>>,
71 control: &CompileController) -> CompileResult {
72 macro_rules! controller_entry_point {
73 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
74 let state = &mut $make_state;
75 let phase_result: &CompileResult = &$phase_result;
76 if phase_result.is_ok() || control.$point.run_callback_on_error {
77 (control.$point.callback)(state);
80 if control.$point.stop == Compilation::Stop {
81 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
82 // if there are no errors?
83 return $tsess.compile_status();
88 // We need nested scopes here, because the intermediate results can keep
89 // large chunks of memory alive and we want to free them as soon as
90 // possible to keep the peak memory usage low
91 let (outputs, trans) = {
92 let krate = match phase_1_parse_input(sess, input) {
94 Err(mut parse_error) => {
96 return Err(CompileIncomplete::Errored(ErrorReported));
100 let (krate, registry) = {
101 let mut compile_state = CompileState::state_after_parse(input,
107 controller_entry_point!(after_parse,
112 (compile_state.krate.unwrap(), compile_state.registry)
115 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
116 let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
117 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
118 phase_2_configure_and_expand(
119 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
121 let mut state = CompileState::state_after_expand(
122 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
124 controller_entry_point!(after_expand, sess, state, Ok(()));
130 write_out_deps(sess, &outputs, &crate_name);
131 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
132 sess.opts.output_types.keys().count() == 1 {
136 let arena = DroplessArena::new();
137 let arenas = GlobalArenas::new();
139 // Construct the HIR map
140 let hir_map = time(sess.time_passes(),
142 || hir_map::map_crate(&mut hir_forest, defs));
145 let _ignore = hir_map.dep_graph.in_ignore();
146 controller_entry_point!(after_hir_lowering,
148 CompileState::state_after_hir_lowering(input,
164 time(sess.time_passes(), "attribute checking", || {
165 hir::check_attr::check_crate(sess, &expanded_crate);
168 let opt_crate = if control.keep_ast {
169 Some(&expanded_crate)
171 drop(expanded_crate);
175 phase_3_run_analysis_passes(sess,
182 |tcx, analysis, incremental_hashes_map, result| {
184 // Eventually, we will want to track plugins.
185 let _ignore = tcx.dep_graph.in_ignore();
187 let mut state = CompileState::state_after_analysis(input,
196 (control.after_analysis.callback)(&mut state);
198 if control.after_analysis.stop == Compilation::Stop {
199 return result.and_then(|_| Err(CompileIncomplete::Stopped));
205 if log_enabled!(::log::LogLevel::Info) {
206 println!("Pre-trans");
207 tcx.print_debug_stats();
209 let trans = phase_4_translate_to_llvm(tcx, analysis, incremental_hashes_map,
212 if log_enabled!(::log::LogLevel::Info) {
213 println!("Post-trans");
214 tcx.print_debug_stats();
217 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
218 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
219 sess.err(&format!("could not emit MIR: {}", e));
220 sess.abort_if_errors();
228 if sess.opts.debugging_opts.print_type_sizes {
229 sess.code_stats.borrow().print_type_sizes();
232 let (phase5_result, trans) = phase_5_run_llvm_passes(sess, trans);
234 controller_entry_point!(after_llvm,
236 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
240 phase_6_link_output(sess, &trans, &outputs);
242 // Now that we won't touch anything in the incremental compilation directory
243 // any more, we can finalize it (which involves renaming it)
244 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
246 if sess.opts.debugging_opts.perf_stats {
247 sess.print_perf_stats();
250 controller_entry_point!(compilation_done,
252 CompileState::state_when_compilation_done(input, sess, outdir, output),
258 fn keep_hygiene_data(sess: &Session) -> bool {
259 sess.opts.debugging_opts.keep_hygiene_data
263 /// The name used for source code that doesn't originate in a file
264 /// (e.g. source from stdin or a string)
265 pub fn anon_src() -> String {
269 pub fn source_name(input: &Input) -> String {
271 // FIXME (#9639): This needs to handle non-utf8 paths
272 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
273 Input::Str { ref name, .. } => name.clone(),
277 /// CompileController is used to customise compilation, it allows compilation to
278 /// be stopped and/or to call arbitrary code at various points in compilation.
279 /// It also allows for various flags to be set to influence what information gets
280 /// collected during compilation.
282 /// This is a somewhat higher level controller than a Session - the Session
283 /// controls what happens in each phase, whereas the CompileController controls
284 /// whether a phase is run at all and whether other code (from outside the
285 /// the compiler) is run between phases.
287 /// Note that if compilation is set to stop and a callback is provided for a
288 /// given entry point, the callback is called before compilation is stopped.
290 /// Expect more entry points to be added in the future.
291 pub struct CompileController<'a> {
292 pub after_parse: PhaseController<'a>,
293 pub after_expand: PhaseController<'a>,
294 pub after_hir_lowering: PhaseController<'a>,
295 pub after_analysis: PhaseController<'a>,
296 pub after_llvm: PhaseController<'a>,
297 pub compilation_done: PhaseController<'a>,
299 pub make_glob_map: MakeGlobMap,
300 // Whether the compiler should keep the ast beyond parsing.
304 impl<'a> CompileController<'a> {
305 pub fn basic() -> CompileController<'a> {
307 after_parse: PhaseController::basic(),
308 after_expand: PhaseController::basic(),
309 after_hir_lowering: PhaseController::basic(),
310 after_analysis: PhaseController::basic(),
311 after_llvm: PhaseController::basic(),
312 compilation_done: PhaseController::basic(),
313 make_glob_map: MakeGlobMap::No,
319 pub struct PhaseController<'a> {
320 pub stop: Compilation,
321 // If true then the compiler will try to run the callback even if the phase
322 // ends with an error. Note that this is not always possible.
323 pub run_callback_on_error: bool,
324 pub callback: Box<Fn(&mut CompileState) + 'a>,
327 impl<'a> PhaseController<'a> {
328 pub fn basic() -> PhaseController<'a> {
330 stop: Compilation::Continue,
331 run_callback_on_error: false,
332 callback: box |_| {},
337 /// State that is passed to a callback. What state is available depends on when
338 /// during compilation the callback is made. See the various constructor methods
339 /// (`state_*`) in the impl to see which data is provided for any given entry point.
340 pub struct CompileState<'a, 'tcx: 'a> {
341 pub input: &'a Input,
342 pub session: &'tcx Session,
343 pub krate: Option<ast::Crate>,
344 pub registry: Option<Registry<'a>>,
345 pub cstore: Option<&'a CStore>,
346 pub crate_name: Option<&'a str>,
347 pub output_filenames: Option<&'a OutputFilenames>,
348 pub out_dir: Option<&'a Path>,
349 pub out_file: Option<&'a Path>,
350 pub arena: Option<&'tcx DroplessArena>,
351 pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
352 pub expanded_crate: Option<&'a ast::Crate>,
353 pub hir_crate: Option<&'a hir::Crate>,
354 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
355 pub resolutions: Option<&'a Resolutions>,
356 pub analysis: Option<&'a ty::CrateAnalysis>,
357 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
358 pub trans: Option<&'a trans::CrateTranslation>,
361 impl<'a, 'tcx> CompileState<'a, 'tcx> {
362 fn empty(input: &'a Input,
363 session: &'tcx Session,
364 out_dir: &'a Option<PathBuf>)
369 out_dir: out_dir.as_ref().map(|s| &**s),
377 output_filenames: None,
378 expanded_crate: None,
388 fn state_after_parse(input: &'a Input,
389 session: &'tcx Session,
390 out_dir: &'a Option<PathBuf>,
391 out_file: &'a Option<PathBuf>,
396 // Initialize the registry before moving `krate`
397 registry: Some(Registry::new(&session, krate.span)),
399 cstore: Some(cstore),
400 out_file: out_file.as_ref().map(|s| &**s),
401 ..CompileState::empty(input, session, out_dir)
405 fn state_after_expand(input: &'a Input,
406 session: &'tcx Session,
407 out_dir: &'a Option<PathBuf>,
408 out_file: &'a Option<PathBuf>,
410 expanded_crate: &'a ast::Crate,
414 crate_name: Some(crate_name),
415 cstore: Some(cstore),
416 expanded_crate: Some(expanded_crate),
417 out_file: out_file.as_ref().map(|s| &**s),
418 ..CompileState::empty(input, session, out_dir)
422 fn state_after_hir_lowering(input: &'a Input,
423 session: &'tcx Session,
424 out_dir: &'a Option<PathBuf>,
425 out_file: &'a Option<PathBuf>,
426 arena: &'tcx DroplessArena,
427 arenas: &'tcx GlobalArenas<'tcx>,
429 hir_map: &'a hir_map::Map<'tcx>,
430 analysis: &'a ty::CrateAnalysis,
431 resolutions: &'a Resolutions,
432 krate: &'a ast::Crate,
433 hir_crate: &'a hir::Crate,
437 crate_name: Some(crate_name),
439 arenas: Some(arenas),
440 cstore: Some(cstore),
441 hir_map: Some(hir_map),
442 analysis: Some(analysis),
443 resolutions: Some(resolutions),
444 expanded_crate: Some(krate),
445 hir_crate: Some(hir_crate),
446 out_file: out_file.as_ref().map(|s| &**s),
447 ..CompileState::empty(input, session, out_dir)
451 fn state_after_analysis(input: &'a Input,
452 session: &'tcx Session,
453 out_dir: &'a Option<PathBuf>,
454 out_file: &'a Option<PathBuf>,
455 krate: Option<&'a ast::Crate>,
456 hir_crate: &'a hir::Crate,
457 analysis: &'a ty::CrateAnalysis,
458 tcx: TyCtxt<'a, 'tcx, 'tcx>,
462 analysis: Some(analysis),
464 expanded_crate: krate,
465 hir_crate: Some(hir_crate),
466 crate_name: Some(crate_name),
467 out_file: out_file.as_ref().map(|s| &**s),
468 ..CompileState::empty(input, session, out_dir)
473 fn state_after_llvm(input: &'a Input,
474 session: &'tcx Session,
475 out_dir: &'a Option<PathBuf>,
476 out_file: &'a Option<PathBuf>,
477 trans: &'a trans::CrateTranslation)
481 out_file: out_file.as_ref().map(|s| &**s),
482 ..CompileState::empty(input, session, out_dir)
486 fn state_when_compilation_done(input: &'a Input,
487 session: &'tcx Session,
488 out_dir: &'a Option<PathBuf>,
489 out_file: &'a Option<PathBuf>)
492 out_file: out_file.as_ref().map(|s| &**s),
493 ..CompileState::empty(input, session, out_dir)
498 pub fn phase_1_parse_input<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
499 let continue_after_error = sess.opts.debugging_opts.continue_parse_after_error;
500 sess.diagnostic().set_continue_after_error(continue_after_error);
502 let krate = time(sess.time_passes(), "parsing", || {
504 Input::File(ref file) => {
505 parse::parse_crate_from_file(file, &sess.parse_sess)
507 Input::Str { ref input, ref name } => {
508 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
513 sess.diagnostic().set_continue_after_error(true);
515 if sess.opts.debugging_opts.ast_json_noexpand {
516 println!("{}", json::as_json(&krate));
519 if sess.opts.debugging_opts.input_stats {
520 println!("Lines of code: {}", sess.codemap().count_lines());
521 println!("Pre-expansion node count: {}", count_nodes(&krate));
524 if let Some(ref s) = sess.opts.debugging_opts.show_span {
525 syntax::show_span::run(sess.diagnostic(), s, &krate);
528 if sess.opts.debugging_opts.hir_stats {
529 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
535 fn count_nodes(krate: &ast::Crate) -> usize {
536 let mut counter = NodeCounter::new();
537 visit::walk_crate(&mut counter, krate);
541 // For continuing compilation after a parsed crate has been
544 pub struct ExpansionResult {
545 pub expanded_crate: ast::Crate,
546 pub defs: hir_map::Definitions,
547 pub analysis: ty::CrateAnalysis,
548 pub resolutions: Resolutions,
549 pub hir_forest: hir_map::Forest,
552 /// Run the "early phases" of the compiler: initial `cfg` processing,
553 /// loading compiler plugins (including those from `addl_plugins`),
554 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
555 /// harness if one is to be provided, injection of a dependency on the
556 /// standard library and prelude, and name resolution.
558 /// Returns `None` if we're aborting after handling -W help.
559 pub fn phase_2_configure_and_expand<F>(sess: &Session,
562 registry: Option<Registry>,
564 addl_plugins: Option<Vec<String>>,
565 make_glob_map: MakeGlobMap,
567 -> Result<ExpansionResult, CompileIncomplete>
568 where F: FnOnce(&ast::Crate) -> CompileResult,
570 let time_passes = sess.time_passes();
572 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
573 // these need to be set "early" so that expansion sees `quote` if enabled.
574 *sess.features.borrow_mut() = features;
576 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
577 *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
579 time(time_passes, "recursion limit", || {
580 middle::recursion_limit::update_limits(sess, &krate);
583 krate = time(time_passes, "crate injection", || {
584 let alt_std_name = sess.opts.alt_std_name.clone();
585 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
588 let mut addl_plugins = Some(addl_plugins);
589 let registrars = time(time_passes, "plugin loading", || {
590 plugin::load::load_plugins(sess,
594 addl_plugins.take().unwrap())
597 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
599 time(time_passes, "plugin registration", || {
600 if sess.features.borrow().rustc_diagnostic_macros {
601 registry.register_macro("__diagnostic_used",
602 diagnostics::plugin::expand_diagnostic_used);
603 registry.register_macro("__register_diagnostic",
604 diagnostics::plugin::expand_register_diagnostic);
605 registry.register_macro("__build_diagnostic_array",
606 diagnostics::plugin::expand_build_diagnostic_array);
609 for registrar in registrars {
610 registry.args_hidden = Some(registrar.args);
611 (registrar.fun)(&mut registry);
615 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
616 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
617 llvm_passes, attributes, .. } = registry;
619 sess.track_errors(|| {
620 let mut ls = sess.lint_store.borrow_mut();
621 for pass in early_lint_passes {
622 ls.register_early_pass(Some(sess), true, pass);
624 for pass in late_lint_passes {
625 ls.register_late_pass(Some(sess), true, pass);
628 for (name, to) in lint_groups {
629 ls.register_group(Some(sess), true, name, to);
632 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
633 *sess.plugin_attributes.borrow_mut() = attributes.clone();
636 // Lint plugins are registered; now we can process command line flags.
637 if sess.opts.describe_lints {
638 super::describe_lints(&sess.lint_store.borrow(), true);
639 return Err(CompileIncomplete::Stopped);
641 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
643 // Currently, we ignore the name resolution data structures for the purposes of dependency
644 // tracking. Instead we will run name resolution and include its output in the hash of each
645 // item, much like we do for macro expansion. In other words, the hash reflects not just
646 // its contents but the results of name resolution on those contents. Hopefully we'll push
647 // this back at some point.
648 let _ignore = sess.dep_graph.in_ignore();
649 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
650 crate_loader.preprocess(&krate);
651 let resolver_arenas = Resolver::arenas();
652 let mut resolver = Resolver::new(sess,
658 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
659 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
661 krate = time(time_passes, "expansion", || {
662 // Windows dlls do not have rpaths, so they don't know how to find their
663 // dependencies. It's up to us to tell the system where to find all the
664 // dependent dlls. Note that this uses cfg!(windows) as opposed to
665 // targ_cfg because syntax extensions are always loaded for the host
666 // compiler, not for the target.
668 // This is somewhat of an inherently racy operation, however, as
669 // multiple threads calling this function could possibly continue
670 // extending PATH far beyond what it should. To solve this for now we
671 // just don't add any new elements to PATH which are already there
672 // within PATH. This is basically a targeted fix at #17360 for rustdoc
673 // which runs rustc in parallel but has been seen (#33844) to cause
674 // problems with PATH becoming too long.
675 let mut old_path = OsString::new();
677 old_path = env::var_os("PATH").unwrap_or(old_path);
678 let mut new_path = sess.host_filesearch(PathKind::All)
679 .get_dylib_search_paths();
680 for path in env::split_paths(&old_path) {
681 if !new_path.contains(&path) {
686 &env::join_paths(new_path.iter()
687 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
690 let features = sess.features.borrow();
691 let cfg = syntax::ext::expand::ExpansionConfig {
692 features: Some(&features),
693 recursion_limit: sess.recursion_limit.get(),
694 trace_mac: sess.opts.debugging_opts.trace_macros,
695 should_test: sess.opts.test,
696 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
699 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
700 let err_count = ecx.parse_sess.span_diagnostic.err_count();
702 let krate = ecx.monotonic_expander().expand_crate(krate);
704 ecx.check_unused_macros();
706 let mut missing_fragment_specifiers: Vec<_> =
707 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
708 missing_fragment_specifiers.sort();
709 for span in missing_fragment_specifiers {
710 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
711 let msg = "missing fragment specifier".to_string();
712 sess.add_lint(lint, ast::CRATE_NODE_ID, span, msg);
714 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
715 ecx.parse_sess.span_diagnostic.abort_if_errors();
718 env::set_var("PATH", &old_path);
723 krate = time(time_passes, "maybe building test harness", || {
724 syntax::test::modify_for_testing(&sess.parse_sess,
731 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
732 // bunch of checks in the `modify` function below. For now just skip this
733 // step entirely if we're rustdoc as it's not too useful anyway.
734 if !sess.opts.actually_rustdoc {
735 krate = time(time_passes, "maybe creating a macro crate", || {
736 let crate_types = sess.crate_types.borrow();
737 let num_crate_types = crate_types.len();
738 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
739 let is_test_crate = sess.opts.test;
740 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
750 krate = time(time_passes, "creating allocators", || {
751 allocator::expand::modify(&sess.parse_sess,
757 after_expand(&krate)?;
759 if sess.opts.debugging_opts.input_stats {
760 println!("Post-expansion node count: {}", count_nodes(&krate));
763 if sess.opts.debugging_opts.hir_stats {
764 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
767 if sess.opts.debugging_opts.ast_json {
768 println!("{}", json::as_json(&krate));
772 "checking for inline asm in case the target doesn't support it",
773 || no_asm::check_crate(sess, &krate));
777 || lint::check_ast_crate(sess, &krate));
781 || ast_validation::check_crate(sess, &krate));
783 time(time_passes, "name resolution", || -> CompileResult {
784 resolver.resolve_crate(&krate);
788 if resolver.found_unresolved_macro {
789 sess.parse_sess.span_diagnostic.abort_if_errors();
792 // Needs to go *after* expansion to be able to check the results of macro expansion.
793 time(time_passes, "complete gated feature checking", || {
794 sess.track_errors(|| {
795 syntax::feature_gate::check_crate(&krate,
797 &sess.features.borrow(),
799 sess.opts.unstable_features);
804 let hir_forest = time(time_passes, "lowering ast -> hir", || {
805 let hir_crate = lower_crate(sess, &krate, &mut resolver);
807 if sess.opts.debugging_opts.hir_stats {
808 hir_stats::print_hir_stats(&hir_crate);
811 hir_map::Forest::new(hir_crate, &sess.dep_graph)
814 // Discard hygiene data, which isn't required after lowering to HIR.
815 if !keep_hygiene_data(sess) {
816 syntax::ext::hygiene::clear_markings();
820 expanded_crate: krate,
821 defs: resolver.definitions,
822 analysis: ty::CrateAnalysis {
823 access_levels: Rc::new(AccessLevels::default()),
824 reachable: Rc::new(NodeSet()),
825 name: crate_name.to_string(),
826 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
828 resolutions: Resolutions {
829 freevars: resolver.freevars,
830 export_map: resolver.export_map,
831 trait_map: resolver.trait_map,
832 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
834 hir_forest: hir_forest,
838 /// Run the resolution, typechecking, region checking and other
839 /// miscellaneous analysis passes on the crate. Return various
840 /// structures carrying the results of the analysis.
841 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
842 hir_map: hir_map::Map<'tcx>,
843 mut analysis: ty::CrateAnalysis,
844 resolutions: Resolutions,
845 arena: &'tcx DroplessArena,
846 arenas: &'tcx GlobalArenas<'tcx>,
849 -> Result<R, CompileIncomplete>
850 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
852 IncrementalHashesMap,
855 macro_rules! try_with_f {
856 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
860 f($t, $a, $h, Err(x));
867 let time_passes = sess.time_passes();
869 let lang_items = time(time_passes, "language item collection", || {
870 sess.track_errors(|| {
871 middle::lang_items::collect_language_items(&sess, &hir_map)
875 let named_region_map = time(time_passes,
876 "lifetime resolution",
877 || middle::resolve_lifetime::krate(sess, &hir_map))?;
880 "looking for entry point",
881 || middle::entry::find_entry_point(sess, &hir_map));
883 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
884 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
886 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
890 || loops::check_crate(sess, &hir_map));
893 "static item recursion checking",
894 || static_recursion::check_crate(sess, &hir_map))?;
896 let index = stability::Index::new(&sess);
898 let mut local_providers = ty::maps::Providers::default();
899 borrowck::provide(&mut local_providers);
900 mir::provide(&mut local_providers);
901 reachable::provide(&mut local_providers);
902 rustc_privacy::provide(&mut local_providers);
903 trans::provide(&mut local_providers);
904 typeck::provide(&mut local_providers);
905 ty::provide(&mut local_providers);
906 traits::provide(&mut local_providers);
907 reachable::provide(&mut local_providers);
908 rustc_const_eval::provide(&mut local_providers);
909 middle::region::provide(&mut local_providers);
910 cstore::provide_local(&mut local_providers);
912 let mut extern_providers = ty::maps::Providers::default();
913 cstore::provide(&mut extern_providers);
914 trans::provide(&mut extern_providers);
915 ty::provide_extern(&mut extern_providers);
916 traits::provide_extern(&mut extern_providers);
917 // FIXME(eddyb) get rid of this once we replace const_eval with miri.
918 rustc_const_eval::provide(&mut extern_providers);
920 // Setup the MIR passes that we want to run.
921 let mut passes = Passes::new();
922 passes.push_hook(mir::transform::dump_mir::DumpMir);
924 // Remove all `EndRegion` statements that are not involved in borrows.
925 passes.push_pass(MIR_CONST, mir::transform::clean_end_regions::CleanEndRegions);
927 // What we need to do constant evaluation.
928 passes.push_pass(MIR_CONST, mir::transform::simplify::SimplifyCfg::new("initial"));
929 passes.push_pass(MIR_CONST, mir::transform::type_check::TypeckMir);
930 passes.push_pass(MIR_CONST, mir::transform::rustc_peek::SanityCheck);
932 // We compute "constant qualifications" betwen MIR_CONST and MIR_VALIDATED.
934 // What we need to run borrowck etc.
935 passes.push_pass(MIR_VALIDATED, mir::transform::qualify_consts::QualifyAndPromoteConstants);
936 passes.push_pass(MIR_VALIDATED,
937 mir::transform::simplify_branches::SimplifyBranches::new("initial"));
938 passes.push_pass(MIR_VALIDATED, mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
939 passes.push_pass(MIR_VALIDATED, mir::transform::nll::NLL);
941 // borrowck runs between MIR_VALIDATED and MIR_OPTIMIZED.
943 // These next passes must be executed together
944 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
945 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
946 passes.push_pass(MIR_OPTIMIZED, mir::transform::elaborate_drops::ElaborateDrops);
947 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
948 // AddValidation needs to run after ElaborateDrops and before EraseRegions, and it needs
949 // an AllCallEdges pass right before it.
950 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AllCallEdges);
951 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_validation::AddValidation);
952 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
953 // No lifetime analysis based on borrowing can be done from here on out.
955 // From here on out, regions are gone.
956 passes.push_pass(MIR_OPTIMIZED, mir::transform::erase_regions::EraseRegions);
958 // Optimizations begin.
959 passes.push_pass(MIR_OPTIMIZED, mir::transform::inline::Inline);
960 passes.push_pass(MIR_OPTIMIZED, mir::transform::instcombine::InstCombine);
961 passes.push_pass(MIR_OPTIMIZED, mir::transform::deaggregator::Deaggregator);
962 passes.push_pass(MIR_OPTIMIZED, mir::transform::copy_prop::CopyPropagation);
963 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyLocals);
964 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
965 passes.push_pass(MIR_OPTIMIZED, mir::transform::dump_mir::Marker("PreTrans"));
967 TyCtxt::create_and_enter(sess,
980 let incremental_hashes_map =
982 "compute_incremental_hashes_map",
983 || rustc_incremental::compute_incremental_hashes_map(tcx));
987 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
989 time(time_passes, "stability index", || {
990 tcx.stability.borrow_mut().build(tcx)
994 "stability checking",
995 || stability::check_unstable_api_usage(tcx));
997 // passes are timed inside typeck
998 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
1002 || consts::check_crate(tcx));
1004 analysis.access_levels =
1005 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1008 "intrinsic checking",
1009 || middle::intrinsicck::check_crate(tcx));
1013 || middle::effect::check_crate(tcx));
1017 || check_match::check_crate(tcx));
1019 // this must run before MIR dump, because
1020 // "not all control paths return a value" is reported here.
1022 // maybe move the check to a MIR pass?
1024 "liveness checking",
1025 || middle::liveness::check_crate(tcx));
1029 || borrowck::check_crate(tcx));
1031 // Avoid overwhelming user with errors if type checking failed.
1032 // I'm not sure how helpful this is, to be honest, but it avoids
1034 // lot of annoying errors in the compile-fail tests (basically,
1035 // lint warnings and so on -- kindck used to do this abort, but
1036 // kindck is gone now). -nmatsakis
1037 if sess.err_count() > 0 {
1038 return Ok(f(tcx, analysis, incremental_hashes_map, sess.compile_status()));
1041 analysis.reachable =
1043 "reachability checking",
1044 || reachable::find_reachable(tcx));
1046 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1048 time(time_passes, "unused lib feature checking", || {
1049 stability::check_unused_or_stable_features(tcx)
1052 time(time_passes, "lint checking", || lint::check_crate(tcx));
1054 return Ok(f(tcx, analysis, incremental_hashes_map, tcx.sess.compile_status()));
1058 /// Run the translation phase to LLVM, after which the AST and analysis can
1060 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1061 analysis: ty::CrateAnalysis,
1062 incremental_hashes_map: IncrementalHashesMap,
1063 output_filenames: &OutputFilenames)
1064 -> write::OngoingCrateTranslation {
1065 let time_passes = tcx.sess.time_passes();
1068 "resolving dependency formats",
1069 || dependency_format::calculate(tcx));
1074 move || trans::trans_crate(tcx, analysis, incremental_hashes_map, output_filenames));
1079 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1080 /// as a side effect.
1081 pub fn phase_5_run_llvm_passes(sess: &Session,
1082 trans: write::OngoingCrateTranslation)
1083 -> (CompileResult, trans::CrateTranslation) {
1084 let trans = trans.join(sess);
1086 if sess.opts.debugging_opts.incremental_info {
1087 write::dump_incremental_data(&trans);
1090 time(sess.time_passes(),
1091 "serialize work products",
1092 move || rustc_incremental::save_work_products(sess));
1094 (sess.compile_status(), trans)
1097 /// Run the linker on any artifacts that resulted from the LLVM run.
1098 /// This should produce either a finished executable or library.
1099 pub fn phase_6_link_output(sess: &Session,
1100 trans: &trans::CrateTranslation,
1101 outputs: &OutputFilenames) {
1102 time(sess.time_passes(),
1104 || link::link_binary(sess, trans, outputs, &trans.crate_name.as_str()));
1107 fn escape_dep_filename(filename: &str) -> String {
1108 // Apparently clang and gcc *only* escape spaces:
1109 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1110 filename.replace(" ", "\\ ")
1113 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1114 let mut out_filenames = Vec::new();
1115 for output_type in sess.opts.output_types.keys() {
1116 let file = outputs.path(*output_type);
1117 match *output_type {
1118 OutputType::Exe => {
1119 for output in sess.crate_types.borrow().iter() {
1120 let p = link::filename_for_input(sess, *output, crate_name, outputs);
1121 out_filenames.push(p);
1125 out_filenames.push(file);
1130 // Write out dependency rules to the dep-info file if requested
1131 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1134 let deps_filename = outputs.path(OutputType::DepInfo);
1137 (|| -> io::Result<()> {
1138 // Build a list of files used to compile the output and
1139 // write Makefile-compatible dependency rules
1140 let files: Vec<String> = sess.codemap()
1143 .filter(|fmap| fmap.is_real_file())
1144 .filter(|fmap| !fmap.is_imported())
1145 .map(|fmap| escape_dep_filename(&fmap.name))
1147 let mut file = fs::File::create(&deps_filename)?;
1148 for path in &out_filenames {
1149 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1152 // Emit a fake target for each input file to the compilation. This
1153 // prevents `make` from spitting out an error if a file is later
1154 // deleted. For more info see #28735
1156 writeln!(file, "{}:", path)?;
1164 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1165 deps_filename.display(),
1171 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1172 // Unconditionally collect crate types from attributes to make them used
1173 let attr_types: Vec<config::CrateType> =
1176 if a.check_name("crate_type") {
1177 match a.value_str() {
1178 Some(ref n) if *n == "rlib" => {
1179 Some(config::CrateTypeRlib)
1181 Some(ref n) if *n == "dylib" => {
1182 Some(config::CrateTypeDylib)
1184 Some(ref n) if *n == "cdylib" => {
1185 Some(config::CrateTypeCdylib)
1187 Some(ref n) if *n == "lib" => {
1188 Some(config::default_lib_output())
1190 Some(ref n) if *n == "staticlib" => {
1191 Some(config::CrateTypeStaticlib)
1193 Some(ref n) if *n == "proc-macro" => {
1194 Some(config::CrateTypeProcMacro)
1196 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1198 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1201 "invalid `crate_type` value".to_string());
1205 session.struct_span_err(a.span, "`crate_type` requires a value")
1206 .note("for example: `#![crate_type=\"lib\"]`")
1217 // If we're generating a test executable, then ignore all other output
1218 // styles at all other locations
1219 if session.opts.test {
1220 return vec![config::CrateTypeExecutable];
1223 // Only check command line flags if present. If no types are specified by
1224 // command line, then reuse the empty `base` Vec to hold the types that
1225 // will be found in crate attributes.
1226 let mut base = session.opts.crate_types.clone();
1227 if base.is_empty() {
1228 base.extend(attr_types);
1229 if base.is_empty() {
1230 base.push(link::default_output_for_target(session));
1237 .filter(|crate_type| {
1238 let res = !link::invalid_output_for_target(session, *crate_type);
1241 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1243 session.opts.target_triple));
1251 pub fn compute_crate_disambiguator(session: &Session) -> String {
1252 use std::hash::Hasher;
1254 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1255 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1256 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1257 // should still be safe enough to avoid collisions in practice.
1258 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1259 // a hex-string instead of raw bytes. We should really use the
1260 // smaller representation.
1261 let mut hasher = StableHasher::<Fingerprint>::new();
1263 let mut metadata = session.opts.cg.metadata.clone();
1264 // We don't want the crate_disambiguator to dependent on the order
1265 // -C metadata arguments, so sort them:
1267 // Every distinct -C metadata value is only incorporated once:
1270 hasher.write(b"metadata");
1271 for s in &metadata {
1272 // Also incorporate the length of a metadata string, so that we generate
1273 // different values for `-Cmetadata=ab -Cmetadata=c` and
1274 // `-Cmetadata=a -Cmetadata=bc`
1275 hasher.write_usize(s.len());
1276 hasher.write(s.as_bytes());
1279 // If this is an executable, add a special suffix, so that we don't get
1280 // symbol conflicts when linking against a library of the same name.
1281 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1283 format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1286 pub fn build_output_filenames(input: &Input,
1287 odir: &Option<PathBuf>,
1288 ofile: &Option<PathBuf>,
1289 attrs: &[ast::Attribute],
1291 -> OutputFilenames {
1294 // "-" as input file will cause the parser to read from stdin so we
1295 // have to make up a name
1296 // We want to toss everything after the final '.'
1297 let dirpath = match *odir {
1298 Some(ref d) => d.clone(),
1299 None => PathBuf::new(),
1302 // If a crate name is present, we use it as the link name
1303 let stem = sess.opts
1306 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1307 .unwrap_or(input.filestem());
1310 out_directory: dirpath,
1312 single_output_file: None,
1313 extra: sess.opts.cg.extra_filename.clone(),
1314 outputs: sess.opts.output_types.clone(),
1318 Some(ref out_file) => {
1319 let unnamed_output_types = sess.opts
1322 .filter(|a| a.is_none())
1324 let ofile = if unnamed_output_types > 1 {
1325 sess.warn("due to multiple output types requested, the explicitly specified \
1326 output file name will be adapted for each output type");
1329 Some(out_file.clone())
1332 sess.warn("ignoring --out-dir flag due to -o flag.");
1335 let cur_dir = Path::new("");
1338 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1339 out_filestem: out_file.file_stem()
1340 .unwrap_or(OsStr::new(""))
1344 single_output_file: ofile,
1345 extra: sess.opts.cg.extra_filename.clone(),
1346 outputs: sess.opts.output_types.clone(),