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::dep_graph::DepGraph;
13 use rustc::hir::{map as hir_map, FreevarMap, TraitMap};
14 use rustc::hir::def::DefMap;
15 use rustc::hir::lowering::lower_crate;
17 use rustc::mir::mir_map::MirMap;
18 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
19 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::ty::{self, TyCtxt};
25 use rustc::util::common::time;
26 use rustc::util::nodemap::NodeSet;
27 use rustc_back::sha2::{Sha256, Digest};
28 use rustc_borrowck as borrowck;
29 use rustc_incremental;
30 use rustc_resolve as resolve;
31 use rustc_metadata::macro_import;
32 use rustc_metadata::creader::read_local_crates;
33 use rustc_metadata::cstore::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, rvalues, static_recursion};
41 use rustc_const_eval::check_match;
42 use super::Compilation;
46 use std::collections::HashMap;
48 use std::ffi::{OsString, OsStr};
50 use std::io::{self, Write};
51 use std::path::{Path, PathBuf};
52 use syntax::ast::{self, NodeIdAssigner};
53 use syntax::attr::{self, AttrMetaMethods};
54 use syntax::diagnostics;
55 use syntax::fold::Folder;
56 use syntax::parse::{self, PResult, token};
57 use syntax::util::node_count::NodeCounter;
63 pub struct Resolutions {
65 pub freevars: FreevarMap,
66 pub trait_map: TraitMap,
67 pub maybe_unused_trait_imports: NodeSet,
70 pub fn compile_input(sess: &Session,
72 cfg: ast::CrateConfig,
74 outdir: &Option<PathBuf>,
75 output: &Option<PathBuf>,
76 addl_plugins: Option<Vec<String>>,
77 control: &CompileController) -> CompileResult {
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 return compile_result_from_err_count($tsess.err_count());
92 // We need nested scopes here, because the intermediate results can keep
93 // large chunks of memory alive and we want to free them as soon as
94 // possible to keep the peak memory usage low
95 let (outputs, trans) = {
96 let krate = match phase_1_parse_input(sess, cfg, input) {
98 Err(mut parse_error) => {
105 let mut compile_state = CompileState::state_after_parse(input,
111 controller_entry_point!(after_parse,
116 compile_state.krate.unwrap()
119 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
120 let id = link::find_crate_name(Some(sess), &krate.attrs, input);
121 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
122 let make_glob_map = control.make_glob_map;
123 phase_2_configure_and_expand(sess, &cstore, krate, &id, addl_plugins, make_glob_map)?
126 controller_entry_point!(after_expand,
128 CompileState::state_after_expand(input,
137 write_out_deps(sess, &outputs, &id);
139 controller_entry_point!(after_write_deps,
141 CompileState::state_after_write_deps(input,
150 let arenas = ty::CtxtArenas::new();
152 // Construct the HIR map
153 let hir_map = time(sess.time_passes(),
155 || hir_map::map_crate(&mut hir_forest, defs));
158 let _ignore = hir_map.dep_graph.in_ignore();
159 controller_entry_point!(after_hir_lowering,
161 CompileState::state_after_hir_lowering(input,
176 time(sess.time_passes(), "attribute checking", || {
177 hir::check_attr::check_crate(sess, &expanded_crate);
180 let opt_crate = if keep_ast(sess) {
181 Some(&expanded_crate)
183 drop(expanded_crate);
187 phase_3_run_analysis_passes(sess,
193 |tcx, mir_map, analysis, result| {
195 // Eventually, we will want to track plugins.
196 let _ignore = tcx.dep_graph.in_ignore();
198 let mut state = CompileState::state_after_analysis(input,
208 (control.after_analysis.callback)(&mut state);
210 if control.after_analysis.stop == Compilation::Stop {
211 return result.and_then(|_| Err(0usize));
217 if log_enabled!(::log::INFO) {
218 println!("Pre-trans");
219 tcx.print_debug_stats();
221 let trans = phase_4_translate_to_llvm(tcx,
225 if log_enabled!(::log::INFO) {
226 println!("Post-trans");
227 tcx.print_debug_stats();
230 // Discard interned strings as they are no longer required.
231 token::get_ident_interner().clear();
237 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
239 controller_entry_point!(after_llvm,
241 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
245 phase_6_link_output(sess, &trans, &outputs);
250 fn keep_mtwt_tables(sess: &Session) -> bool {
251 sess.opts.debugging_opts.keep_mtwt_tables
254 fn keep_ast(sess: &Session) -> bool {
255 sess.opts.debugging_opts.keep_ast ||
256 sess.opts.debugging_opts.save_analysis ||
257 sess.opts.debugging_opts.save_analysis_csv
260 /// The name used for source code that doesn't originate in a file
261 /// (e.g. source from stdin or a string)
262 pub fn anon_src() -> String {
266 pub fn source_name(input: &Input) -> String {
268 // FIXME (#9639): This needs to handle non-utf8 paths
269 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
270 Input::Str { ref name, .. } => name.clone(),
274 /// CompileController is used to customise compilation, it allows compilation to
275 /// be stopped and/or to call arbitrary code at various points in compilation.
276 /// It also allows for various flags to be set to influence what information gets
277 /// collected during compilation.
279 /// This is a somewhat higher level controller than a Session - the Session
280 /// controls what happens in each phase, whereas the CompileController controls
281 /// whether a phase is run at all and whether other code (from outside the
282 /// the compiler) is run between phases.
284 /// Note that if compilation is set to stop and a callback is provided for a
285 /// given entry point, the callback is called before compilation is stopped.
287 /// Expect more entry points to be added in the future.
288 pub struct CompileController<'a> {
289 pub after_parse: PhaseController<'a>,
290 pub after_expand: PhaseController<'a>,
291 pub after_write_deps: PhaseController<'a>,
292 pub after_hir_lowering: PhaseController<'a>,
293 pub after_analysis: PhaseController<'a>,
294 pub after_llvm: PhaseController<'a>,
296 pub make_glob_map: resolve::MakeGlobMap,
299 impl<'a> CompileController<'a> {
300 pub fn basic() -> CompileController<'a> {
302 after_parse: PhaseController::basic(),
303 after_expand: PhaseController::basic(),
304 after_write_deps: PhaseController::basic(),
305 after_hir_lowering: PhaseController::basic(),
306 after_analysis: PhaseController::basic(),
307 after_llvm: PhaseController::basic(),
308 make_glob_map: resolve::MakeGlobMap::No,
313 pub struct PhaseController<'a> {
314 pub stop: Compilation,
315 // If true then the compiler will try to run the callback even if the phase
316 // ends with an error. Note that this is not always possible.
317 pub run_callback_on_error: bool,
318 pub callback: Box<Fn(&mut CompileState) + 'a>,
321 impl<'a> PhaseController<'a> {
322 pub fn basic() -> PhaseController<'a> {
324 stop: Compilation::Continue,
325 run_callback_on_error: false,
326 callback: box |_| {},
331 /// State that is passed to a callback. What state is available depends on when
332 /// during compilation the callback is made. See the various constructor methods
333 /// (`state_*`) in the impl to see which data is provided for any given entry point.
334 pub struct CompileState<'a, 'b, 'ast: 'a, 'tcx: 'b> where 'ast: 'tcx {
335 pub input: &'a Input,
336 pub session: &'ast Session,
337 pub krate: Option<ast::Crate>,
338 pub cstore: Option<&'a CStore>,
339 pub crate_name: Option<&'a str>,
340 pub output_filenames: Option<&'a OutputFilenames>,
341 pub out_dir: Option<&'a Path>,
342 pub out_file: Option<&'a Path>,
343 pub arenas: Option<&'ast ty::CtxtArenas<'ast>>,
344 pub expanded_crate: Option<&'a ast::Crate>,
345 pub hir_crate: Option<&'a hir::Crate>,
346 pub ast_map: Option<&'a hir_map::Map<'ast>>,
347 pub resolutions: Option<&'a Resolutions>,
348 pub mir_map: Option<&'b MirMap<'tcx>>,
349 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
350 pub tcx: Option<TyCtxt<'b, 'tcx, 'tcx>>,
351 pub trans: Option<&'a trans::CrateTranslation>,
354 impl<'a, 'b, 'ast, 'tcx> CompileState<'a, 'b, 'ast, 'tcx> {
355 fn empty(input: &'a Input,
356 session: &'ast Session,
357 out_dir: &'a Option<PathBuf>)
358 -> CompileState<'a, 'b, 'ast, 'tcx> {
362 out_dir: out_dir.as_ref().map(|s| &**s),
368 output_filenames: None,
369 expanded_crate: None,
380 fn state_after_parse(input: &'a Input,
381 session: &'ast Session,
382 out_dir: &'a Option<PathBuf>,
383 out_file: &'a Option<PathBuf>,
386 -> CompileState<'a, 'b, 'ast, 'tcx> {
389 cstore: Some(cstore),
390 out_file: out_file.as_ref().map(|s| &**s),
391 ..CompileState::empty(input, session, out_dir)
395 fn state_after_expand(input: &'a Input,
396 session: &'ast Session,
397 out_dir: &'a Option<PathBuf>,
398 out_file: &'a Option<PathBuf>,
400 expanded_crate: &'a ast::Crate,
402 -> CompileState<'a, 'b, 'ast, 'tcx> {
404 crate_name: Some(crate_name),
405 cstore: Some(cstore),
406 expanded_crate: Some(expanded_crate),
407 out_file: out_file.as_ref().map(|s| &**s),
408 ..CompileState::empty(input, session, out_dir)
412 fn state_after_write_deps(input: &'a Input,
413 session: &'ast Session,
414 out_dir: &'a Option<PathBuf>,
415 out_file: &'a Option<PathBuf>,
417 krate: &'a ast::Crate,
419 -> CompileState<'a, 'b, 'ast, 'tcx> {
421 crate_name: Some(crate_name),
422 cstore: Some(cstore),
423 expanded_crate: Some(krate),
424 out_file: out_file.as_ref().map(|s| &**s),
425 ..CompileState::empty(input, session, out_dir)
429 fn state_after_hir_lowering(input: &'a Input,
430 session: &'ast Session,
431 out_dir: &'a Option<PathBuf>,
432 out_file: &'a Option<PathBuf>,
433 arenas: &'ast ty::CtxtArenas<'ast>,
435 hir_map: &'a hir_map::Map<'ast>,
436 analysis: &'a ty::CrateAnalysis,
437 resolutions: &'a Resolutions,
438 krate: &'a ast::Crate,
439 hir_crate: &'a hir::Crate,
441 -> CompileState<'a, 'b, 'ast, 'tcx> {
443 crate_name: Some(crate_name),
444 arenas: Some(arenas),
445 cstore: Some(cstore),
446 ast_map: Some(hir_map),
447 analysis: Some(analysis),
448 resolutions: Some(resolutions),
449 expanded_crate: Some(krate),
450 hir_crate: Some(hir_crate),
451 out_file: out_file.as_ref().map(|s| &**s),
452 ..CompileState::empty(input, session, out_dir)
456 fn state_after_analysis(input: &'a Input,
457 session: &'ast Session,
458 out_dir: &'a Option<PathBuf>,
459 out_file: &'a Option<PathBuf>,
460 krate: Option<&'a ast::Crate>,
461 hir_crate: &'a hir::Crate,
462 analysis: &'a ty::CrateAnalysis<'a>,
463 mir_map: Option<&'b MirMap<'tcx>>,
464 tcx: TyCtxt<'b, 'tcx, 'tcx>,
466 -> CompileState<'a, 'b, 'ast, 'tcx> {
468 analysis: Some(analysis),
471 expanded_crate: krate,
472 hir_crate: Some(hir_crate),
473 crate_name: Some(crate_name),
474 out_file: out_file.as_ref().map(|s| &**s),
475 ..CompileState::empty(input, session, out_dir)
480 fn state_after_llvm(input: &'a Input,
481 session: &'ast Session,
482 out_dir: &'a Option<PathBuf>,
483 out_file: &'a Option<PathBuf>,
484 trans: &'a trans::CrateTranslation)
485 -> CompileState<'a, 'b, 'ast, 'tcx> {
488 out_file: out_file.as_ref().map(|s| &**s),
489 ..CompileState::empty(input, session, out_dir)
494 pub fn phase_1_parse_input<'a>(sess: &'a Session,
495 cfg: ast::CrateConfig,
497 -> PResult<'a, ast::Crate> {
498 // These may be left in an incoherent state after a previous compile.
499 // `clear_tables` and `get_ident_interner().clear()` can be used to free
500 // memory, but they do not restore the initial state.
501 syntax::ext::mtwt::reset_tables();
502 token::reset_ident_interner();
503 let continue_after_error = sess.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, cfg.clone(), &sess.parse_sess)
511 Input::Str { ref input, ref name } => {
512 parse::parse_crate_from_source_str(name.clone(),
520 sess.diagnostic().set_continue_after_error(true);
522 if sess.opts.debugging_opts.ast_json_noexpand {
523 println!("{}", json::as_json(&krate));
526 if sess.opts.debugging_opts.input_stats {
527 println!("Lines of code: {}", sess.codemap().count_lines());
528 println!("Pre-expansion node count: {}", count_nodes(&krate));
531 if let Some(ref s) = sess.opts.debugging_opts.show_span {
532 syntax::show_span::run(sess.diagnostic(), s, &krate);
538 fn count_nodes(krate: &ast::Crate) -> usize {
539 let mut counter = NodeCounter::new();
540 visit::walk_crate(&mut counter, krate);
544 // For continuing compilation after a parsed crate has been
547 pub struct ExpansionResult<'a> {
548 pub expanded_crate: ast::Crate,
549 pub defs: hir_map::Definitions,
550 pub analysis: ty::CrateAnalysis<'a>,
551 pub resolutions: Resolutions,
552 pub hir_forest: hir_map::Forest,
555 /// Run the "early phases" of the compiler: initial `cfg` processing,
556 /// loading compiler plugins (including those from `addl_plugins`),
557 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
558 /// harness if one is to be provided, injection of a dependency on the
559 /// standard library and prelude, and name resolution.
561 /// Returns `None` if we're aborting after handling -W help.
562 pub fn phase_2_configure_and_expand<'a>(sess: &Session,
564 mut krate: ast::Crate,
566 addl_plugins: Option<Vec<String>>,
567 make_glob_map: resolve::MakeGlobMap)
568 -> Result<ExpansionResult<'a>, usize> {
569 let time_passes = sess.time_passes();
571 // strip before anything else because crate metadata may use #[cfg_attr]
572 // and so macros can depend on configuration variables, such as
574 // #[macro_use] #[cfg(foo)]
575 // mod bar { macro_rules! baz!(() => {{}}) }
577 // baz! should not use this definition unless foo is enabled.
579 krate = time(time_passes, "configuration", || {
580 let (krate, features) =
581 syntax::config::strip_unconfigured_items(krate, &sess.parse_sess, sess.opts.test);
582 // these need to be set "early" so that expansion sees `quote` if enabled.
583 *sess.features.borrow_mut() = features;
587 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
588 sess.crate_disambiguator.set(token::intern(&compute_crate_disambiguator(sess)));
590 time(time_passes, "recursion limit", || {
591 middle::recursion_limit::update_recursion_limit(sess, &krate);
594 krate = time(time_passes, "crate injection", || {
595 let alt_std_name = sess.opts.alt_std_name.clone();
596 syntax::std_inject::maybe_inject_crates_ref(&sess.parse_sess, krate, alt_std_name)
599 let mut addl_plugins = Some(addl_plugins);
600 let registrars = time(time_passes, "plugin loading", || {
601 plugin::load::load_plugins(sess,
605 addl_plugins.take().unwrap())
608 let mut registry = Registry::new(sess, &krate);
610 time(time_passes, "plugin registration", || {
611 if sess.features.borrow().rustc_diagnostic_macros {
612 registry.register_macro("__diagnostic_used",
613 diagnostics::plugin::expand_diagnostic_used);
614 registry.register_macro("__register_diagnostic",
615 diagnostics::plugin::expand_register_diagnostic);
616 registry.register_macro("__build_diagnostic_array",
617 diagnostics::plugin::expand_build_diagnostic_array);
620 for registrar in registrars {
621 registry.args_hidden = Some(registrar.args);
622 (registrar.fun)(&mut registry);
626 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
627 llvm_passes, attributes, mir_passes, .. } = registry;
629 sess.track_errors(|| {
630 let mut ls = sess.lint_store.borrow_mut();
631 for pass in early_lint_passes {
632 ls.register_early_pass(Some(sess), true, pass);
634 for pass in late_lint_passes {
635 ls.register_late_pass(Some(sess), true, pass);
638 for (name, to) in lint_groups {
639 ls.register_group(Some(sess), true, name, to);
642 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
643 sess.mir_passes.borrow_mut().extend(mir_passes);
644 *sess.plugin_attributes.borrow_mut() = attributes.clone();
647 // Lint plugins are registered; now we can process command line flags.
648 if sess.opts.describe_lints {
649 super::describe_lints(&sess.lint_store.borrow(), true);
652 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
654 krate = time(time_passes, "expansion", || {
655 // Windows dlls do not have rpaths, so they don't know how to find their
656 // dependencies. It's up to us to tell the system where to find all the
657 // dependent dlls. Note that this uses cfg!(windows) as opposed to
658 // targ_cfg because syntax extensions are always loaded for the host
659 // compiler, not for the target.
661 // This is somewhat of an inherently racy operation, however, as
662 // multiple threads calling this function could possibly continue
663 // extending PATH far beyond what it should. To solve this for now we
664 // just don't add any new elements to PATH which are already there
665 // within PATH. This is basically a targeted fix at #17360 for rustdoc
666 // which runs rustc in parallel but has been seen (#33844) to cause
667 // problems with PATH becoming too long.
668 let mut old_path = OsString::new();
670 old_path = env::var_os("PATH").unwrap_or(old_path);
671 let mut new_path = sess.host_filesearch(PathKind::All)
672 .get_dylib_search_paths();
673 for path in env::split_paths(&old_path) {
674 if !new_path.contains(&path) {
678 env::set_var("PATH", &env::join_paths(new_path).unwrap());
680 let features = sess.features.borrow();
681 let cfg = syntax::ext::expand::ExpansionConfig {
682 crate_name: crate_name.to_string(),
683 features: Some(&features),
684 recursion_limit: sess.recursion_limit.get(),
685 trace_mac: sess.opts.debugging_opts.trace_macros,
686 should_test: sess.opts.test,
688 let mut loader = macro_import::MacroLoader::new(sess, &cstore, crate_name);
689 let mut ecx = syntax::ext::base::ExtCtxt::new(&sess.parse_sess,
690 krate.config.clone(),
693 syntax_ext::register_builtins(&mut ecx.syntax_env);
694 let (ret, macro_names) = syntax::ext::expand::expand_crate(ecx,
698 env::set_var("PATH", &old_path);
700 *sess.available_macros.borrow_mut() = macro_names;
704 krate = time(time_passes, "maybe building test harness", || {
705 syntax::test::modify_for_testing(&sess.parse_sess,
712 "checking for inline asm in case the target doesn't support it",
713 || no_asm::check_crate(sess, &krate));
715 // Needs to go *after* expansion to be able to check the results of macro expansion.
716 time(time_passes, "complete gated feature checking", || {
717 sess.track_errors(|| {
718 syntax::feature_gate::check_crate(&krate,
720 &sess.features.borrow(),
722 sess.opts.unstable_features);
726 if sess.opts.debugging_opts.input_stats {
727 println!("Post-expansion node count: {}", count_nodes(&krate));
730 krate = assign_node_ids(sess, krate);
732 // Collect defintions for def ids.
734 time(sess.time_passes(), "collecting defs", || hir_map::collect_definitions(&krate));
736 time(sess.time_passes(),
737 "external crate/lib resolution",
738 || read_local_crates(sess, &cstore, &defs, &krate, crate_name, &sess.dep_graph));
740 time(sess.time_passes(),
742 || lint::check_ast_crate(sess, &krate));
744 time(sess.time_passes(),
746 || ast_validation::check_crate(sess, &krate));
748 let (analysis, resolutions, hir_forest) =
749 lower_and_resolve(sess, crate_name, &mut defs, &krate, &sess.dep_graph, make_glob_map);
751 // Discard MTWT tables that aren't required past lowering to HIR.
752 if !keep_mtwt_tables(sess) {
753 syntax::ext::mtwt::clear_tables();
757 expanded_crate: krate,
760 resolutions: resolutions,
761 hir_forest: hir_forest
765 pub fn assign_node_ids(sess: &Session, krate: ast::Crate) -> ast::Crate {
767 use syntax::util::move_map::MoveMap;
769 struct NodeIdAssigner<'a> {
773 impl<'a> Folder for NodeIdAssigner<'a> {
774 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
775 assert_eq!(old_id, ast::DUMMY_NODE_ID);
776 self.sess.next_node_id()
779 fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> {
780 block.map(|mut block| {
781 block.id = self.new_id(block.id);
783 let stmt = block.stmts.pop();
784 block.stmts = block.stmts.move_flat_map(|s| self.fold_stmt(s).into_iter());
785 if let Some(ast::Stmt { node: ast::StmtKind::Expr(expr), span, .. }) = stmt {
786 let expr = self.fold_expr(expr);
787 block.stmts.push(ast::Stmt {
789 node: ast::StmtKind::Expr(expr),
792 } else if let Some(stmt) = stmt {
793 block.stmts.extend(self.fold_stmt(stmt));
801 let krate = time(sess.time_passes(),
802 "assigning node ids",
803 || NodeIdAssigner { sess: sess }.fold_crate(krate));
805 if sess.opts.debugging_opts.ast_json {
806 println!("{}", json::as_json(&krate));
812 pub fn lower_and_resolve<'a>(sess: &Session,
814 defs: &mut hir_map::Definitions,
816 dep_graph: &DepGraph,
817 make_glob_map: resolve::MakeGlobMap)
818 -> (ty::CrateAnalysis<'a>, Resolutions, hir_map::Forest) {
819 resolve::with_resolver(sess, defs, make_glob_map, |mut resolver| {
820 time(sess.time_passes(), "name resolution", || {
821 resolve::resolve_crate(&mut resolver, krate);
825 let hir_forest = time(sess.time_passes(), "lowering ast -> hir", || {
826 hir_map::Forest::new(lower_crate(sess, krate, sess, &mut resolver), dep_graph)
830 export_map: resolver.export_map,
831 access_levels: AccessLevels::default(),
832 reachable: NodeSet(),
834 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
836 def_map: resolver.def_map,
837 freevars: resolver.freevars,
838 trait_map: resolver.trait_map,
839 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
844 /// Run the resolution, typechecking, region checking and other
845 /// miscellaneous analysis passes on the crate. Return various
846 /// structures carrying the results of the analysis.
847 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
848 hir_map: hir_map::Map<'tcx>,
849 mut analysis: ty::CrateAnalysis,
850 resolutions: Resolutions,
851 arenas: &'tcx ty::CtxtArenas<'tcx>,
855 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
856 Option<MirMap<'tcx>>,
860 macro_rules! try_with_f {
861 ($e: expr, ($t: expr, $m: expr, $a: expr)) => {
865 f($t, $m, $a, Err(x));
872 let time_passes = sess.time_passes();
874 let lang_items = time(time_passes, "language item collection", || {
875 sess.track_errors(|| {
876 middle::lang_items::collect_language_items(&sess, &hir_map)
880 let named_region_map = time(time_passes,
881 "lifetime resolution",
882 || middle::resolve_lifetime::krate(sess,
884 &resolutions.def_map))?;
887 "looking for entry point",
888 || middle::entry::find_entry_point(sess, &hir_map));
890 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
891 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
894 let region_map = time(time_passes,
896 || middle::region::resolve_crate(sess, &hir_map));
900 || loops::check_crate(sess, &hir_map));
903 "static item recursion checking",
904 || static_recursion::check_crate(sess, &resolutions.def_map, &hir_map))?;
906 let index = stability::Index::new(&hir_map);
908 let trait_map = resolutions.trait_map;
909 TyCtxt::create_and_enter(sess,
914 resolutions.freevars,
915 resolutions.maybe_unused_trait_imports,
923 || rustc_incremental::load_dep_graph(tcx));
925 // passes are timed inside typeck
926 try_with_f!(typeck::check_crate(tcx, trait_map), (tcx, None, analysis));
930 || consts::check_crate(tcx));
932 analysis.access_levels =
933 time(time_passes, "privacy checking", || {
934 rustc_privacy::check_crate(tcx, &analysis.export_map)
937 // Do not move this check past lint
938 time(time_passes, "stability index", || {
939 tcx.stability.borrow_mut().build(tcx, &analysis.access_levels)
943 "intrinsic checking",
944 || middle::intrinsicck::check_crate(tcx));
948 || middle::effect::check_crate(tcx));
952 || check_match::check_crate(tcx));
954 // this must run before MIR dump, because
955 // "not all control paths return a value" is reported here.
957 // maybe move the check to a MIR pass?
960 || middle::liveness::check_crate(tcx));
964 || rvalues::check_crate(tcx));
969 || mir::mir_map::build_mir_for_crate(tcx));
971 time(time_passes, "MIR passes", || {
972 let mut passes = sess.mir_passes.borrow_mut();
973 // Push all the built-in passes.
974 passes.push_hook(box mir::transform::dump_mir::DumpMir);
975 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("initial"));
976 passes.push_pass(box mir::transform::qualify_consts::QualifyAndPromoteConstants);
977 passes.push_pass(box mir::transform::type_check::TypeckMir);
979 box mir::transform::simplify_branches::SimplifyBranches::new("initial"));
980 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("qualify-consts"));
981 // And run everything.
982 passes.run_passes(tcx, &mut mir_map);
987 || borrowck::check_crate(tcx, &mir_map));
989 // Avoid overwhelming user with errors if type checking failed.
990 // I'm not sure how helpful this is, to be honest, but it avoids
992 // lot of annoying errors in the compile-fail tests (basically,
993 // lint warnings and so on -- kindck used to do this abort, but
994 // kindck is gone now). -nmatsakis
995 if sess.err_count() > 0 {
996 return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
1001 "reachability checking",
1002 || reachable::find_reachable(tcx, &analysis.access_levels));
1004 time(time_passes, "death checking", || {
1005 middle::dead::check_crate(tcx, &analysis.access_levels);
1008 let ref lib_features_used =
1010 "stability checking",
1011 || stability::check_unstable_api_usage(tcx));
1013 time(time_passes, "unused lib feature checking", || {
1014 stability::check_unused_or_stable_features(&tcx.sess,
1020 || lint::check_crate(tcx, &analysis.access_levels));
1022 // The above three passes generate errors w/o aborting
1023 if sess.err_count() > 0 {
1024 return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
1027 Ok(f(tcx, Some(mir_map), analysis, Ok(())))
1031 /// Run the translation phase to LLVM, after which the AST and analysis can
1032 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1033 mut mir_map: MirMap<'tcx>,
1034 analysis: ty::CrateAnalysis)
1035 -> trans::CrateTranslation {
1036 let time_passes = tcx.sess.time_passes();
1039 "resolving dependency formats",
1040 || dependency_format::calculate(&tcx.sess));
1042 // Run the passes that transform the MIR into a more suitable for translation
1044 time(time_passes, "Prepare MIR codegen passes", || {
1045 let mut passes = ::rustc::mir::transform::Passes::new();
1046 passes.push_hook(box mir::transform::dump_mir::DumpMir);
1047 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1048 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("no-landing-pads"));
1050 passes.push_pass(box mir::transform::erase_regions::EraseRegions);
1052 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1053 passes.push_pass(box borrowck::ElaborateDrops);
1054 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1055 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("elaborate-drops"));
1057 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1058 passes.push_pass(box mir::transform::dump_mir::Marker("PreTrans"));
1060 passes.run_passes(tcx, &mut mir_map);
1066 move || trans::trans_crate(tcx, &mir_map, analysis));
1070 move || rustc_incremental::assert_dep_graph(tcx));
1073 "serialize dep graph",
1074 move || rustc_incremental::save_dep_graph(tcx));
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: &trans::CrateTranslation,
1083 outputs: &OutputFilenames) -> CompileResult {
1084 if sess.opts.cg.no_integrated_as {
1085 let mut map = HashMap::new();
1086 map.insert(OutputType::Assembly, None);
1087 time(sess.time_passes(),
1089 || write::run_passes(sess, trans, &map, outputs));
1091 write::run_assembler(sess, outputs);
1093 // Remove assembly source, unless --save-temps was specified
1094 if !sess.opts.cg.save_temps {
1095 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
1098 time(sess.time_passes(),
1100 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1103 if sess.err_count() > 0 {
1104 Err(sess.err_count())
1110 /// Run the linker on any artifacts that resulted from the LLVM run.
1111 /// This should produce either a finished executable or library.
1112 pub fn phase_6_link_output(sess: &Session,
1113 trans: &trans::CrateTranslation,
1114 outputs: &OutputFilenames) {
1115 time(sess.time_passes(),
1117 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
1120 fn escape_dep_filename(filename: &str) -> String {
1121 // Apparently clang and gcc *only* escape spaces:
1122 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1123 filename.replace(" ", "\\ ")
1126 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
1127 let mut out_filenames = Vec::new();
1128 for output_type in sess.opts.output_types.keys() {
1129 let file = outputs.path(*output_type);
1130 match *output_type {
1131 OutputType::Exe => {
1132 for output in sess.crate_types.borrow().iter() {
1133 let p = link::filename_for_input(sess, *output, id, outputs);
1134 out_filenames.push(p);
1138 out_filenames.push(file);
1143 // Write out dependency rules to the dep-info file if requested
1144 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1147 let deps_filename = outputs.path(OutputType::DepInfo);
1150 (|| -> io::Result<()> {
1151 // Build a list of files used to compile the output and
1152 // write Makefile-compatible dependency rules
1153 let files: Vec<String> = sess.codemap()
1157 .filter(|fmap| fmap.is_real_file())
1158 .filter(|fmap| !fmap.is_imported())
1159 .map(|fmap| escape_dep_filename(&fmap.name))
1161 let mut file = fs::File::create(&deps_filename)?;
1162 for path in &out_filenames {
1163 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1166 // Emit a fake target for each input file to the compilation. This
1167 // prevents `make` from spitting out an error if a file is later
1168 // deleted. For more info see #28735
1170 writeln!(file, "{}:", path)?;
1178 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1179 deps_filename.display(),
1185 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1186 // Unconditionally collect crate types from attributes to make them used
1187 let attr_types: Vec<config::CrateType> =
1190 if a.check_name("crate_type") {
1191 match a.value_str() {
1192 Some(ref n) if *n == "rlib" => {
1193 Some(config::CrateTypeRlib)
1195 Some(ref n) if *n == "dylib" => {
1196 Some(config::CrateTypeDylib)
1198 Some(ref n) if *n == "cdylib" => {
1199 Some(config::CrateTypeCdylib)
1201 Some(ref n) if *n == "lib" => {
1202 Some(config::default_lib_output())
1204 Some(ref n) if *n == "staticlib" => {
1205 Some(config::CrateTypeStaticlib)
1207 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1209 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1212 "invalid `crate_type` value".to_string());
1216 session.struct_span_err(a.span, "`crate_type` requires a value")
1217 .note("for example: `#![crate_type=\"lib\"]`")
1228 // If we're generating a test executable, then ignore all other output
1229 // styles at all other locations
1230 if session.opts.test {
1231 return vec![config::CrateTypeExecutable];
1234 // Only check command line flags if present. If no types are specified by
1235 // command line, then reuse the empty `base` Vec to hold the types that
1236 // will be found in crate attributes.
1237 let mut base = session.opts.crate_types.clone();
1238 if base.is_empty() {
1239 base.extend(attr_types);
1240 if base.is_empty() {
1241 base.push(link::default_output_for_target(session));
1248 .filter(|crate_type| {
1249 let res = !link::invalid_output_for_target(session, *crate_type);
1252 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1254 session.opts.target_triple));
1262 pub fn compute_crate_disambiguator(session: &Session) -> String {
1263 let mut hasher = Sha256::new();
1265 let mut metadata = session.opts.cg.metadata.clone();
1266 // We don't want the crate_disambiguator to dependent on the order
1267 // -C metadata arguments, so sort them:
1269 // Every distinct -C metadata value is only incorporated once:
1272 hasher.input_str("metadata");
1273 for s in &metadata {
1274 // Also incorporate the length of a metadata string, so that we generate
1275 // different values for `-Cmetadata=ab -Cmetadata=c` and
1276 // `-Cmetadata=a -Cmetadata=bc`
1277 hasher.input_str(&format!("{}", s.len())[..]);
1278 hasher.input_str(&s[..]);
1281 let mut hash = hasher.result_str();
1283 // If this is an executable, add a special suffix, so that we don't get
1284 // symbol conflicts when linking against a library of the same name.
1285 if session.crate_types.borrow().contains(&config::CrateTypeExecutable) {
1286 hash.push_str("-exe");
1292 pub fn build_output_filenames(input: &Input,
1293 odir: &Option<PathBuf>,
1294 ofile: &Option<PathBuf>,
1295 attrs: &[ast::Attribute],
1297 -> OutputFilenames {
1300 // "-" as input file will cause the parser to read from stdin so we
1301 // have to make up a name
1302 // We want to toss everything after the final '.'
1303 let dirpath = match *odir {
1304 Some(ref d) => d.clone(),
1305 None => PathBuf::new(),
1308 // If a crate name is present, we use it as the link name
1309 let stem = sess.opts
1312 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1313 .unwrap_or(input.filestem());
1316 out_directory: dirpath,
1318 single_output_file: None,
1319 extra: sess.opts.cg.extra_filename.clone(),
1320 outputs: sess.opts.output_types.clone(),
1324 Some(ref out_file) => {
1325 let unnamed_output_types = sess.opts
1328 .filter(|a| a.is_none())
1330 let ofile = if unnamed_output_types > 1 {
1331 sess.warn("ignoring specified output filename because multiple outputs were \
1335 Some(out_file.clone())
1338 sess.warn("ignoring --out-dir flag due to -o flag.");
1341 let cur_dir = Path::new("");
1344 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1345 out_filestem: out_file.file_stem()
1346 .unwrap_or(OsStr::new(""))
1350 single_output_file: ofile,
1351 extra: sess.opts.cg.extra_filename.clone(),
1352 outputs: sess.opts.output_types.clone(),