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,
20 use rustc::session::search_paths::PathKind;
22 use rustc::middle::{self, dependency_format, stability, reachable};
23 use rustc::middle::privacy::AccessLevels;
24 use rustc::mir::transform::{MIR_CONST, MIR_VALIDATED, MIR_OPTIMIZED, Passes};
25 use rustc::ty::{self, TyCtxt, Resolutions, GlobalArenas};
27 use rustc::util::common::{ErrorReported, time};
28 use rustc::util::nodemap::NodeSet;
29 use rustc::util::fs::rename_or_copy_remove;
30 use rustc_allocator as allocator;
31 use rustc_borrowck as borrowck;
32 use rustc_incremental::{self, IncrementalHashesMap};
33 use rustc_resolve::{MakeGlobMap, Resolver};
34 use rustc_metadata::creader::CrateLoader;
35 use rustc_metadata::cstore::{self, CStore};
36 use rustc_trans::back::{link, write};
37 use rustc_trans as trans;
38 use rustc_typeck as typeck;
40 use rustc_plugin::registry::Registry;
41 use rustc_plugin as plugin;
42 use rustc_passes::{ast_validation, no_asm, loops, consts, static_recursion, hir_stats};
43 use rustc_const_eval::{self, check_match};
44 use super::Compilation;
49 use std::ffi::{OsString, OsStr};
51 use std::io::{self, Write};
53 use std::path::{Path, PathBuf};
55 use syntax::{ast, diagnostics, visit};
57 use syntax::ext::base::ExtCtxt;
58 use syntax::parse::{self, PResult};
59 use syntax::symbol::Symbol;
60 use syntax::util::node_count::NodeCounter;
63 use arena::DroplessArena;
67 pub fn compile_input(sess: &Session,
70 outdir: &Option<PathBuf>,
71 output: &Option<PathBuf>,
72 addl_plugins: Option<Vec<String>>,
73 control: &CompileController) -> CompileResult {
74 macro_rules! controller_entry_point {
75 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
76 let state = &mut $make_state;
77 let phase_result: &CompileResult = &$phase_result;
78 if phase_result.is_ok() || control.$point.run_callback_on_error {
79 (control.$point.callback)(state);
82 if control.$point.stop == Compilation::Stop {
83 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
84 // if there are no errors?
85 return $tsess.compile_status();
90 // We need nested scopes here, because the intermediate results can keep
91 // large chunks of memory alive and we want to free them as soon as
92 // possible to keep the peak memory usage low
93 let (outputs, trans) = {
94 let krate = match phase_1_parse_input(sess, input) {
96 Err(mut parse_error) => {
98 return Err(CompileIncomplete::Errored(ErrorReported));
102 let (krate, registry) = {
103 let mut compile_state = CompileState::state_after_parse(input,
109 controller_entry_point!(after_parse,
114 (compile_state.krate.unwrap(), compile_state.registry)
117 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
118 let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
119 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
120 phase_2_configure_and_expand(
121 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
123 let mut state = CompileState::state_after_expand(
124 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
126 controller_entry_point!(after_expand, sess, state, Ok(()));
132 write_out_deps(sess, &outputs, &crate_name);
133 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
134 sess.opts.output_types.keys().count() == 1 {
138 let arena = DroplessArena::new();
139 let arenas = GlobalArenas::new();
141 // Construct the HIR map
142 let hir_map = time(sess.time_passes(),
144 || hir_map::map_crate(&mut hir_forest, defs));
147 let _ignore = hir_map.dep_graph.in_ignore();
148 controller_entry_point!(after_hir_lowering,
150 CompileState::state_after_hir_lowering(input,
166 time(sess.time_passes(), "attribute checking", || {
167 hir::check_attr::check_crate(sess, &expanded_crate);
170 let opt_crate = if control.keep_ast {
171 Some(&expanded_crate)
173 drop(expanded_crate);
177 phase_3_run_analysis_passes(sess,
184 |tcx, analysis, incremental_hashes_map, result| {
186 // Eventually, we will want to track plugins.
187 let _ignore = tcx.dep_graph.in_ignore();
189 let mut state = CompileState::state_after_analysis(input,
198 (control.after_analysis.callback)(&mut state);
200 if control.after_analysis.stop == Compilation::Stop {
201 return result.and_then(|_| Err(CompileIncomplete::Stopped));
207 if log_enabled!(::log::LogLevel::Info) {
208 println!("Pre-trans");
209 tcx.print_debug_stats();
211 let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map,
214 if log_enabled!(::log::LogLevel::Info) {
215 println!("Post-trans");
216 tcx.print_debug_stats();
219 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
220 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
221 sess.err(&format!("could not emit MIR: {}", e));
222 sess.abort_if_errors();
230 if sess.opts.debugging_opts.print_type_sizes {
231 sess.code_stats.borrow().print_type_sizes();
234 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
236 controller_entry_point!(after_llvm,
238 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
242 write::cleanup_llvm(&trans);
244 phase_6_link_output(sess, &trans, &outputs);
246 // Now that we won't touch anything in the incremental compilation directory
247 // any more, we can finalize it (which involves renaming it)
248 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
250 if sess.opts.debugging_opts.perf_stats {
251 sess.print_perf_stats();
254 controller_entry_point!(compilation_done,
256 CompileState::state_when_compilation_done(input, sess, outdir, output),
262 fn keep_hygiene_data(sess: &Session) -> bool {
263 sess.opts.debugging_opts.keep_hygiene_data
267 /// The name used for source code that doesn't originate in a file
268 /// (e.g. source from stdin or a string)
269 pub fn anon_src() -> String {
273 pub fn source_name(input: &Input) -> String {
275 // FIXME (#9639): This needs to handle non-utf8 paths
276 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
277 Input::Str { ref name, .. } => name.clone(),
281 /// CompileController is used to customise compilation, it allows compilation to
282 /// be stopped and/or to call arbitrary code at various points in compilation.
283 /// It also allows for various flags to be set to influence what information gets
284 /// collected during compilation.
286 /// This is a somewhat higher level controller than a Session - the Session
287 /// controls what happens in each phase, whereas the CompileController controls
288 /// whether a phase is run at all and whether other code (from outside the
289 /// the compiler) is run between phases.
291 /// Note that if compilation is set to stop and a callback is provided for a
292 /// given entry point, the callback is called before compilation is stopped.
294 /// Expect more entry points to be added in the future.
295 pub struct CompileController<'a> {
296 pub after_parse: PhaseController<'a>,
297 pub after_expand: PhaseController<'a>,
298 pub after_hir_lowering: PhaseController<'a>,
299 pub after_analysis: PhaseController<'a>,
300 pub after_llvm: PhaseController<'a>,
301 pub compilation_done: PhaseController<'a>,
303 pub make_glob_map: MakeGlobMap,
304 // Whether the compiler should keep the ast beyond parsing.
308 impl<'a> CompileController<'a> {
309 pub fn basic() -> CompileController<'a> {
311 after_parse: PhaseController::basic(),
312 after_expand: PhaseController::basic(),
313 after_hir_lowering: PhaseController::basic(),
314 after_analysis: PhaseController::basic(),
315 after_llvm: PhaseController::basic(),
316 compilation_done: PhaseController::basic(),
317 make_glob_map: MakeGlobMap::No,
323 pub struct PhaseController<'a> {
324 pub stop: Compilation,
325 // If true then the compiler will try to run the callback even if the phase
326 // ends with an error. Note that this is not always possible.
327 pub run_callback_on_error: bool,
328 pub callback: Box<Fn(&mut CompileState) + 'a>,
331 impl<'a> PhaseController<'a> {
332 pub fn basic() -> PhaseController<'a> {
334 stop: Compilation::Continue,
335 run_callback_on_error: false,
336 callback: box |_| {},
341 /// State that is passed to a callback. What state is available depends on when
342 /// during compilation the callback is made. See the various constructor methods
343 /// (`state_*`) in the impl to see which data is provided for any given entry point.
344 pub struct CompileState<'a, 'tcx: 'a> {
345 pub input: &'a Input,
346 pub session: &'tcx Session,
347 pub krate: Option<ast::Crate>,
348 pub registry: Option<Registry<'a>>,
349 pub cstore: Option<&'a CStore>,
350 pub crate_name: Option<&'a str>,
351 pub output_filenames: Option<&'a OutputFilenames>,
352 pub out_dir: Option<&'a Path>,
353 pub out_file: Option<&'a Path>,
354 pub arena: Option<&'tcx DroplessArena>,
355 pub arenas: Option<&'tcx GlobalArenas<'tcx>>,
356 pub expanded_crate: Option<&'a ast::Crate>,
357 pub hir_crate: Option<&'a hir::Crate>,
358 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
359 pub resolutions: Option<&'a Resolutions>,
360 pub analysis: Option<&'a ty::CrateAnalysis>,
361 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
362 pub trans: Option<&'a trans::CrateTranslation>,
365 impl<'a, 'tcx> CompileState<'a, 'tcx> {
366 fn empty(input: &'a Input,
367 session: &'tcx Session,
368 out_dir: &'a Option<PathBuf>)
373 out_dir: out_dir.as_ref().map(|s| &**s),
381 output_filenames: None,
382 expanded_crate: None,
392 fn state_after_parse(input: &'a Input,
393 session: &'tcx Session,
394 out_dir: &'a Option<PathBuf>,
395 out_file: &'a Option<PathBuf>,
400 // Initialize the registry before moving `krate`
401 registry: Some(Registry::new(&session, krate.span)),
403 cstore: Some(cstore),
404 out_file: out_file.as_ref().map(|s| &**s),
405 ..CompileState::empty(input, session, out_dir)
409 fn state_after_expand(input: &'a Input,
410 session: &'tcx Session,
411 out_dir: &'a Option<PathBuf>,
412 out_file: &'a Option<PathBuf>,
414 expanded_crate: &'a ast::Crate,
418 crate_name: Some(crate_name),
419 cstore: Some(cstore),
420 expanded_crate: Some(expanded_crate),
421 out_file: out_file.as_ref().map(|s| &**s),
422 ..CompileState::empty(input, session, out_dir)
426 fn state_after_hir_lowering(input: &'a Input,
427 session: &'tcx Session,
428 out_dir: &'a Option<PathBuf>,
429 out_file: &'a Option<PathBuf>,
430 arena: &'tcx DroplessArena,
431 arenas: &'tcx GlobalArenas<'tcx>,
433 hir_map: &'a hir_map::Map<'tcx>,
434 analysis: &'a ty::CrateAnalysis,
435 resolutions: &'a Resolutions,
436 krate: &'a ast::Crate,
437 hir_crate: &'a hir::Crate,
441 crate_name: Some(crate_name),
443 arenas: Some(arenas),
444 cstore: Some(cstore),
445 hir_map: Some(hir_map),
446 analysis: Some(analysis),
447 resolutions: Some(resolutions),
448 expanded_crate: Some(krate),
449 hir_crate: Some(hir_crate),
450 out_file: out_file.as_ref().map(|s| &**s),
451 ..CompileState::empty(input, session, out_dir)
455 fn state_after_analysis(input: &'a Input,
456 session: &'tcx Session,
457 out_dir: &'a Option<PathBuf>,
458 out_file: &'a Option<PathBuf>,
459 krate: Option<&'a ast::Crate>,
460 hir_crate: &'a hir::Crate,
461 analysis: &'a ty::CrateAnalysis,
462 tcx: TyCtxt<'a, 'tcx, 'tcx>,
466 analysis: Some(analysis),
468 expanded_crate: krate,
469 hir_crate: Some(hir_crate),
470 crate_name: Some(crate_name),
471 out_file: out_file.as_ref().map(|s| &**s),
472 ..CompileState::empty(input, session, out_dir)
477 fn state_after_llvm(input: &'a Input,
478 session: &'tcx Session,
479 out_dir: &'a Option<PathBuf>,
480 out_file: &'a Option<PathBuf>,
481 trans: &'a trans::CrateTranslation)
485 out_file: out_file.as_ref().map(|s| &**s),
486 ..CompileState::empty(input, session, out_dir)
490 fn state_when_compilation_done(input: &'a Input,
491 session: &'tcx Session,
492 out_dir: &'a Option<PathBuf>,
493 out_file: &'a Option<PathBuf>)
496 out_file: out_file.as_ref().map(|s| &**s),
497 ..CompileState::empty(input, session, out_dir)
502 pub fn phase_1_parse_input<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
503 let continue_after_error = sess.opts.debugging_opts.continue_parse_after_error;
504 sess.diagnostic().set_continue_after_error(continue_after_error);
506 let krate = time(sess.time_passes(), "parsing", || {
508 Input::File(ref file) => {
509 parse::parse_crate_from_file(file, &sess.parse_sess)
511 Input::Str { ref input, ref name } => {
512 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
517 sess.diagnostic().set_continue_after_error(true);
519 if sess.opts.debugging_opts.ast_json_noexpand {
520 println!("{}", json::as_json(&krate));
523 if sess.opts.debugging_opts.input_stats {
524 println!("Lines of code: {}", sess.codemap().count_lines());
525 println!("Pre-expansion node count: {}", count_nodes(&krate));
528 if let Some(ref s) = sess.opts.debugging_opts.show_span {
529 syntax::show_span::run(sess.diagnostic(), s, &krate);
532 if sess.opts.debugging_opts.hir_stats {
533 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
539 fn count_nodes(krate: &ast::Crate) -> usize {
540 let mut counter = NodeCounter::new();
541 visit::walk_crate(&mut counter, krate);
545 // For continuing compilation after a parsed crate has been
548 pub struct ExpansionResult {
549 pub expanded_crate: ast::Crate,
550 pub defs: hir_map::Definitions,
551 pub analysis: ty::CrateAnalysis,
552 pub resolutions: Resolutions,
553 pub hir_forest: hir_map::Forest,
556 /// Run the "early phases" of the compiler: initial `cfg` processing,
557 /// loading compiler plugins (including those from `addl_plugins`),
558 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
559 /// harness if one is to be provided, injection of a dependency on the
560 /// standard library and prelude, and name resolution.
562 /// Returns `None` if we're aborting after handling -W help.
563 pub fn phase_2_configure_and_expand<F>(sess: &Session,
566 registry: Option<Registry>,
568 addl_plugins: Option<Vec<String>>,
569 make_glob_map: MakeGlobMap,
571 -> Result<ExpansionResult, CompileIncomplete>
572 where F: FnOnce(&ast::Crate) -> CompileResult,
574 let time_passes = sess.time_passes();
576 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
577 // these need to be set "early" so that expansion sees `quote` if enabled.
578 *sess.features.borrow_mut() = features;
580 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
581 *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
583 time(time_passes, "recursion limit", || {
584 middle::recursion_limit::update_limits(sess, &krate);
587 krate = time(time_passes, "crate injection", || {
588 let alt_std_name = sess.opts.alt_std_name.clone();
589 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
592 let mut addl_plugins = Some(addl_plugins);
593 let registrars = time(time_passes, "plugin loading", || {
594 plugin::load::load_plugins(sess,
598 addl_plugins.take().unwrap())
601 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
603 time(time_passes, "plugin registration", || {
604 if sess.features.borrow().rustc_diagnostic_macros {
605 registry.register_macro("__diagnostic_used",
606 diagnostics::plugin::expand_diagnostic_used);
607 registry.register_macro("__register_diagnostic",
608 diagnostics::plugin::expand_register_diagnostic);
609 registry.register_macro("__build_diagnostic_array",
610 diagnostics::plugin::expand_build_diagnostic_array);
613 for registrar in registrars {
614 registry.args_hidden = Some(registrar.args);
615 (registrar.fun)(&mut registry);
619 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
620 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
621 llvm_passes, attributes, .. } = registry;
623 sess.track_errors(|| {
624 let mut ls = sess.lint_store.borrow_mut();
625 for pass in early_lint_passes {
626 ls.register_early_pass(Some(sess), true, pass);
628 for pass in late_lint_passes {
629 ls.register_late_pass(Some(sess), true, pass);
632 for (name, to) in lint_groups {
633 ls.register_group(Some(sess), true, name, to);
636 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
637 *sess.plugin_attributes.borrow_mut() = attributes.clone();
640 // Lint plugins are registered; now we can process command line flags.
641 if sess.opts.describe_lints {
642 super::describe_lints(&sess.lint_store.borrow(), true);
643 return Err(CompileIncomplete::Stopped);
645 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
647 // Currently, we ignore the name resolution data structures for the purposes of dependency
648 // tracking. Instead we will run name resolution and include its output in the hash of each
649 // item, much like we do for macro expansion. In other words, the hash reflects not just
650 // its contents but the results of name resolution on those contents. Hopefully we'll push
651 // this back at some point.
652 let _ignore = sess.dep_graph.in_ignore();
653 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
654 crate_loader.preprocess(&krate);
655 let resolver_arenas = Resolver::arenas();
656 let mut resolver = Resolver::new(sess,
662 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
663 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
665 krate = time(time_passes, "expansion", || {
666 // Windows dlls do not have rpaths, so they don't know how to find their
667 // dependencies. It's up to us to tell the system where to find all the
668 // dependent dlls. Note that this uses cfg!(windows) as opposed to
669 // targ_cfg because syntax extensions are always loaded for the host
670 // compiler, not for the target.
672 // This is somewhat of an inherently racy operation, however, as
673 // multiple threads calling this function could possibly continue
674 // extending PATH far beyond what it should. To solve this for now we
675 // just don't add any new elements to PATH which are already there
676 // within PATH. This is basically a targeted fix at #17360 for rustdoc
677 // which runs rustc in parallel but has been seen (#33844) to cause
678 // problems with PATH becoming too long.
679 let mut old_path = OsString::new();
681 old_path = env::var_os("PATH").unwrap_or(old_path);
682 let mut new_path = sess.host_filesearch(PathKind::All)
683 .get_dylib_search_paths();
684 for path in env::split_paths(&old_path) {
685 if !new_path.contains(&path) {
690 &env::join_paths(new_path.iter()
691 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
694 let features = sess.features.borrow();
695 let cfg = syntax::ext::expand::ExpansionConfig {
696 features: Some(&features),
697 recursion_limit: sess.recursion_limit.get(),
698 trace_mac: sess.opts.debugging_opts.trace_macros,
699 should_test: sess.opts.test,
700 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
703 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
704 let err_count = ecx.parse_sess.span_diagnostic.err_count();
706 let krate = ecx.monotonic_expander().expand_crate(krate);
708 ecx.check_unused_macros();
710 let mut missing_fragment_specifiers: Vec<_> =
711 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
712 missing_fragment_specifiers.sort();
713 for span in missing_fragment_specifiers {
714 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
715 let msg = "missing fragment specifier".to_string();
716 sess.add_lint(lint, ast::CRATE_NODE_ID, span, msg);
718 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
719 ecx.parse_sess.span_diagnostic.abort_if_errors();
722 env::set_var("PATH", &old_path);
727 krate = time(time_passes, "maybe building test harness", || {
728 syntax::test::modify_for_testing(&sess.parse_sess,
735 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
736 // bunch of checks in the `modify` function below. For now just skip this
737 // step entirely if we're rustdoc as it's not too useful anyway.
738 if !sess.opts.actually_rustdoc {
739 krate = time(time_passes, "maybe creating a macro crate", || {
740 let crate_types = sess.crate_types.borrow();
741 let num_crate_types = crate_types.len();
742 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
743 let is_test_crate = sess.opts.test;
744 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
754 krate = time(time_passes, "creating allocators", || {
755 allocator::expand::modify(&sess.parse_sess,
761 after_expand(&krate)?;
763 if sess.opts.debugging_opts.input_stats {
764 println!("Post-expansion node count: {}", count_nodes(&krate));
767 if sess.opts.debugging_opts.hir_stats {
768 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
771 if sess.opts.debugging_opts.ast_json {
772 println!("{}", json::as_json(&krate));
776 "checking for inline asm in case the target doesn't support it",
777 || no_asm::check_crate(sess, &krate));
781 || lint::check_ast_crate(sess, &krate));
785 || ast_validation::check_crate(sess, &krate));
787 time(time_passes, "name resolution", || -> CompileResult {
788 resolver.resolve_crate(&krate);
792 if resolver.found_unresolved_macro {
793 sess.parse_sess.span_diagnostic.abort_if_errors();
796 // Needs to go *after* expansion to be able to check the results of macro expansion.
797 time(time_passes, "complete gated feature checking", || {
798 sess.track_errors(|| {
799 syntax::feature_gate::check_crate(&krate,
801 &sess.features.borrow(),
803 sess.opts.unstable_features);
808 let hir_forest = time(time_passes, "lowering ast -> hir", || {
809 let hir_crate = lower_crate(sess, &krate, &mut resolver);
811 if sess.opts.debugging_opts.hir_stats {
812 hir_stats::print_hir_stats(&hir_crate);
815 hir_map::Forest::new(hir_crate, &sess.dep_graph)
818 // Discard hygiene data, which isn't required after lowering to HIR.
819 if !keep_hygiene_data(sess) {
820 syntax::ext::hygiene::clear_markings();
824 expanded_crate: krate,
825 defs: resolver.definitions,
826 analysis: ty::CrateAnalysis {
827 access_levels: Rc::new(AccessLevels::default()),
828 reachable: Rc::new(NodeSet()),
829 name: crate_name.to_string(),
830 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
832 resolutions: Resolutions {
833 freevars: resolver.freevars,
834 export_map: resolver.export_map,
835 trait_map: resolver.trait_map,
836 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
838 hir_forest: hir_forest,
842 /// Run the resolution, typechecking, region checking and other
843 /// miscellaneous analysis passes on the crate. Return various
844 /// structures carrying the results of the analysis.
845 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
846 hir_map: hir_map::Map<'tcx>,
847 mut analysis: ty::CrateAnalysis,
848 resolutions: Resolutions,
849 arena: &'tcx DroplessArena,
850 arenas: &'tcx GlobalArenas<'tcx>,
853 -> Result<R, CompileIncomplete>
854 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
856 IncrementalHashesMap,
859 macro_rules! try_with_f {
860 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
864 f($t, $a, $h, Err(x));
871 let time_passes = sess.time_passes();
873 let lang_items = time(time_passes, "language item collection", || {
874 sess.track_errors(|| {
875 middle::lang_items::collect_language_items(&sess, &hir_map)
879 let named_region_map = time(time_passes,
880 "lifetime resolution",
881 || middle::resolve_lifetime::krate(sess, &hir_map))?;
884 "looking for entry point",
885 || middle::entry::find_entry_point(sess, &hir_map));
887 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
888 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
890 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
894 || loops::check_crate(sess, &hir_map));
897 "static item recursion checking",
898 || static_recursion::check_crate(sess, &hir_map))?;
900 let index = stability::Index::new(&sess);
902 let mut local_providers = ty::maps::Providers::default();
903 borrowck::provide(&mut local_providers);
904 mir::provide(&mut local_providers);
905 reachable::provide(&mut local_providers);
906 rustc_privacy::provide(&mut local_providers);
907 trans::provide(&mut local_providers);
908 typeck::provide(&mut local_providers);
909 ty::provide(&mut local_providers);
910 traits::provide(&mut local_providers);
911 reachable::provide(&mut local_providers);
912 rustc_const_eval::provide(&mut local_providers);
913 middle::region::provide(&mut local_providers);
914 cstore::provide_local(&mut local_providers);
916 let mut extern_providers = ty::maps::Providers::default();
917 cstore::provide(&mut extern_providers);
918 trans::provide(&mut extern_providers);
919 ty::provide_extern(&mut extern_providers);
920 traits::provide_extern(&mut extern_providers);
921 // FIXME(eddyb) get rid of this once we replace const_eval with miri.
922 rustc_const_eval::provide(&mut extern_providers);
924 // Setup the MIR passes that we want to run.
925 let mut passes = Passes::new();
926 passes.push_hook(mir::transform::dump_mir::DumpMir);
928 // Remove all `EndRegion` statements that are not involved in borrows.
929 passes.push_pass(MIR_CONST, mir::transform::clean_end_regions::CleanEndRegions);
931 // What we need to do constant evaluation.
932 passes.push_pass(MIR_CONST, mir::transform::simplify::SimplifyCfg::new("initial"));
933 passes.push_pass(MIR_CONST, mir::transform::type_check::TypeckMir);
934 passes.push_pass(MIR_CONST, mir::transform::rustc_peek::SanityCheck);
936 // We compute "constant qualifications" betwen MIR_CONST and MIR_VALIDATED.
938 // What we need to run borrowck etc.
939 passes.push_pass(MIR_VALIDATED, mir::transform::qualify_consts::QualifyAndPromoteConstants);
940 passes.push_pass(MIR_VALIDATED,
941 mir::transform::simplify_branches::SimplifyBranches::new("initial"));
942 passes.push_pass(MIR_VALIDATED, mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
943 passes.push_pass(MIR_VALIDATED, mir::transform::nll::NLL);
945 // borrowck runs between MIR_VALIDATED and MIR_OPTIMIZED.
947 // These next passes must be executed together
948 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
949 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AddCallGuards);
950 passes.push_pass(MIR_OPTIMIZED, mir::transform::elaborate_drops::ElaborateDrops);
951 passes.push_pass(MIR_OPTIMIZED, mir::transform::no_landing_pads::NoLandingPads);
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 // AddValidation needs to run after ElaborateDrops and before EraseRegions.
956 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_validation::AddValidation);
958 // From here on out, regions are gone.
959 passes.push_pass(MIR_OPTIMIZED, mir::transform::erase_regions::EraseRegions);
961 // Optimizations begin.
962 passes.push_pass(MIR_OPTIMIZED, mir::transform::inline::Inline);
963 passes.push_pass(MIR_OPTIMIZED, mir::transform::instcombine::InstCombine);
964 passes.push_pass(MIR_OPTIMIZED, mir::transform::deaggregator::Deaggregator);
965 passes.push_pass(MIR_OPTIMIZED, mir::transform::copy_prop::CopyPropagation);
966 passes.push_pass(MIR_OPTIMIZED, mir::transform::simplify::SimplifyLocals);
967 passes.push_pass(MIR_OPTIMIZED, mir::transform::add_call_guards::AddCallGuards);
968 passes.push_pass(MIR_OPTIMIZED, mir::transform::dump_mir::Marker("PreTrans"));
970 TyCtxt::create_and_enter(sess,
983 let incremental_hashes_map =
985 "compute_incremental_hashes_map",
986 || rustc_incremental::compute_incremental_hashes_map(tcx));
990 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
992 time(time_passes, "stability index", || {
993 tcx.stability.borrow_mut().build(tcx)
997 "stability checking",
998 || stability::check_unstable_api_usage(tcx));
1000 // passes are timed inside typeck
1001 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
1005 || consts::check_crate(tcx));
1007 analysis.access_levels =
1008 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1011 "intrinsic checking",
1012 || middle::intrinsicck::check_crate(tcx));
1016 || middle::effect::check_crate(tcx));
1020 || check_match::check_crate(tcx));
1022 // this must run before MIR dump, because
1023 // "not all control paths return a value" is reported here.
1025 // maybe move the check to a MIR pass?
1027 "liveness checking",
1028 || middle::liveness::check_crate(tcx));
1032 || borrowck::check_crate(tcx));
1034 // Avoid overwhelming user with errors if type checking failed.
1035 // I'm not sure how helpful this is, to be honest, but it avoids
1037 // lot of annoying errors in the compile-fail tests (basically,
1038 // lint warnings and so on -- kindck used to do this abort, but
1039 // kindck is gone now). -nmatsakis
1040 if sess.err_count() > 0 {
1041 return Ok(f(tcx, analysis, incremental_hashes_map, sess.compile_status()));
1044 analysis.reachable =
1046 "reachability checking",
1047 || reachable::find_reachable(tcx));
1049 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1051 time(time_passes, "unused lib feature checking", || {
1052 stability::check_unused_or_stable_features(tcx)
1055 time(time_passes, "lint checking", || lint::check_crate(tcx));
1057 return Ok(f(tcx, analysis, incremental_hashes_map, tcx.sess.compile_status()));
1061 /// Run the translation phase to LLVM, after which the AST and analysis can
1063 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1064 analysis: ty::CrateAnalysis,
1065 incremental_hashes_map: &IncrementalHashesMap,
1066 output_filenames: &OutputFilenames)
1067 -> trans::CrateTranslation {
1068 let time_passes = tcx.sess.time_passes();
1071 "resolving dependency formats",
1072 || dependency_format::calculate(tcx));
1077 move || trans::trans_crate(tcx, analysis, &incremental_hashes_map, output_filenames));
1081 || rustc_incremental::assert_dep_graph(tcx));
1084 "serialize dep graph",
1085 || rustc_incremental::save_dep_graph(tcx,
1086 &incremental_hashes_map,
1087 &translation.metadata.hashes,
1088 translation.link.crate_hash));
1092 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1093 /// as a side effect.
1094 pub fn phase_5_run_llvm_passes(sess: &Session,
1095 trans: &trans::CrateTranslation,
1096 outputs: &OutputFilenames) -> CompileResult {
1097 if sess.opts.cg.no_integrated_as ||
1098 (sess.target.target.options.no_integrated_as &&
1099 (outputs.outputs.contains_key(&OutputType::Object) ||
1100 outputs.outputs.contains_key(&OutputType::Exe)))
1102 let output_types = OutputTypes::new(&[(OutputType::Assembly, None)]);
1103 time(sess.time_passes(),
1105 || write::run_passes(sess, trans, &output_types, outputs));
1107 write::run_assembler(sess, outputs);
1109 // HACK the linker expects the object file to be named foo.0.o but
1110 // `run_assembler` produces an object named just foo.o. Rename it if we
1111 // are going to build an executable
1112 if sess.opts.output_types.contains_key(&OutputType::Exe) {
1113 let f = outputs.path(OutputType::Object);
1114 rename_or_copy_remove(&f,
1115 f.with_file_name(format!("{}.0.o",
1116 f.file_stem().unwrap().to_string_lossy()))).unwrap();
1119 // Remove assembly source, unless --save-temps was specified
1120 if !sess.opts.cg.save_temps {
1121 fs::remove_file(&outputs.temp_path(OutputType::Assembly, None)).unwrap();
1124 time(sess.time_passes(),
1126 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1129 time(sess.time_passes(),
1130 "serialize work products",
1131 move || rustc_incremental::save_work_products(sess));
1133 sess.compile_status()
1136 /// Run the linker on any artifacts that resulted from the LLVM run.
1137 /// This should produce either a finished executable or library.
1138 pub fn phase_6_link_output(sess: &Session,
1139 trans: &trans::CrateTranslation,
1140 outputs: &OutputFilenames) {
1141 time(sess.time_passes(),
1143 || link::link_binary(sess, trans, outputs, &trans.crate_name.as_str()));
1146 fn escape_dep_filename(filename: &str) -> String {
1147 // Apparently clang and gcc *only* escape spaces:
1148 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1149 filename.replace(" ", "\\ ")
1152 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1153 let mut out_filenames = Vec::new();
1154 for output_type in sess.opts.output_types.keys() {
1155 let file = outputs.path(*output_type);
1156 match *output_type {
1157 OutputType::Exe => {
1158 for output in sess.crate_types.borrow().iter() {
1159 let p = link::filename_for_input(sess, *output, crate_name, outputs);
1160 out_filenames.push(p);
1164 out_filenames.push(file);
1169 // Write out dependency rules to the dep-info file if requested
1170 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1173 let deps_filename = outputs.path(OutputType::DepInfo);
1176 (|| -> io::Result<()> {
1177 // Build a list of files used to compile the output and
1178 // write Makefile-compatible dependency rules
1179 let files: Vec<String> = sess.codemap()
1182 .filter(|fmap| fmap.is_real_file())
1183 .filter(|fmap| !fmap.is_imported())
1184 .map(|fmap| escape_dep_filename(&fmap.name))
1186 let mut file = fs::File::create(&deps_filename)?;
1187 for path in &out_filenames {
1188 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1191 // Emit a fake target for each input file to the compilation. This
1192 // prevents `make` from spitting out an error if a file is later
1193 // deleted. For more info see #28735
1195 writeln!(file, "{}:", path)?;
1203 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1204 deps_filename.display(),
1210 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1211 // Unconditionally collect crate types from attributes to make them used
1212 let attr_types: Vec<config::CrateType> =
1215 if a.check_name("crate_type") {
1216 match a.value_str() {
1217 Some(ref n) if *n == "rlib" => {
1218 Some(config::CrateTypeRlib)
1220 Some(ref n) if *n == "dylib" => {
1221 Some(config::CrateTypeDylib)
1223 Some(ref n) if *n == "cdylib" => {
1224 Some(config::CrateTypeCdylib)
1226 Some(ref n) if *n == "lib" => {
1227 Some(config::default_lib_output())
1229 Some(ref n) if *n == "staticlib" => {
1230 Some(config::CrateTypeStaticlib)
1232 Some(ref n) if *n == "proc-macro" => {
1233 Some(config::CrateTypeProcMacro)
1235 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1237 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1240 "invalid `crate_type` value".to_string());
1244 session.struct_span_err(a.span, "`crate_type` requires a value")
1245 .note("for example: `#![crate_type=\"lib\"]`")
1256 // If we're generating a test executable, then ignore all other output
1257 // styles at all other locations
1258 if session.opts.test {
1259 return vec![config::CrateTypeExecutable];
1262 // Only check command line flags if present. If no types are specified by
1263 // command line, then reuse the empty `base` Vec to hold the types that
1264 // will be found in crate attributes.
1265 let mut base = session.opts.crate_types.clone();
1266 if base.is_empty() {
1267 base.extend(attr_types);
1268 if base.is_empty() {
1269 base.push(link::default_output_for_target(session));
1276 .filter(|crate_type| {
1277 let res = !link::invalid_output_for_target(session, *crate_type);
1280 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1282 session.opts.target_triple));
1290 pub fn compute_crate_disambiguator(session: &Session) -> String {
1291 use std::hash::Hasher;
1293 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1294 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1295 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1296 // should still be safe enough to avoid collisions in practice.
1297 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1298 // a hex-string instead of raw bytes. We should really use the
1299 // smaller representation.
1300 let mut hasher = StableHasher::<Fingerprint>::new();
1302 let mut metadata = session.opts.cg.metadata.clone();
1303 // We don't want the crate_disambiguator to dependent on the order
1304 // -C metadata arguments, so sort them:
1306 // Every distinct -C metadata value is only incorporated once:
1309 hasher.write(b"metadata");
1310 for s in &metadata {
1311 // Also incorporate the length of a metadata string, so that we generate
1312 // different values for `-Cmetadata=ab -Cmetadata=c` and
1313 // `-Cmetadata=a -Cmetadata=bc`
1314 hasher.write_usize(s.len());
1315 hasher.write(s.as_bytes());
1318 // If this is an executable, add a special suffix, so that we don't get
1319 // symbol conflicts when linking against a library of the same name.
1320 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1322 format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1325 pub fn build_output_filenames(input: &Input,
1326 odir: &Option<PathBuf>,
1327 ofile: &Option<PathBuf>,
1328 attrs: &[ast::Attribute],
1330 -> OutputFilenames {
1333 // "-" as input file will cause the parser to read from stdin so we
1334 // have to make up a name
1335 // We want to toss everything after the final '.'
1336 let dirpath = match *odir {
1337 Some(ref d) => d.clone(),
1338 None => PathBuf::new(),
1341 // If a crate name is present, we use it as the link name
1342 let stem = sess.opts
1345 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1346 .unwrap_or(input.filestem());
1349 out_directory: dirpath,
1351 single_output_file: None,
1352 extra: sess.opts.cg.extra_filename.clone(),
1353 outputs: sess.opts.output_types.clone(),
1357 Some(ref out_file) => {
1358 let unnamed_output_types = sess.opts
1361 .filter(|a| a.is_none())
1363 let ofile = if unnamed_output_types > 1 {
1364 sess.warn("due to multiple output types requested, the explicitly specified \
1365 output file name will be adapted for each output type");
1368 Some(out_file.clone())
1371 sess.warn("ignoring --out-dir flag due to -o flag.");
1374 let cur_dir = Path::new("");
1377 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1378 out_filestem: out_file.file_stem()
1379 .unwrap_or(OsStr::new(""))
1383 single_output_file: ofile,
1384 extra: sess.opts.cg.extra_filename.clone(),
1385 outputs: sess.opts.output_types.clone(),