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.
12 use rustc::hir::{map as hir_map, FreevarMap, TraitMap};
13 use rustc::hir::def::DefMap;
14 use rustc::hir::lowering::lower_crate;
16 use rustc::mir::mir_map::MirMap;
17 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
18 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
19 use rustc::session::search_paths::PathKind;
21 use rustc::middle::{self, dependency_format, stability, reachable};
22 use rustc::middle::privacy::AccessLevels;
23 use rustc::ty::{self, TyCtxt};
24 use rustc::util::common::time;
25 use rustc::util::nodemap::NodeSet;
26 use rustc_back::sha2::{Sha256, Digest};
27 use rustc_borrowck as borrowck;
28 use rustc_incremental;
29 use rustc_resolve::{MakeGlobMap, Resolver};
30 use rustc_metadata::macro_import;
31 use rustc_metadata::creader::read_local_crates;
32 use rustc_metadata::cstore::CStore;
33 use rustc_trans::back::{link, write};
34 use rustc_trans as trans;
35 use rustc_typeck as typeck;
37 use rustc_plugin::registry::Registry;
38 use rustc_plugin as plugin;
39 use rustc_passes::{ast_validation, no_asm, loops, consts, rvalues, static_recursion};
40 use rustc_const_eval::check_match;
41 use super::Compilation;
45 use std::collections::HashMap;
47 use std::ffi::{OsString, OsStr};
49 use std::io::{self, Write};
50 use std::path::{Path, PathBuf};
51 use syntax::{ast, diagnostics, visit};
52 use syntax::attr::{self, AttrMetaMethods};
53 use syntax::parse::{self, PResult, token};
54 use syntax::util::node_count::NodeCounter;
59 pub struct Resolutions {
61 pub freevars: FreevarMap,
62 pub trait_map: TraitMap,
63 pub maybe_unused_trait_imports: NodeSet,
66 pub fn compile_input(sess: &Session,
68 cfg: ast::CrateConfig,
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 return compile_result_from_err_count($tsess.err_count());
88 // We need nested scopes here, because the intermediate results can keep
89 // large chunks of memory alive and we want to free them as soon as
90 // possible to keep the peak memory usage low
91 let (outputs, trans) = {
92 let krate = match phase_1_parse_input(sess, cfg, input) {
94 Err(mut parse_error) => {
101 let mut compile_state = CompileState::state_after_parse(input,
107 controller_entry_point!(after_parse,
112 compile_state.krate.unwrap()
115 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
116 let id = link::find_crate_name(Some(sess), &krate.attrs, input);
117 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
118 phase_2_configure_and_expand(
119 sess, &cstore, krate, &id, addl_plugins, control.make_glob_map,
121 let mut state = CompileState::state_after_expand(
122 input, sess, outdir, output, &cstore, expanded_crate, &id,
124 controller_entry_point!(after_expand, sess, state, Ok(()));
130 write_out_deps(sess, &outputs, &id);
132 let arenas = ty::CtxtArenas::new();
134 // Construct the HIR map
135 let hir_map = time(sess.time_passes(),
137 || hir_map::map_crate(&mut hir_forest, defs));
140 let _ignore = hir_map.dep_graph.in_ignore();
141 controller_entry_point!(after_hir_lowering,
143 CompileState::state_after_hir_lowering(input,
158 time(sess.time_passes(), "attribute checking", || {
159 hir::check_attr::check_crate(sess, &expanded_crate);
162 let opt_crate = if keep_ast(sess) {
163 Some(&expanded_crate)
165 drop(expanded_crate);
169 phase_3_run_analysis_passes(sess,
175 |tcx, mir_map, analysis, result| {
177 // Eventually, we will want to track plugins.
178 let _ignore = tcx.dep_graph.in_ignore();
180 let mut state = CompileState::state_after_analysis(input,
190 (control.after_analysis.callback)(&mut state);
192 if control.after_analysis.stop == Compilation::Stop {
193 return result.and_then(|_| Err(0usize));
199 if log_enabled!(::log::INFO) {
200 println!("Pre-trans");
201 tcx.print_debug_stats();
203 let trans = phase_4_translate_to_llvm(tcx,
207 if log_enabled!(::log::INFO) {
208 println!("Post-trans");
209 tcx.print_debug_stats();
212 // Discard interned strings as they are no longer required.
213 token::clear_ident_interner();
219 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
221 controller_entry_point!(after_llvm,
223 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
227 write::cleanup_llvm(&trans);
229 phase_6_link_output(sess, &trans, &outputs);
231 controller_entry_point!(compilation_done,
233 CompileState::state_when_compilation_done(input, sess, outdir, output),
239 fn keep_mtwt_tables(sess: &Session) -> bool {
240 sess.opts.debugging_opts.keep_mtwt_tables
243 fn keep_ast(sess: &Session) -> bool {
244 sess.opts.debugging_opts.keep_ast ||
245 sess.opts.debugging_opts.save_analysis ||
246 sess.opts.debugging_opts.save_analysis_csv
249 /// The name used for source code that doesn't originate in a file
250 /// (e.g. source from stdin or a string)
251 pub fn anon_src() -> String {
255 pub fn source_name(input: &Input) -> String {
257 // FIXME (#9639): This needs to handle non-utf8 paths
258 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
259 Input::Str { ref name, .. } => name.clone(),
263 /// CompileController is used to customise compilation, it allows compilation to
264 /// be stopped and/or to call arbitrary code at various points in compilation.
265 /// It also allows for various flags to be set to influence what information gets
266 /// collected during compilation.
268 /// This is a somewhat higher level controller than a Session - the Session
269 /// controls what happens in each phase, whereas the CompileController controls
270 /// whether a phase is run at all and whether other code (from outside the
271 /// the compiler) is run between phases.
273 /// Note that if compilation is set to stop and a callback is provided for a
274 /// given entry point, the callback is called before compilation is stopped.
276 /// Expect more entry points to be added in the future.
277 pub struct CompileController<'a> {
278 pub after_parse: PhaseController<'a>,
279 pub after_expand: PhaseController<'a>,
280 pub after_hir_lowering: PhaseController<'a>,
281 pub after_analysis: PhaseController<'a>,
282 pub after_llvm: PhaseController<'a>,
283 pub compilation_done: PhaseController<'a>,
285 pub make_glob_map: MakeGlobMap,
288 impl<'a> CompileController<'a> {
289 pub fn basic() -> CompileController<'a> {
291 after_parse: PhaseController::basic(),
292 after_expand: PhaseController::basic(),
293 after_hir_lowering: PhaseController::basic(),
294 after_analysis: PhaseController::basic(),
295 after_llvm: PhaseController::basic(),
296 compilation_done: PhaseController::basic(),
297 make_glob_map: MakeGlobMap::No,
302 pub struct PhaseController<'a> {
303 pub stop: Compilation,
304 // If true then the compiler will try to run the callback even if the phase
305 // ends with an error. Note that this is not always possible.
306 pub run_callback_on_error: bool,
307 pub callback: Box<Fn(&mut CompileState) + 'a>,
310 impl<'a> PhaseController<'a> {
311 pub fn basic() -> PhaseController<'a> {
313 stop: Compilation::Continue,
314 run_callback_on_error: false,
315 callback: box |_| {},
320 /// State that is passed to a callback. What state is available depends on when
321 /// during compilation the callback is made. See the various constructor methods
322 /// (`state_*`) in the impl to see which data is provided for any given entry point.
323 pub struct CompileState<'a, 'b, 'ast: 'a, 'tcx: 'b> where 'ast: 'tcx {
324 pub input: &'a Input,
325 pub session: &'ast Session,
326 pub krate: Option<ast::Crate>,
327 pub cstore: Option<&'a CStore>,
328 pub crate_name: Option<&'a str>,
329 pub output_filenames: Option<&'a OutputFilenames>,
330 pub out_dir: Option<&'a Path>,
331 pub out_file: Option<&'a Path>,
332 pub arenas: Option<&'ast ty::CtxtArenas<'ast>>,
333 pub expanded_crate: Option<&'a ast::Crate>,
334 pub hir_crate: Option<&'a hir::Crate>,
335 pub ast_map: Option<&'a hir_map::Map<'ast>>,
336 pub resolutions: Option<&'a Resolutions>,
337 pub mir_map: Option<&'b MirMap<'tcx>>,
338 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
339 pub tcx: Option<TyCtxt<'b, 'tcx, 'tcx>>,
340 pub trans: Option<&'a trans::CrateTranslation>,
343 impl<'a, 'b, 'ast, 'tcx> CompileState<'a, 'b, 'ast, 'tcx> {
344 fn empty(input: &'a Input,
345 session: &'ast Session,
346 out_dir: &'a Option<PathBuf>)
347 -> CompileState<'a, 'b, 'ast, 'tcx> {
351 out_dir: out_dir.as_ref().map(|s| &**s),
357 output_filenames: None,
358 expanded_crate: None,
369 fn state_after_parse(input: &'a Input,
370 session: &'ast Session,
371 out_dir: &'a Option<PathBuf>,
372 out_file: &'a Option<PathBuf>,
375 -> CompileState<'a, 'b, 'ast, 'tcx> {
378 cstore: Some(cstore),
379 out_file: out_file.as_ref().map(|s| &**s),
380 ..CompileState::empty(input, session, out_dir)
384 fn state_after_expand(input: &'a Input,
385 session: &'ast Session,
386 out_dir: &'a Option<PathBuf>,
387 out_file: &'a Option<PathBuf>,
389 expanded_crate: &'a ast::Crate,
391 -> CompileState<'a, 'b, 'ast, 'tcx> {
393 crate_name: Some(crate_name),
394 cstore: Some(cstore),
395 expanded_crate: Some(expanded_crate),
396 out_file: out_file.as_ref().map(|s| &**s),
397 ..CompileState::empty(input, session, out_dir)
401 fn state_after_hir_lowering(input: &'a Input,
402 session: &'ast Session,
403 out_dir: &'a Option<PathBuf>,
404 out_file: &'a Option<PathBuf>,
405 arenas: &'ast ty::CtxtArenas<'ast>,
407 hir_map: &'a hir_map::Map<'ast>,
408 analysis: &'a ty::CrateAnalysis,
409 resolutions: &'a Resolutions,
410 krate: &'a ast::Crate,
411 hir_crate: &'a hir::Crate,
413 -> CompileState<'a, 'b, 'ast, 'tcx> {
415 crate_name: Some(crate_name),
416 arenas: Some(arenas),
417 cstore: Some(cstore),
418 ast_map: Some(hir_map),
419 analysis: Some(analysis),
420 resolutions: Some(resolutions),
421 expanded_crate: Some(krate),
422 hir_crate: Some(hir_crate),
423 out_file: out_file.as_ref().map(|s| &**s),
424 ..CompileState::empty(input, session, out_dir)
428 fn state_after_analysis(input: &'a Input,
429 session: &'ast Session,
430 out_dir: &'a Option<PathBuf>,
431 out_file: &'a Option<PathBuf>,
432 krate: Option<&'a ast::Crate>,
433 hir_crate: &'a hir::Crate,
434 analysis: &'a ty::CrateAnalysis<'a>,
435 mir_map: Option<&'b MirMap<'tcx>>,
436 tcx: TyCtxt<'b, 'tcx, 'tcx>,
438 -> CompileState<'a, 'b, 'ast, 'tcx> {
440 analysis: Some(analysis),
443 expanded_crate: krate,
444 hir_crate: Some(hir_crate),
445 crate_name: Some(crate_name),
446 out_file: out_file.as_ref().map(|s| &**s),
447 ..CompileState::empty(input, session, out_dir)
452 fn state_after_llvm(input: &'a Input,
453 session: &'ast Session,
454 out_dir: &'a Option<PathBuf>,
455 out_file: &'a Option<PathBuf>,
456 trans: &'a trans::CrateTranslation)
457 -> CompileState<'a, 'b, 'ast, 'tcx> {
460 out_file: out_file.as_ref().map(|s| &**s),
461 ..CompileState::empty(input, session, out_dir)
465 fn state_when_compilation_done(input: &'a Input,
466 session: &'ast Session,
467 out_dir: &'a Option<PathBuf>,
468 out_file: &'a Option<PathBuf>)
469 -> CompileState<'a, 'b, 'ast, 'tcx> {
471 out_file: out_file.as_ref().map(|s| &**s),
472 ..CompileState::empty(input, session, out_dir)
477 pub fn phase_1_parse_input<'a>(sess: &'a Session,
478 cfg: ast::CrateConfig,
480 -> PResult<'a, ast::Crate> {
481 // These may be left in an incoherent state after a previous compile.
482 // `clear_tables` and `clear_ident_interner` can be used to free
483 // memory, but they do not restore the initial state.
484 syntax::ext::mtwt::reset_tables();
485 token::reset_ident_interner();
486 let continue_after_error = sess.opts.continue_parse_after_error;
487 sess.diagnostic().set_continue_after_error(continue_after_error);
489 let krate = time(sess.time_passes(), "parsing", || {
491 Input::File(ref file) => {
492 parse::parse_crate_from_file(file, cfg.clone(), &sess.parse_sess)
494 Input::Str { ref input, ref name } => {
495 parse::parse_crate_from_source_str(name.clone(),
503 sess.diagnostic().set_continue_after_error(true);
505 if sess.opts.debugging_opts.ast_json_noexpand {
506 println!("{}", json::as_json(&krate));
509 if sess.opts.debugging_opts.input_stats {
510 println!("Lines of code: {}", sess.codemap().count_lines());
511 println!("Pre-expansion node count: {}", count_nodes(&krate));
514 if let Some(ref s) = sess.opts.debugging_opts.show_span {
515 syntax::show_span::run(sess.diagnostic(), s, &krate);
521 fn count_nodes(krate: &ast::Crate) -> usize {
522 let mut counter = NodeCounter::new();
523 visit::walk_crate(&mut counter, krate);
527 // For continuing compilation after a parsed crate has been
530 pub struct ExpansionResult<'a> {
531 pub expanded_crate: ast::Crate,
532 pub defs: hir_map::Definitions,
533 pub analysis: ty::CrateAnalysis<'a>,
534 pub resolutions: Resolutions,
535 pub hir_forest: hir_map::Forest,
538 /// Run the "early phases" of the compiler: initial `cfg` processing,
539 /// loading compiler plugins (including those from `addl_plugins`),
540 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
541 /// harness if one is to be provided, injection of a dependency on the
542 /// standard library and prelude, and name resolution.
544 /// Returns `None` if we're aborting after handling -W help.
545 pub fn phase_2_configure_and_expand<'a, F>(sess: &Session,
547 mut krate: ast::Crate,
549 addl_plugins: Option<Vec<String>>,
550 make_glob_map: MakeGlobMap,
552 -> Result<ExpansionResult<'a>, usize>
553 where F: FnOnce(&ast::Crate) -> CompileResult,
555 let time_passes = sess.time_passes();
557 // strip before anything else because crate metadata may use #[cfg_attr]
558 // and so macros can depend on configuration variables, such as
560 // #[macro_use] #[cfg(foo)]
561 // mod bar { macro_rules! baz!(() => {{}}) }
563 // baz! should not use this definition unless foo is enabled.
565 krate = time(time_passes, "configuration", || {
566 let (krate, features) =
567 syntax::config::strip_unconfigured_items(krate, &sess.parse_sess, sess.opts.test);
568 // these need to be set "early" so that expansion sees `quote` if enabled.
569 *sess.features.borrow_mut() = features;
573 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
574 sess.crate_disambiguator.set(token::intern(&compute_crate_disambiguator(sess)));
576 time(time_passes, "recursion limit", || {
577 middle::recursion_limit::update_recursion_limit(sess, &krate);
580 krate = time(time_passes, "crate injection", || {
581 let alt_std_name = sess.opts.alt_std_name.clone();
582 syntax::std_inject::maybe_inject_crates_ref(&sess.parse_sess, krate, alt_std_name)
585 let mut addl_plugins = Some(addl_plugins);
586 let registrars = time(time_passes, "plugin loading", || {
587 plugin::load::load_plugins(sess,
591 addl_plugins.take().unwrap())
594 let mut registry = Registry::new(sess, &krate);
596 time(time_passes, "plugin registration", || {
597 if sess.features.borrow().rustc_diagnostic_macros {
598 registry.register_macro("__diagnostic_used",
599 diagnostics::plugin::expand_diagnostic_used);
600 registry.register_macro("__register_diagnostic",
601 diagnostics::plugin::expand_register_diagnostic);
602 registry.register_macro("__build_diagnostic_array",
603 diagnostics::plugin::expand_build_diagnostic_array);
606 for registrar in registrars {
607 registry.args_hidden = Some(registrar.args);
608 (registrar.fun)(&mut registry);
612 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
613 llvm_passes, attributes, mir_passes, .. } = registry;
615 sess.track_errors(|| {
616 let mut ls = sess.lint_store.borrow_mut();
617 for pass in early_lint_passes {
618 ls.register_early_pass(Some(sess), true, pass);
620 for pass in late_lint_passes {
621 ls.register_late_pass(Some(sess), true, pass);
624 for (name, to) in lint_groups {
625 ls.register_group(Some(sess), true, name, to);
628 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
629 sess.mir_passes.borrow_mut().extend(mir_passes);
630 *sess.plugin_attributes.borrow_mut() = attributes.clone();
633 // Lint plugins are registered; now we can process command line flags.
634 if sess.opts.describe_lints {
635 super::describe_lints(&sess.lint_store.borrow(), true);
638 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
640 krate = time(time_passes, "expansion", || {
641 // Windows dlls do not have rpaths, so they don't know how to find their
642 // dependencies. It's up to us to tell the system where to find all the
643 // dependent dlls. Note that this uses cfg!(windows) as opposed to
644 // targ_cfg because syntax extensions are always loaded for the host
645 // compiler, not for the target.
647 // This is somewhat of an inherently racy operation, however, as
648 // multiple threads calling this function could possibly continue
649 // extending PATH far beyond what it should. To solve this for now we
650 // just don't add any new elements to PATH which are already there
651 // within PATH. This is basically a targeted fix at #17360 for rustdoc
652 // which runs rustc in parallel but has been seen (#33844) to cause
653 // problems with PATH becoming too long.
654 let mut old_path = OsString::new();
656 old_path = env::var_os("PATH").unwrap_or(old_path);
657 let mut new_path = sess.host_filesearch(PathKind::All)
658 .get_dylib_search_paths();
659 for path in env::split_paths(&old_path) {
660 if !new_path.contains(&path) {
664 env::set_var("PATH", &env::join_paths(new_path).unwrap());
666 let features = sess.features.borrow();
667 let cfg = syntax::ext::expand::ExpansionConfig {
668 crate_name: crate_name.to_string(),
669 features: Some(&features),
670 recursion_limit: sess.recursion_limit.get(),
671 trace_mac: sess.opts.debugging_opts.trace_macros,
672 should_test: sess.opts.test,
674 let mut loader = macro_import::MacroLoader::new(sess, &cstore, crate_name);
675 let mut ecx = syntax::ext::base::ExtCtxt::new(&sess.parse_sess,
676 krate.config.clone(),
679 syntax_ext::register_builtins(&mut ecx.syntax_env);
680 let (ret, macro_names) = syntax::ext::expand::expand_crate(ecx,
684 env::set_var("PATH", &old_path);
686 *sess.available_macros.borrow_mut() = macro_names;
690 krate = time(time_passes, "maybe building test harness", || {
691 syntax::test::modify_for_testing(&sess.parse_sess,
697 let resolver_arenas = Resolver::arenas();
698 let mut resolver = Resolver::new(sess, make_glob_map, &resolver_arenas);
700 let krate = time(sess.time_passes(), "assigning node ids", || resolver.assign_node_ids(krate));
702 if sess.opts.debugging_opts.input_stats {
703 println!("Post-expansion node count: {}", count_nodes(&krate));
706 if sess.opts.debugging_opts.ast_json {
707 println!("{}", json::as_json(&krate));
711 "checking for inline asm in case the target doesn't support it",
712 || no_asm::check_crate(sess, &krate));
714 // Needs to go *after* expansion to be able to check the results of macro expansion.
715 time(time_passes, "complete gated feature checking", || {
716 sess.track_errors(|| {
717 syntax::feature_gate::check_crate(&krate,
719 &sess.features.borrow(),
721 sess.opts.unstable_features);
725 // Collect defintions for def ids.
726 time(sess.time_passes(), "collecting defs", || resolver.definitions.collect(&krate));
728 time(sess.time_passes(), "external crate/lib resolution", || {
729 let defs = &resolver.definitions;
730 read_local_crates(sess, &cstore, defs, &krate, crate_name, &sess.dep_graph)
733 time(sess.time_passes(),
735 || lint::check_ast_crate(sess, &krate));
737 time(sess.time_passes(),
739 || ast_validation::check_crate(sess, &krate));
741 time(sess.time_passes(), "name resolution", || -> CompileResult {
742 // Currently, we ignore the name resolution data structures for the purposes of dependency
743 // tracking. Instead we will run name resolution and include its output in the hash of each
744 // item, much like we do for macro expansion. In other words, the hash reflects not just
745 // its contents but the results of name resolution on those contents. Hopefully we'll push
746 // this back at some point.
747 let _ignore = sess.dep_graph.in_ignore();
748 resolver.build_reduced_graph(&krate);
749 resolver.resolve_imports();
751 // Since import resolution will eventually happen in expansion,
752 // don't perform `after_expand` until after import resolution.
753 after_expand(&krate)?;
755 resolver.resolve_crate(&krate);
760 let hir_forest = time(sess.time_passes(), "lowering ast -> hir", || {
761 hir_map::Forest::new(lower_crate(sess, &krate, &mut resolver), &sess.dep_graph)
764 // Discard MTWT tables that aren't required past lowering to HIR.
765 if !keep_mtwt_tables(sess) {
766 syntax::ext::mtwt::clear_tables();
770 expanded_crate: krate,
771 defs: resolver.definitions,
772 analysis: ty::CrateAnalysis {
773 export_map: resolver.export_map,
774 access_levels: AccessLevels::default(),
775 reachable: NodeSet(),
777 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
779 resolutions: Resolutions {
780 def_map: resolver.def_map,
781 freevars: resolver.freevars,
782 trait_map: resolver.trait_map,
783 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
785 hir_forest: hir_forest
789 /// Run the resolution, typechecking, region checking and other
790 /// miscellaneous analysis passes on the crate. Return various
791 /// structures carrying the results of the analysis.
792 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
793 hir_map: hir_map::Map<'tcx>,
794 mut analysis: ty::CrateAnalysis,
795 resolutions: Resolutions,
796 arenas: &'tcx ty::CtxtArenas<'tcx>,
800 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
801 Option<MirMap<'tcx>>,
805 macro_rules! try_with_f {
806 ($e: expr, ($t: expr, $m: expr, $a: expr)) => {
810 f($t, $m, $a, Err(x));
817 let time_passes = sess.time_passes();
819 let lang_items = time(time_passes, "language item collection", || {
820 sess.track_errors(|| {
821 middle::lang_items::collect_language_items(&sess, &hir_map)
825 let named_region_map = time(time_passes,
826 "lifetime resolution",
827 || middle::resolve_lifetime::krate(sess,
829 &resolutions.def_map))?;
832 "looking for entry point",
833 || middle::entry::find_entry_point(sess, &hir_map));
835 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
836 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
839 let region_map = time(time_passes,
841 || middle::region::resolve_crate(sess, &hir_map));
845 || loops::check_crate(sess, &hir_map));
848 "static item recursion checking",
849 || static_recursion::check_crate(sess, &resolutions.def_map, &hir_map))?;
851 let index = stability::Index::new(&hir_map);
853 let trait_map = resolutions.trait_map;
854 TyCtxt::create_and_enter(sess,
859 resolutions.freevars,
860 resolutions.maybe_unused_trait_imports,
868 || rustc_incremental::load_dep_graph(tcx));
870 // passes are timed inside typeck
871 try_with_f!(typeck::check_crate(tcx, trait_map), (tcx, None, analysis));
875 || consts::check_crate(tcx));
877 analysis.access_levels =
878 time(time_passes, "privacy checking", || {
879 rustc_privacy::check_crate(tcx, &analysis.export_map)
882 // Do not move this check past lint
883 time(time_passes, "stability index", || {
884 tcx.stability.borrow_mut().build(tcx, &analysis.access_levels)
888 "intrinsic checking",
889 || middle::intrinsicck::check_crate(tcx));
893 || middle::effect::check_crate(tcx));
897 || check_match::check_crate(tcx));
899 // this must run before MIR dump, because
900 // "not all control paths return a value" is reported here.
902 // maybe move the check to a MIR pass?
905 || middle::liveness::check_crate(tcx));
909 || rvalues::check_crate(tcx));
914 || mir::mir_map::build_mir_for_crate(tcx));
916 time(time_passes, "MIR passes", || {
917 let mut passes = sess.mir_passes.borrow_mut();
918 // Push all the built-in passes.
919 passes.push_hook(box mir::transform::dump_mir::DumpMir);
920 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("initial"));
921 passes.push_pass(box mir::transform::qualify_consts::QualifyAndPromoteConstants);
922 passes.push_pass(box mir::transform::type_check::TypeckMir);
924 box mir::transform::simplify_branches::SimplifyBranches::new("initial"));
925 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("qualify-consts"));
926 // And run everything.
927 passes.run_passes(tcx, &mut mir_map);
932 || borrowck::check_crate(tcx, &mir_map));
934 // Avoid overwhelming user with errors if type checking failed.
935 // I'm not sure how helpful this is, to be honest, but it avoids
937 // lot of annoying errors in the compile-fail tests (basically,
938 // lint warnings and so on -- kindck used to do this abort, but
939 // kindck is gone now). -nmatsakis
940 if sess.err_count() > 0 {
941 return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
946 "reachability checking",
947 || reachable::find_reachable(tcx, &analysis.access_levels));
949 time(time_passes, "death checking", || {
950 middle::dead::check_crate(tcx, &analysis.access_levels);
953 let ref lib_features_used =
955 "stability checking",
956 || stability::check_unstable_api_usage(tcx));
958 time(time_passes, "unused lib feature checking", || {
959 stability::check_unused_or_stable_features(&tcx.sess,
965 || lint::check_crate(tcx, &analysis.access_levels));
967 // The above three passes generate errors w/o aborting
968 if sess.err_count() > 0 {
969 return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
972 Ok(f(tcx, Some(mir_map), analysis, Ok(())))
976 /// Run the translation phase to LLVM, after which the AST and analysis can
977 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
978 mut mir_map: MirMap<'tcx>,
979 analysis: ty::CrateAnalysis)
980 -> trans::CrateTranslation {
981 let time_passes = tcx.sess.time_passes();
984 "resolving dependency formats",
985 || dependency_format::calculate(&tcx.sess));
987 // Run the passes that transform the MIR into a more suitable for translation
989 time(time_passes, "Prepare MIR codegen passes", || {
990 let mut passes = ::rustc::mir::transform::Passes::new();
991 passes.push_hook(box mir::transform::dump_mir::DumpMir);
992 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
993 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("no-landing-pads"));
995 passes.push_pass(box mir::transform::erase_regions::EraseRegions);
997 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
998 passes.push_pass(box borrowck::ElaborateDrops);
999 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1000 passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("elaborate-drops"));
1002 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1003 passes.push_pass(box mir::transform::dump_mir::Marker("PreTrans"));
1005 passes.run_passes(tcx, &mut mir_map);
1011 move || trans::trans_crate(tcx, &mir_map, analysis));
1015 move || rustc_incremental::assert_dep_graph(tcx));
1018 "serialize dep graph",
1019 move || rustc_incremental::save_dep_graph(tcx));
1024 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1025 /// as a side effect.
1026 pub fn phase_5_run_llvm_passes(sess: &Session,
1027 trans: &trans::CrateTranslation,
1028 outputs: &OutputFilenames) -> CompileResult {
1029 if sess.opts.cg.no_integrated_as {
1030 let mut map = HashMap::new();
1031 map.insert(OutputType::Assembly, None);
1032 time(sess.time_passes(),
1034 || write::run_passes(sess, trans, &map, outputs));
1036 write::run_assembler(sess, outputs);
1038 // Remove assembly source, unless --save-temps was specified
1039 if !sess.opts.cg.save_temps {
1040 fs::remove_file(&outputs.temp_path(OutputType::Assembly, None)).unwrap();
1043 time(sess.time_passes(),
1045 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1048 if sess.err_count() > 0 {
1049 Err(sess.err_count())
1055 /// Run the linker on any artifacts that resulted from the LLVM run.
1056 /// This should produce either a finished executable or library.
1057 pub fn phase_6_link_output(sess: &Session,
1058 trans: &trans::CrateTranslation,
1059 outputs: &OutputFilenames) {
1060 time(sess.time_passes(),
1062 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
1065 fn escape_dep_filename(filename: &str) -> String {
1066 // Apparently clang and gcc *only* escape spaces:
1067 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1068 filename.replace(" ", "\\ ")
1071 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
1072 let mut out_filenames = Vec::new();
1073 for output_type in sess.opts.output_types.keys() {
1074 let file = outputs.path(*output_type);
1075 match *output_type {
1076 OutputType::Exe => {
1077 for output in sess.crate_types.borrow().iter() {
1078 let p = link::filename_for_input(sess, *output, id, outputs);
1079 out_filenames.push(p);
1083 out_filenames.push(file);
1088 // Write out dependency rules to the dep-info file if requested
1089 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1092 let deps_filename = outputs.path(OutputType::DepInfo);
1095 (|| -> io::Result<()> {
1096 // Build a list of files used to compile the output and
1097 // write Makefile-compatible dependency rules
1098 let files: Vec<String> = sess.codemap()
1102 .filter(|fmap| fmap.is_real_file())
1103 .filter(|fmap| !fmap.is_imported())
1104 .map(|fmap| escape_dep_filename(&fmap.name))
1106 let mut file = fs::File::create(&deps_filename)?;
1107 for path in &out_filenames {
1108 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1111 // Emit a fake target for each input file to the compilation. This
1112 // prevents `make` from spitting out an error if a file is later
1113 // deleted. For more info see #28735
1115 writeln!(file, "{}:", path)?;
1123 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1124 deps_filename.display(),
1130 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1131 // Unconditionally collect crate types from attributes to make them used
1132 let attr_types: Vec<config::CrateType> =
1135 if a.check_name("crate_type") {
1136 match a.value_str() {
1137 Some(ref n) if *n == "rlib" => {
1138 Some(config::CrateTypeRlib)
1140 Some(ref n) if *n == "dylib" => {
1141 Some(config::CrateTypeDylib)
1143 Some(ref n) if *n == "cdylib" => {
1144 Some(config::CrateTypeCdylib)
1146 Some(ref n) if *n == "lib" => {
1147 Some(config::default_lib_output())
1149 Some(ref n) if *n == "staticlib" => {
1150 Some(config::CrateTypeStaticlib)
1152 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1154 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1157 "invalid `crate_type` value".to_string());
1161 session.struct_span_err(a.span, "`crate_type` requires a value")
1162 .note("for example: `#![crate_type=\"lib\"]`")
1173 // If we're generating a test executable, then ignore all other output
1174 // styles at all other locations
1175 if session.opts.test {
1176 return vec![config::CrateTypeExecutable];
1179 // Only check command line flags if present. If no types are specified by
1180 // command line, then reuse the empty `base` Vec to hold the types that
1181 // will be found in crate attributes.
1182 let mut base = session.opts.crate_types.clone();
1183 if base.is_empty() {
1184 base.extend(attr_types);
1185 if base.is_empty() {
1186 base.push(link::default_output_for_target(session));
1193 .filter(|crate_type| {
1194 let res = !link::invalid_output_for_target(session, *crate_type);
1197 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1199 session.opts.target_triple));
1207 pub fn compute_crate_disambiguator(session: &Session) -> String {
1208 let mut hasher = Sha256::new();
1210 let mut metadata = session.opts.cg.metadata.clone();
1211 // We don't want the crate_disambiguator to dependent on the order
1212 // -C metadata arguments, so sort them:
1214 // Every distinct -C metadata value is only incorporated once:
1217 hasher.input_str("metadata");
1218 for s in &metadata {
1219 // Also incorporate the length of a metadata string, so that we generate
1220 // different values for `-Cmetadata=ab -Cmetadata=c` and
1221 // `-Cmetadata=a -Cmetadata=bc`
1222 hasher.input_str(&format!("{}", s.len())[..]);
1223 hasher.input_str(&s[..]);
1226 let mut hash = hasher.result_str();
1228 // If this is an executable, add a special suffix, so that we don't get
1229 // symbol conflicts when linking against a library of the same name.
1230 if session.crate_types.borrow().contains(&config::CrateTypeExecutable) {
1231 hash.push_str("-exe");
1237 pub fn build_output_filenames(input: &Input,
1238 odir: &Option<PathBuf>,
1239 ofile: &Option<PathBuf>,
1240 attrs: &[ast::Attribute],
1242 -> OutputFilenames {
1245 // "-" as input file will cause the parser to read from stdin so we
1246 // have to make up a name
1247 // We want to toss everything after the final '.'
1248 let dirpath = match *odir {
1249 Some(ref d) => d.clone(),
1250 None => PathBuf::new(),
1253 // If a crate name is present, we use it as the link name
1254 let stem = sess.opts
1257 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1258 .unwrap_or(input.filestem());
1261 out_directory: dirpath,
1263 single_output_file: None,
1264 extra: sess.opts.cg.extra_filename.clone(),
1265 outputs: sess.opts.output_types.clone(),
1269 Some(ref out_file) => {
1270 let unnamed_output_types = sess.opts
1273 .filter(|a| a.is_none())
1275 let ofile = if unnamed_output_types > 1 {
1276 sess.warn("ignoring specified output filename because multiple outputs were \
1280 Some(out_file.clone())
1283 sess.warn("ignoring --out-dir flag due to -o flag.");
1286 let cur_dir = Path::new("");
1289 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1290 out_filestem: out_file.file_stem()
1291 .unwrap_or(OsStr::new(""))
1295 single_output_file: ofile,
1296 extra: sess.opts.cg.extra_filename.clone(),
1297 outputs: sess.opts.output_types.clone(),