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 #![cfg_attr(not(feature="llvm"), allow(dead_code))]
13 use rustc::hir::{self, map as hir_map};
14 use rustc::hir::lowering::lower_crate;
15 use rustc::ich::Fingerprint;
16 use rustc_data_structures::stable_hasher::StableHasher;
18 use rustc::session::{Session, CompileResult};
19 use rustc::session::CompileIncomplete;
20 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
21 use rustc::session::search_paths::PathKind;
23 use rustc::middle::{self, stability, reachable};
24 use rustc::middle::cstore::CrateStore;
25 use rustc::middle::privacy::AccessLevels;
26 use rustc::mir::transform::{MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED, Passes};
27 use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
29 use rustc::util::common::{ErrorReported, time};
30 use rustc::util::nodemap::NodeSet;
31 use rustc_allocator as allocator;
32 use rustc_borrowck as borrowck;
33 use rustc_incremental::{self, IncrementalHashesMap};
34 use rustc_resolve::{MakeGlobMap, Resolver};
35 use rustc_metadata::creader::CrateLoader;
36 use rustc_metadata::cstore::{self, CStore};
37 use rustc_trans::back::write;
38 use rustc_trans as trans;
39 use rustc_typeck as typeck;
41 use rustc_plugin::registry::Registry;
42 use rustc_plugin as plugin;
43 use rustc_passes::{ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
44 use rustc_const_eval::{self, check_match};
45 use super::Compilation;
50 use std::ffi::{OsString, OsStr};
52 use std::io::{self, Write};
54 use std::path::{Path, PathBuf};
56 use syntax::{ast, diagnostics, visit};
58 use syntax::ext::base::ExtCtxt;
59 use syntax::parse::{self, PResult};
60 use syntax::symbol::Symbol;
61 use syntax::util::node_count::NodeCounter;
64 use arena::DroplessArena;
70 pub fn compile_input(sess: &Session,
73 outdir: &Option<PathBuf>,
74 output: &Option<PathBuf>,
75 addl_plugins: Option<Vec<String>>,
76 control: &CompileController) -> CompileResult {
77 use rustc_trans::back::write::OngoingCrateTranslation;
78 macro_rules! controller_entry_point {
79 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
80 let state = &mut $make_state;
81 let phase_result: &CompileResult = &$phase_result;
82 if phase_result.is_ok() || control.$point.run_callback_on_error {
83 (control.$point.callback)(state);
86 if control.$point.stop == Compilation::Stop {
87 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
88 // if there are no errors?
89 return $tsess.compile_status();
94 if cfg!(not(feature="llvm")) {
95 use rustc::session::config::CrateType;
96 if !sess.opts.debugging_opts.no_trans && sess.opts.output_types.should_trans() {
97 sess.err("LLVM is not supported by this rustc. Please use -Z no-trans to compile")
100 if sess.opts.crate_types.iter().all(|&t|{
101 t != CrateType::CrateTypeRlib && t != CrateType::CrateTypeExecutable
102 }) && !sess.opts.crate_types.is_empty() {
104 "LLVM is not supported by this rustc, so non rlib libraries are not supported"
108 sess.abort_if_errors();
111 if sess.profile_queries() {
115 // We need nested scopes here, because the intermediate results can keep
116 // large chunks of memory alive and we want to free them as soon as
117 // possible to keep the peak memory usage low
118 let (outputs, trans): (OutputFilenames, OngoingCrateTranslation) = {
119 let krate = match phase_1_parse_input(control, sess, input) {
121 Err(mut parse_error) => {
123 return Err(CompileIncomplete::Errored(ErrorReported));
127 let (krate, registry) = {
128 let mut compile_state = CompileState::state_after_parse(input,
134 controller_entry_point!(after_parse,
139 (compile_state.krate.unwrap(), compile_state.registry)
142 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
144 ::rustc_trans_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
145 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
146 phase_2_configure_and_expand(
147 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
149 let mut state = CompileState::state_after_expand(
150 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
152 controller_entry_point!(after_expand, sess, state, Ok(()));
158 write_out_deps(sess, &outputs, &crate_name);
159 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
160 sess.opts.output_types.keys().count() == 1 {
164 let arena = DroplessArena::new();
165 let arenas = GlobalArenas::new();
167 // Construct the HIR map
168 let hir_map = time(sess.time_passes(),
170 || hir_map::map_crate(&mut hir_forest, defs));
173 let _ignore = hir_map.dep_graph.in_ignore();
174 controller_entry_point!(after_hir_lowering,
176 CompileState::state_after_hir_lowering(input,
192 time(sess.time_passes(), "attribute checking", || {
193 hir::check_attr::check_crate(sess, &expanded_crate);
196 let opt_crate = if control.keep_ast {
197 Some(&expanded_crate)
199 drop(expanded_crate);
203 phase_3_run_analysis_passes(sess,
211 |tcx, analysis, incremental_hashes_map, result| {
213 // Eventually, we will want to track plugins.
214 let _ignore = tcx.dep_graph.in_ignore();
216 let mut state = CompileState::state_after_analysis(input,
225 (control.after_analysis.callback)(&mut state);
227 if control.after_analysis.stop == Compilation::Stop {
228 return result.and_then(|_| Err(CompileIncomplete::Stopped));
234 if log_enabled!(::log::LogLevel::Info) {
235 println!("Pre-trans");
236 tcx.print_debug_stats();
239 let trans = phase_4_translate_to_llvm(tcx, analysis, incremental_hashes_map,
242 if log_enabled!(::log::LogLevel::Info) {
243 println!("Post-trans");
244 tcx.print_debug_stats();
247 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
248 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
249 sess.err(&format!("could not emit MIR: {}", e));
250 sess.abort_if_errors();
258 if cfg!(not(feature="llvm")) {
259 let (_, _) = (outputs, trans);
260 sess.fatal("LLVM is not supported by this rustc");
263 #[cfg(feature="llvm")]
265 if sess.opts.debugging_opts.print_type_sizes {
266 sess.code_stats.borrow().print_type_sizes();
269 let (phase5_result, trans) = phase_5_run_llvm_passes(sess, trans);
271 controller_entry_point!(after_llvm,
273 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
277 phase_6_link_output(sess, &trans, &outputs);
279 // Now that we won't touch anything in the incremental compilation directory
280 // any more, we can finalize it (which involves renaming it)
281 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
283 if sess.opts.debugging_opts.perf_stats {
284 sess.print_perf_stats();
287 controller_entry_point!(
290 CompileState::state_when_compilation_done(input, sess, outdir, output),
298 fn keep_hygiene_data(sess: &Session) -> bool {
299 sess.opts.debugging_opts.keep_hygiene_data
303 /// The name used for source code that doesn't originate in a file
304 /// (e.g. source from stdin or a string)
305 pub fn anon_src() -> String {
309 pub fn source_name(input: &Input) -> String {
311 // FIXME (#9639): This needs to handle non-utf8 paths
312 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
313 Input::Str { ref name, .. } => name.clone(),
317 /// CompileController is used to customize compilation, it allows compilation to
318 /// be stopped and/or to call arbitrary code at various points in compilation.
319 /// It also allows for various flags to be set to influence what information gets
320 /// collected during compilation.
322 /// This is a somewhat higher level controller than a Session - the Session
323 /// controls what happens in each phase, whereas the CompileController controls
324 /// whether a phase is run at all and whether other code (from outside the
325 /// compiler) is run between phases.
327 /// Note that if compilation is set to stop and a callback is provided for a
328 /// given entry point, the callback is called before compilation is stopped.
330 /// Expect more entry points to be added in the future.
331 pub struct CompileController<'a> {
332 pub after_parse: PhaseController<'a>,
333 pub after_expand: PhaseController<'a>,
334 pub after_hir_lowering: PhaseController<'a>,
335 pub after_analysis: PhaseController<'a>,
336 pub after_llvm: PhaseController<'a>,
337 pub compilation_done: PhaseController<'a>,
339 // FIXME we probably want to group the below options together and offer a
340 // better API, rather than this ad-hoc approach.
341 pub make_glob_map: MakeGlobMap,
342 // Whether the compiler should keep the ast beyond parsing.
344 // -Zcontinue-parse-after-error
345 pub continue_parse_after_error: bool,
348 impl<'a> CompileController<'a> {
349 pub fn basic() -> CompileController<'a> {
351 after_parse: PhaseController::basic(),
352 after_expand: PhaseController::basic(),
353 after_hir_lowering: PhaseController::basic(),
354 after_analysis: PhaseController::basic(),
355 after_llvm: PhaseController::basic(),
356 compilation_done: PhaseController::basic(),
357 make_glob_map: MakeGlobMap::No,
359 continue_parse_after_error: false,
364 pub struct PhaseController<'a> {
365 pub stop: Compilation,
366 // If true then the compiler will try to run the callback even if the phase
367 // ends with an error. Note that this is not always possible.
368 pub run_callback_on_error: bool,
369 pub callback: Box<Fn(&mut CompileState) + 'a>,
372 impl<'a> PhaseController<'a> {
373 pub fn basic() -> PhaseController<'a> {
375 stop: Compilation::Continue,
376 run_callback_on_error: false,
377 callback: box |_| {},
382 /// State that is passed to a callback. What state is available depends on when
383 /// during compilation the callback is made. See the various constructor methods
384 /// (`state_*`) in the impl to see which data is provided for any given entry point.
385 pub struct CompileState<'a, 'tcx: 'a> {
386 pub input: &'a Input,
387 pub session: &'tcx Session,
388 pub krate: Option<ast::Crate>,
389 pub registry: Option<Registry<'a>>,
390 pub cstore: Option<&'tcx CStore>,
391 pub crate_name: Option<&'a str>,
392 pub output_filenames: Option<&'a OutputFilenames>,
393 pub out_dir: Option<&'a Path>,
394 pub out_file: Option<&'a Path>,
395 pub arena: Option<&'tcx DroplessArena>,
396 pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
397 pub expanded_crate: Option<&'a ast::Crate>,
398 pub hir_crate: Option<&'a hir::Crate>,
399 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
400 pub resolutions: Option<&'a Resolutions>,
401 pub analysis: Option<&'a ty::CrateAnalysis>,
402 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
403 pub trans: Option<&'a trans::CrateTranslation>,
406 impl<'a, 'tcx> CompileState<'a, 'tcx> {
407 fn empty(input: &'a Input,
408 session: &'tcx Session,
409 out_dir: &'a Option<PathBuf>)
414 out_dir: out_dir.as_ref().map(|s| &**s),
422 output_filenames: None,
423 expanded_crate: None,
433 fn state_after_parse(input: &'a Input,
434 session: &'tcx Session,
435 out_dir: &'a Option<PathBuf>,
436 out_file: &'a Option<PathBuf>,
438 cstore: &'tcx CStore)
441 // Initialize the registry before moving `krate`
442 registry: Some(Registry::new(&session, krate.span)),
444 cstore: Some(cstore),
445 out_file: out_file.as_ref().map(|s| &**s),
446 ..CompileState::empty(input, session, out_dir)
450 fn state_after_expand(input: &'a Input,
451 session: &'tcx Session,
452 out_dir: &'a Option<PathBuf>,
453 out_file: &'a Option<PathBuf>,
454 cstore: &'tcx CStore,
455 expanded_crate: &'a ast::Crate,
459 crate_name: Some(crate_name),
460 cstore: Some(cstore),
461 expanded_crate: Some(expanded_crate),
462 out_file: out_file.as_ref().map(|s| &**s),
463 ..CompileState::empty(input, session, out_dir)
467 fn state_after_hir_lowering(input: &'a Input,
468 session: &'tcx Session,
469 out_dir: &'a Option<PathBuf>,
470 out_file: &'a Option<PathBuf>,
471 arena: &'tcx DroplessArena,
472 arenas: &'tcx GlobalArenas<'tcx>,
473 cstore: &'tcx CStore,
474 hir_map: &'a hir_map::Map<'tcx>,
475 analysis: &'a ty::CrateAnalysis,
476 resolutions: &'a Resolutions,
477 krate: &'a ast::Crate,
478 hir_crate: &'a hir::Crate,
482 crate_name: Some(crate_name),
484 arenas: Some(arenas),
485 cstore: Some(cstore),
486 hir_map: Some(hir_map),
487 analysis: Some(analysis),
488 resolutions: Some(resolutions),
489 expanded_crate: Some(krate),
490 hir_crate: Some(hir_crate),
491 out_file: out_file.as_ref().map(|s| &**s),
492 ..CompileState::empty(input, session, out_dir)
496 fn state_after_analysis(input: &'a Input,
497 session: &'tcx Session,
498 out_dir: &'a Option<PathBuf>,
499 out_file: &'a Option<PathBuf>,
500 krate: Option<&'a ast::Crate>,
501 hir_crate: &'a hir::Crate,
502 analysis: &'a ty::CrateAnalysis,
503 tcx: TyCtxt<'a, 'tcx, 'tcx>,
507 analysis: Some(analysis),
509 expanded_crate: krate,
510 hir_crate: Some(hir_crate),
511 crate_name: Some(crate_name),
512 out_file: out_file.as_ref().map(|s| &**s),
513 ..CompileState::empty(input, session, out_dir)
517 fn state_after_llvm(input: &'a Input,
518 session: &'tcx Session,
519 out_dir: &'a Option<PathBuf>,
520 out_file: &'a Option<PathBuf>,
521 trans: &'a trans::CrateTranslation)
525 out_file: out_file.as_ref().map(|s| &**s),
526 ..CompileState::empty(input, session, out_dir)
530 fn state_when_compilation_done(input: &'a Input,
531 session: &'tcx Session,
532 out_dir: &'a Option<PathBuf>,
533 out_file: &'a Option<PathBuf>)
536 out_file: out_file.as_ref().map(|s| &**s),
537 ..CompileState::empty(input, session, out_dir)
542 pub fn phase_1_parse_input<'a>(control: &CompileController,
545 -> PResult<'a, ast::Crate> {
546 sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
548 if sess.profile_queries() {
552 let krate = time(sess.time_passes(), "parsing", || {
554 Input::File(ref file) => {
555 parse::parse_crate_from_file(file, &sess.parse_sess)
557 Input::Str { ref input, ref name } => {
558 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
563 sess.diagnostic().set_continue_after_error(true);
565 if sess.opts.debugging_opts.ast_json_noexpand {
566 println!("{}", json::as_json(&krate));
569 if sess.opts.debugging_opts.input_stats {
570 println!("Lines of code: {}", sess.codemap().count_lines());
571 println!("Pre-expansion node count: {}", count_nodes(&krate));
574 if let Some(ref s) = sess.opts.debugging_opts.show_span {
575 syntax::show_span::run(sess.diagnostic(), s, &krate);
578 if sess.opts.debugging_opts.hir_stats {
579 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
585 fn count_nodes(krate: &ast::Crate) -> usize {
586 let mut counter = NodeCounter::new();
587 visit::walk_crate(&mut counter, krate);
591 // For continuing compilation after a parsed crate has been
594 pub struct ExpansionResult {
595 pub expanded_crate: ast::Crate,
596 pub defs: hir_map::Definitions,
597 pub analysis: ty::CrateAnalysis,
598 pub resolutions: Resolutions,
599 pub hir_forest: hir_map::Forest,
602 /// Run the "early phases" of the compiler: initial `cfg` processing,
603 /// loading compiler plugins (including those from `addl_plugins`),
604 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
605 /// harness if one is to be provided, injection of a dependency on the
606 /// standard library and prelude, and name resolution.
608 /// Returns `None` if we're aborting after handling -W help.
609 pub fn phase_2_configure_and_expand<F>(sess: &Session,
612 registry: Option<Registry>,
614 addl_plugins: Option<Vec<String>>,
615 make_glob_map: MakeGlobMap,
617 -> Result<ExpansionResult, CompileIncomplete>
618 where F: FnOnce(&ast::Crate) -> CompileResult,
620 let time_passes = sess.time_passes();
622 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
623 // these need to be set "early" so that expansion sees `quote` if enabled.
624 *sess.features.borrow_mut() = features;
626 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
627 *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
629 time(time_passes, "recursion limit", || {
630 middle::recursion_limit::update_limits(sess, &krate);
633 krate = time(time_passes, "crate injection", || {
634 let alt_std_name = sess.opts.alt_std_name.clone();
635 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
638 let mut addl_plugins = Some(addl_plugins);
639 let registrars = time(time_passes, "plugin loading", || {
640 plugin::load::load_plugins(sess,
644 addl_plugins.take().unwrap())
647 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
649 time(time_passes, "plugin registration", || {
650 if sess.features.borrow().rustc_diagnostic_macros {
651 registry.register_macro("__diagnostic_used",
652 diagnostics::plugin::expand_diagnostic_used);
653 registry.register_macro("__register_diagnostic",
654 diagnostics::plugin::expand_register_diagnostic);
655 registry.register_macro("__build_diagnostic_array",
656 diagnostics::plugin::expand_build_diagnostic_array);
659 for registrar in registrars {
660 registry.args_hidden = Some(registrar.args);
661 (registrar.fun)(&mut registry);
665 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
666 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
667 llvm_passes, attributes, .. } = registry;
669 sess.track_errors(|| {
670 let mut ls = sess.lint_store.borrow_mut();
671 for pass in early_lint_passes {
672 ls.register_early_pass(Some(sess), true, pass);
674 for pass in late_lint_passes {
675 ls.register_late_pass(Some(sess), true, pass);
678 for (name, to) in lint_groups {
679 ls.register_group(Some(sess), true, name, to);
682 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
683 *sess.plugin_attributes.borrow_mut() = attributes.clone();
686 // Lint plugins are registered; now we can process command line flags.
687 if sess.opts.describe_lints {
688 super::describe_lints(&sess.lint_store.borrow(), true);
689 return Err(CompileIncomplete::Stopped);
692 // Currently, we ignore the name resolution data structures for the purposes of dependency
693 // tracking. Instead we will run name resolution and include its output in the hash of each
694 // item, much like we do for macro expansion. In other words, the hash reflects not just
695 // its contents but the results of name resolution on those contents. Hopefully we'll push
696 // this back at some point.
697 let _ignore = sess.dep_graph.in_ignore();
698 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
699 let resolver_arenas = Resolver::arenas();
700 let mut resolver = Resolver::new(sess,
707 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
708 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
710 krate = time(time_passes, "expansion", || {
711 // Windows dlls do not have rpaths, so they don't know how to find their
712 // dependencies. It's up to us to tell the system where to find all the
713 // dependent dlls. Note that this uses cfg!(windows) as opposed to
714 // targ_cfg because syntax extensions are always loaded for the host
715 // compiler, not for the target.
717 // This is somewhat of an inherently racy operation, however, as
718 // multiple threads calling this function could possibly continue
719 // extending PATH far beyond what it should. To solve this for now we
720 // just don't add any new elements to PATH which are already there
721 // within PATH. This is basically a targeted fix at #17360 for rustdoc
722 // which runs rustc in parallel but has been seen (#33844) to cause
723 // problems with PATH becoming too long.
724 let mut old_path = OsString::new();
726 old_path = env::var_os("PATH").unwrap_or(old_path);
727 let mut new_path = sess.host_filesearch(PathKind::All)
728 .get_dylib_search_paths();
729 for path in env::split_paths(&old_path) {
730 if !new_path.contains(&path) {
735 &env::join_paths(new_path.iter()
736 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
739 let features = sess.features.borrow();
740 let cfg = syntax::ext::expand::ExpansionConfig {
741 features: Some(&features),
742 recursion_limit: sess.recursion_limit.get(),
743 trace_mac: sess.opts.debugging_opts.trace_macros,
744 should_test: sess.opts.test,
745 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
748 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
749 let err_count = ecx.parse_sess.span_diagnostic.err_count();
751 let krate = ecx.monotonic_expander().expand_crate(krate);
753 ecx.check_unused_macros();
755 let mut missing_fragment_specifiers: Vec<_> =
756 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
757 missing_fragment_specifiers.sort();
758 for span in missing_fragment_specifiers {
759 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
760 let msg = "missing fragment specifier";
761 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
763 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
764 ecx.parse_sess.span_diagnostic.abort_if_errors();
767 env::set_var("PATH", &old_path);
772 krate = time(time_passes, "maybe building test harness", || {
773 syntax::test::modify_for_testing(&sess.parse_sess,
780 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
781 // bunch of checks in the `modify` function below. For now just skip this
782 // step entirely if we're rustdoc as it's not too useful anyway.
783 if !sess.opts.actually_rustdoc {
784 krate = time(time_passes, "maybe creating a macro crate", || {
785 let crate_types = sess.crate_types.borrow();
786 let num_crate_types = crate_types.len();
787 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
788 let is_test_crate = sess.opts.test;
789 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
799 krate = time(time_passes, "creating allocators", || {
800 allocator::expand::modify(&sess.parse_sess,
806 after_expand(&krate)?;
808 if sess.opts.debugging_opts.input_stats {
809 println!("Post-expansion node count: {}", count_nodes(&krate));
812 if sess.opts.debugging_opts.hir_stats {
813 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
816 if sess.opts.debugging_opts.ast_json {
817 println!("{}", json::as_json(&krate));
821 "checking for inline asm in case the target doesn't support it",
822 || no_asm::check_crate(sess, &krate));
826 || ast_validation::check_crate(sess, &krate));
828 time(time_passes, "name resolution", || -> CompileResult {
829 resolver.resolve_crate(&krate);
833 if resolver.found_unresolved_macro {
834 sess.parse_sess.span_diagnostic.abort_if_errors();
837 // Needs to go *after* expansion to be able to check the results of macro expansion.
838 time(time_passes, "complete gated feature checking", || {
839 sess.track_errors(|| {
840 syntax::feature_gate::check_crate(&krate,
842 &sess.features.borrow(),
844 sess.opts.unstable_features);
849 let hir_forest = time(time_passes, "lowering ast -> hir", || {
850 let hir_crate = lower_crate(sess, cstore, &krate, &mut resolver);
852 if sess.opts.debugging_opts.hir_stats {
853 hir_stats::print_hir_stats(&hir_crate);
856 hir_map::Forest::new(hir_crate, &sess.dep_graph)
861 || lint::check_ast_crate(sess, &krate));
863 // Discard hygiene data, which isn't required after lowering to HIR.
864 if !keep_hygiene_data(sess) {
865 syntax::ext::hygiene::clear_markings();
869 expanded_crate: krate,
870 defs: resolver.definitions,
871 analysis: ty::CrateAnalysis {
872 access_levels: Rc::new(AccessLevels::default()),
873 reachable: Rc::new(NodeSet()),
874 name: crate_name.to_string(),
875 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
877 resolutions: Resolutions {
878 freevars: resolver.freevars,
879 export_map: resolver.export_map,
880 trait_map: resolver.trait_map,
881 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
882 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
888 /// Run the resolution, typechecking, region checking and other
889 /// miscellaneous analysis passes on the crate. Return various
890 /// structures carrying the results of the analysis.
891 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
892 cstore: &'tcx CrateStore,
893 hir_map: hir_map::Map<'tcx>,
894 mut analysis: ty::CrateAnalysis,
895 resolutions: Resolutions,
896 arena: &'tcx DroplessArena,
897 arenas: &'tcx GlobalArenas<'tcx>,
900 -> Result<R, CompileIncomplete>
901 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
903 IncrementalHashesMap,
906 macro_rules! try_with_f {
907 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
911 f($t, $a, $h, Err(x));
918 let time_passes = sess.time_passes();
920 let named_region_map = time(time_passes,
921 "lifetime resolution",
922 || middle::resolve_lifetime::krate(sess, cstore, &hir_map))?;
925 "looking for entry point",
926 || middle::entry::find_entry_point(sess, &hir_map));
928 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
929 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
931 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
935 || loops::check_crate(sess, &hir_map));
938 "static item recursion checking",
939 || static_recursion::check_crate(sess, &hir_map))?;
941 let mut local_providers = ty::maps::Providers::default();
942 borrowck::provide(&mut local_providers);
943 mir::provide(&mut local_providers);
944 reachable::provide(&mut local_providers);
945 rustc_privacy::provide(&mut local_providers);
946 trans::provide(&mut local_providers);
947 typeck::provide(&mut local_providers);
948 ty::provide(&mut local_providers);
949 traits::provide(&mut local_providers);
950 reachable::provide(&mut local_providers);
951 rustc_const_eval::provide(&mut local_providers);
952 middle::region::provide(&mut local_providers);
953 cstore::provide_local(&mut local_providers);
954 lint::provide(&mut local_providers);
956 let mut extern_providers = ty::maps::Providers::default();
957 cstore::provide(&mut extern_providers);
958 trans::provide(&mut extern_providers);
959 ty::provide_extern(&mut extern_providers);
960 traits::provide_extern(&mut extern_providers);
961 // FIXME(eddyb) get rid of this once we replace const_eval with miri.
962 rustc_const_eval::provide(&mut extern_providers);
964 // Setup the MIR passes that we want to run.
965 let mut passes = Passes::new();
966 passes.push_hook(mir::transform::dump_mir::DumpMir);
968 // Remove all `EndRegion` statements that are not involved in borrows.
969 passes.push_pass(MIR_CONST, mir::transform::clean_end_regions::CleanEndRegions);
971 // What we need to do constant evaluation.
972 passes.push_pass(MIR_CONST, mir::transform::simplify::SimplifyCfg::new("initial"));
973 passes.push_pass(MIR_CONST, mir::transform::type_check::TypeckMir);
974 passes.push_pass(MIR_CONST, mir::transform::rustc_peek::SanityCheck);
976 // We compute "constant qualifications" between MIR_CONST and MIR_VALIDATED.
978 // What we need to run borrowck etc.
980 passes.push_pass(MIR_VALIDATED, mir::transform::qualify_consts::QualifyAndPromoteConstants);
982 // FIXME: ariel points SimplifyBranches should run after
983 // mir-borrowck; otherwise code within `if false { ... }` would
985 passes.push_pass(MIR_VALIDATED,
986 mir::transform::simplify_branches::SimplifyBranches::new("initial"));
987 passes.push_pass(MIR_VALIDATED, mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
988 passes.push_pass(MIR_VALIDATED, mir::transform::nll::NLL);
990 // borrowck runs between MIR_VALIDATED and MIR_OPTIMIZED.
992 // These next passes must be executed together
993 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
994 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
995 passes.push_pass(MIR_OPTIMIZED, mir::transform::elaborate_drops::ElaborateDrops);
996 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
997 // AddValidation needs to run after ElaborateDrops and before EraseRegions, and it needs
998 // an AllCallEdges pass right before it.
999 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AllCallEdges);
1000 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_validation::AddValidation);
1001 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
1002 // No lifetime analysis based on borrowing can be done from here on out.
1004 // From here on out, regions are gone.
1005 passes.push_pass(MIR_OPTIMIZED, mir::transform::erase_regions::EraseRegions);
1007 // Optimizations begin.
1008 passes.push_pass(MIR_OPTIMIZED, mir::transform::inline::Inline);
1009 passes.push_pass(MIR_OPTIMIZED, mir::transform::instcombine::InstCombine);
1010 passes.push_pass(MIR_OPTIMIZED, mir::transform::deaggregator::Deaggregator);
1011 passes.push_pass(MIR_OPTIMIZED, mir::transform::copy_prop::CopyPropagation);
1012 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyLocals);
1014 passes.push_pass(MIR_OPTIMIZED, mir::transform::generator::StateTransform);
1015 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::CriticalCallEdges);
1016 passes.push_pass(MIR_OPTIMIZED, mir::transform::dump_mir::Marker("PreTrans"));
1018 TyCtxt::create_and_enter(sess,
1030 let incremental_hashes_map =
1032 "compute_incremental_hashes_map",
1033 || rustc_incremental::compute_incremental_hashes_map(tcx));
1037 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
1040 "stability checking",
1041 || stability::check_unstable_api_usage(tcx));
1043 // passes are timed inside typeck
1044 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
1048 || consts::check_crate(tcx));
1050 analysis.access_levels =
1051 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1054 "intrinsic checking",
1055 || middle::intrinsicck::check_crate(tcx));
1059 || middle::effect::check_crate(tcx));
1063 || check_match::check_crate(tcx));
1065 // this must run before MIR dump, because
1066 // "not all control paths return a value" is reported here.
1068 // maybe move the check to a MIR pass?
1070 "liveness checking",
1071 || middle::liveness::check_crate(tcx));
1075 || borrowck::check_crate(tcx));
1078 "MIR borrow checking",
1079 || for def_id in tcx.body_owners() { tcx.mir_borrowck(def_id) });
1081 // Avoid overwhelming user with errors if type checking failed.
1082 // I'm not sure how helpful this is, to be honest, but it avoids
1084 // lot of annoying errors in the compile-fail tests (basically,
1085 // lint warnings and so on -- kindck used to do this abort, but
1086 // kindck is gone now). -nmatsakis
1087 if sess.err_count() > 0 {
1088 return Ok(f(tcx, analysis, incremental_hashes_map, sess.compile_status()));
1091 analysis.reachable =
1093 "reachability checking",
1094 || reachable::find_reachable(tcx));
1096 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1098 time(time_passes, "unused lib feature checking", || {
1099 stability::check_unused_or_stable_features(tcx)
1102 time(time_passes, "lint checking", || lint::check_crate(tcx));
1104 return Ok(f(tcx, analysis, incremental_hashes_map, tcx.sess.compile_status()));
1108 /// Run the translation phase to LLVM, after which the AST and analysis can
1110 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1111 analysis: ty::CrateAnalysis,
1112 incremental_hashes_map: IncrementalHashesMap,
1113 output_filenames: &OutputFilenames)
1114 -> write::OngoingCrateTranslation {
1115 let time_passes = tcx.sess.time_passes();
1118 "resolving dependency formats",
1119 || ::rustc::middle::dependency_format::calculate(tcx));
1124 move || trans::trans_crate(tcx, analysis, incremental_hashes_map, output_filenames));
1126 if tcx.sess.profile_queries() {
1127 profile::dump("profile_queries".to_string())
1133 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1134 /// as a side effect.
1135 #[cfg(feature="llvm")]
1136 pub fn phase_5_run_llvm_passes(sess: &Session,
1137 trans: write::OngoingCrateTranslation)
1138 -> (CompileResult, trans::CrateTranslation) {
1139 let trans = trans.join(sess);
1141 if sess.opts.debugging_opts.incremental_info {
1142 write::dump_incremental_data(&trans);
1145 time(sess.time_passes(),
1146 "serialize work products",
1147 move || rustc_incremental::save_work_products(sess));
1149 (sess.compile_status(), trans)
1152 /// Run the linker on any artifacts that resulted from the LLVM run.
1153 /// This should produce either a finished executable or library.
1154 #[cfg(feature="llvm")]
1155 pub fn phase_6_link_output(sess: &Session,
1156 trans: &trans::CrateTranslation,
1157 outputs: &OutputFilenames) {
1158 time(sess.time_passes(), "linking", || {
1159 ::rustc_trans::back::link::link_binary(sess,
1162 &trans.crate_name.as_str())
1166 fn escape_dep_filename(filename: &str) -> String {
1167 // Apparently clang and gcc *only* escape spaces:
1168 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1169 filename.replace(" ", "\\ ")
1172 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1173 let mut out_filenames = Vec::new();
1174 for output_type in sess.opts.output_types.keys() {
1175 let file = outputs.path(*output_type);
1176 match *output_type {
1177 OutputType::Exe => {
1178 for output in sess.crate_types.borrow().iter() {
1179 let p = ::rustc_trans_utils::link::filename_for_input(
1185 out_filenames.push(p);
1189 out_filenames.push(file);
1194 // Write out dependency rules to the dep-info file if requested
1195 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1198 let deps_filename = outputs.path(OutputType::DepInfo);
1201 (|| -> io::Result<()> {
1202 // Build a list of files used to compile the output and
1203 // write Makefile-compatible dependency rules
1204 let files: Vec<String> = sess.codemap()
1207 .filter(|fmap| fmap.is_real_file())
1208 .filter(|fmap| !fmap.is_imported())
1209 .map(|fmap| escape_dep_filename(&fmap.name))
1211 let mut file = fs::File::create(&deps_filename)?;
1212 for path in &out_filenames {
1213 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1216 // Emit a fake target for each input file to the compilation. This
1217 // prevents `make` from spitting out an error if a file is later
1218 // deleted. For more info see #28735
1220 writeln!(file, "{}:", path)?;
1228 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1229 deps_filename.display(),
1235 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1236 // Unconditionally collect crate types from attributes to make them used
1237 let attr_types: Vec<config::CrateType> =
1240 if a.check_name("crate_type") {
1241 match a.value_str() {
1242 Some(ref n) if *n == "rlib" => {
1243 Some(config::CrateTypeRlib)
1245 Some(ref n) if *n == "dylib" => {
1246 Some(config::CrateTypeDylib)
1248 Some(ref n) if *n == "cdylib" => {
1249 Some(config::CrateTypeCdylib)
1251 Some(ref n) if *n == "lib" => {
1252 Some(config::default_lib_output())
1254 Some(ref n) if *n == "staticlib" => {
1255 Some(config::CrateTypeStaticlib)
1257 Some(ref n) if *n == "proc-macro" => {
1258 Some(config::CrateTypeProcMacro)
1260 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1262 session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1265 "invalid `crate_type` value");
1269 session.struct_span_err(a.span, "`crate_type` requires a value")
1270 .note("for example: `#![crate_type=\"lib\"]`")
1281 // If we're generating a test executable, then ignore all other output
1282 // styles at all other locations
1283 if session.opts.test {
1284 return vec![config::CrateTypeExecutable];
1287 // Only check command line flags if present. If no types are specified by
1288 // command line, then reuse the empty `base` Vec to hold the types that
1289 // will be found in crate attributes.
1290 let mut base = session.opts.crate_types.clone();
1291 if base.is_empty() {
1292 base.extend(attr_types);
1293 if base.is_empty() {
1294 base.push(::rustc_trans_utils::link::default_output_for_target(session));
1301 .filter(|crate_type| {
1302 let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1305 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1307 session.opts.target_triple));
1315 pub fn compute_crate_disambiguator(session: &Session) -> String {
1316 use std::hash::Hasher;
1318 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1319 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1320 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1321 // should still be safe enough to avoid collisions in practice.
1322 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1323 // a hex-string instead of raw bytes. We should really use the
1324 // smaller representation.
1325 let mut hasher = StableHasher::<Fingerprint>::new();
1327 let mut metadata = session.opts.cg.metadata.clone();
1328 // We don't want the crate_disambiguator to dependent on the order
1329 // -C metadata arguments, so sort them:
1331 // Every distinct -C metadata value is only incorporated once:
1334 hasher.write(b"metadata");
1335 for s in &metadata {
1336 // Also incorporate the length of a metadata string, so that we generate
1337 // different values for `-Cmetadata=ab -Cmetadata=c` and
1338 // `-Cmetadata=a -Cmetadata=bc`
1339 hasher.write_usize(s.len());
1340 hasher.write(s.as_bytes());
1343 // If this is an executable, add a special suffix, so that we don't get
1344 // symbol conflicts when linking against a library of the same name.
1345 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1347 format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1350 pub fn build_output_filenames(input: &Input,
1351 odir: &Option<PathBuf>,
1352 ofile: &Option<PathBuf>,
1353 attrs: &[ast::Attribute],
1355 -> OutputFilenames {
1358 // "-" as input file will cause the parser to read from stdin so we
1359 // have to make up a name
1360 // We want to toss everything after the final '.'
1361 let dirpath = match *odir {
1362 Some(ref d) => d.clone(),
1363 None => PathBuf::new(),
1366 // If a crate name is present, we use it as the link name
1367 let stem = sess.opts
1370 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1371 .unwrap_or(input.filestem());
1374 out_directory: dirpath,
1376 single_output_file: None,
1377 extra: sess.opts.cg.extra_filename.clone(),
1378 outputs: sess.opts.output_types.clone(),
1382 Some(ref out_file) => {
1383 let unnamed_output_types = sess.opts
1386 .filter(|a| a.is_none())
1388 let ofile = if unnamed_output_types > 1 {
1389 sess.warn("due to multiple output types requested, the explicitly specified \
1390 output file name will be adapted for each output type");
1393 Some(out_file.clone())
1396 sess.warn("ignoring --out-dir flag due to -o flag.");
1399 let cur_dir = Path::new("");
1402 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1403 out_filestem: out_file.file_stem()
1404 .unwrap_or(OsStr::new(""))
1408 single_output_file: ofile,
1409 extra: sess.opts.cg.extra_filename.clone(),
1410 outputs: sess.opts.output_types.clone(),