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_data_structures::stable_hasher::StableHasher;
15 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
16 use rustc::session::config::{self, Input, OutputFilenames, OutputType,
18 use rustc::session::search_paths::PathKind;
20 use rustc::middle::{self, dependency_format, stability, reachable};
21 use rustc::middle::privacy::AccessLevels;
22 use rustc::ty::{self, TyCtxt, Resolutions};
23 use rustc::util::common::time;
24 use rustc::util::nodemap::{NodeSet, NodeMap};
25 use rustc_borrowck as borrowck;
26 use rustc_incremental::{self, IncrementalHashesMap};
27 use rustc_incremental::ich::Fingerprint;
28 use rustc_resolve::{MakeGlobMap, Resolver};
29 use rustc_metadata::creader::CrateLoader;
30 use rustc_metadata::cstore::CStore;
31 use rustc_trans::back::{link, write};
32 use rustc_trans as trans;
33 use rustc_typeck as typeck;
35 use rustc_plugin::registry::Registry;
36 use rustc_plugin as plugin;
37 use rustc_passes::{ast_validation, no_asm, loops, consts, rvalues,
38 static_recursion, hir_stats, mir_stats};
39 use rustc_const_eval::check_match;
40 use super::Compilation;
46 use std::ffi::{OsString, OsStr};
48 use std::io::{self, Write};
49 use std::path::{Path, PathBuf};
50 use syntax::{ast, diagnostics, visit};
52 use syntax::ext::base::ExtCtxt;
53 use syntax::parse::{self, PResult};
54 use syntax::symbol::Symbol;
55 use syntax::util::node_count::NodeCounter;
61 pub fn compile_input(sess: &Session,
64 outdir: &Option<PathBuf>,
65 output: &Option<PathBuf>,
66 addl_plugins: Option<Vec<String>>,
67 control: &CompileController) -> CompileResult {
68 macro_rules! controller_entry_point {
69 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
70 let state = &mut $make_state;
71 let phase_result: &CompileResult = &$phase_result;
72 if phase_result.is_ok() || control.$point.run_callback_on_error {
73 (control.$point.callback)(state);
76 if control.$point.stop == Compilation::Stop {
77 return compile_result_from_err_count($tsess.err_count());
82 // We need nested scopes here, because the intermediate results can keep
83 // large chunks of memory alive and we want to free them as soon as
84 // possible to keep the peak memory usage low
85 let (outputs, trans) = {
86 let krate = match phase_1_parse_input(sess, input) {
88 Err(mut parse_error) => {
94 let (krate, registry) = {
95 let mut compile_state = CompileState::state_after_parse(input,
101 controller_entry_point!(after_parse,
106 (compile_state.krate.unwrap(), compile_state.registry)
109 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
110 let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
111 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
112 phase_2_configure_and_expand(
113 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
115 let mut state = CompileState::state_after_expand(
116 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
118 controller_entry_point!(after_expand, sess, state, Ok(()));
124 write_out_deps(sess, &outputs, &crate_name);
126 let arenas = ty::CtxtArenas::new();
128 // Construct the HIR map
129 let hir_map = time(sess.time_passes(),
131 || hir_map::map_crate(&mut hir_forest, defs));
134 let _ignore = hir_map.dep_graph.in_ignore();
135 controller_entry_point!(after_hir_lowering,
137 CompileState::state_after_hir_lowering(input,
152 time(sess.time_passes(), "attribute checking", || {
153 hir::check_attr::check_crate(sess, &expanded_crate);
156 let opt_crate = if keep_ast(sess) {
157 Some(&expanded_crate)
159 drop(expanded_crate);
163 phase_3_run_analysis_passes(sess,
169 |tcx, analysis, incremental_hashes_map, result| {
171 // Eventually, we will want to track plugins.
172 let _ignore = tcx.dep_graph.in_ignore();
174 let mut state = CompileState::state_after_analysis(input,
183 (control.after_analysis.callback)(&mut state);
185 if control.after_analysis.stop == Compilation::Stop {
186 return result.and_then(|_| Err(0usize));
192 if log_enabled!(::log::INFO) {
193 println!("Pre-trans");
194 tcx.print_debug_stats();
196 let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map);
198 if log_enabled!(::log::INFO) {
199 println!("Post-trans");
200 tcx.print_debug_stats();
207 if sess.opts.debugging_opts.print_type_sizes {
208 sess.code_stats.borrow().print_type_sizes();
211 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
213 controller_entry_point!(after_llvm,
215 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
219 write::cleanup_llvm(&trans);
221 phase_6_link_output(sess, &trans, &outputs);
223 // Now that we won't touch anything in the incremental compilation directory
224 // any more, we can finalize it (which involves renaming it)
225 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
227 if sess.opts.debugging_opts.perf_stats {
228 sess.print_perf_stats();
231 controller_entry_point!(compilation_done,
233 CompileState::state_when_compilation_done(input, sess, outdir, output),
239 fn keep_hygiene_data(sess: &Session) -> bool {
240 sess.opts.debugging_opts.keep_hygiene_data
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 ||
247 sess.opts.debugging_opts.save_analysis_api
250 /// The name used for source code that doesn't originate in a file
251 /// (e.g. source from stdin or a string)
252 pub fn anon_src() -> String {
256 pub fn source_name(input: &Input) -> String {
258 // FIXME (#9639): This needs to handle non-utf8 paths
259 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
260 Input::Str { ref name, .. } => name.clone(),
264 /// CompileController is used to customise compilation, it allows compilation to
265 /// be stopped and/or to call arbitrary code at various points in compilation.
266 /// It also allows for various flags to be set to influence what information gets
267 /// collected during compilation.
269 /// This is a somewhat higher level controller than a Session - the Session
270 /// controls what happens in each phase, whereas the CompileController controls
271 /// whether a phase is run at all and whether other code (from outside the
272 /// the compiler) is run between phases.
274 /// Note that if compilation is set to stop and a callback is provided for a
275 /// given entry point, the callback is called before compilation is stopped.
277 /// Expect more entry points to be added in the future.
278 pub struct CompileController<'a> {
279 pub after_parse: PhaseController<'a>,
280 pub after_expand: PhaseController<'a>,
281 pub after_hir_lowering: PhaseController<'a>,
282 pub after_analysis: PhaseController<'a>,
283 pub after_llvm: PhaseController<'a>,
284 pub compilation_done: PhaseController<'a>,
286 pub make_glob_map: MakeGlobMap,
289 impl<'a> CompileController<'a> {
290 pub fn basic() -> CompileController<'a> {
292 after_parse: PhaseController::basic(),
293 after_expand: PhaseController::basic(),
294 after_hir_lowering: PhaseController::basic(),
295 after_analysis: PhaseController::basic(),
296 after_llvm: PhaseController::basic(),
297 compilation_done: PhaseController::basic(),
298 make_glob_map: MakeGlobMap::No,
303 pub struct PhaseController<'a> {
304 pub stop: Compilation,
305 // If true then the compiler will try to run the callback even if the phase
306 // ends with an error. Note that this is not always possible.
307 pub run_callback_on_error: bool,
308 pub callback: Box<Fn(&mut CompileState) + 'a>,
311 impl<'a> PhaseController<'a> {
312 pub fn basic() -> PhaseController<'a> {
314 stop: Compilation::Continue,
315 run_callback_on_error: false,
316 callback: box |_| {},
321 /// State that is passed to a callback. What state is available depends on when
322 /// during compilation the callback is made. See the various constructor methods
323 /// (`state_*`) in the impl to see which data is provided for any given entry point.
324 pub struct CompileState<'a, 'tcx: 'a> {
325 pub input: &'a Input,
326 pub session: &'tcx Session,
327 pub krate: Option<ast::Crate>,
328 pub registry: Option<Registry<'a>>,
329 pub cstore: Option<&'a CStore>,
330 pub crate_name: Option<&'a str>,
331 pub output_filenames: Option<&'a OutputFilenames>,
332 pub out_dir: Option<&'a Path>,
333 pub out_file: Option<&'a Path>,
334 pub arenas: Option<&'tcx ty::CtxtArenas<'tcx>>,
335 pub expanded_crate: Option<&'a ast::Crate>,
336 pub hir_crate: Option<&'a hir::Crate>,
337 pub ast_map: Option<&'a hir_map::Map<'tcx>>,
338 pub resolutions: Option<&'a Resolutions>,
339 pub analysis: Option<&'a ty::CrateAnalysis<'tcx>>,
340 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
341 pub trans: Option<&'a trans::CrateTranslation>,
344 impl<'a, 'tcx> CompileState<'a, 'tcx> {
345 fn empty(input: &'a Input,
346 session: &'tcx Session,
347 out_dir: &'a Option<PathBuf>)
352 out_dir: out_dir.as_ref().map(|s| &**s),
359 output_filenames: None,
360 expanded_crate: None,
370 fn state_after_parse(input: &'a Input,
371 session: &'tcx Session,
372 out_dir: &'a Option<PathBuf>,
373 out_file: &'a Option<PathBuf>,
378 // Initialize the registry before moving `krate`
379 registry: Some(Registry::new(&session, krate.span)),
381 cstore: Some(cstore),
382 out_file: out_file.as_ref().map(|s| &**s),
383 ..CompileState::empty(input, session, out_dir)
387 fn state_after_expand(input: &'a Input,
388 session: &'tcx Session,
389 out_dir: &'a Option<PathBuf>,
390 out_file: &'a Option<PathBuf>,
392 expanded_crate: &'a ast::Crate,
396 crate_name: Some(crate_name),
397 cstore: Some(cstore),
398 expanded_crate: Some(expanded_crate),
399 out_file: out_file.as_ref().map(|s| &**s),
400 ..CompileState::empty(input, session, out_dir)
404 fn state_after_hir_lowering(input: &'a Input,
405 session: &'tcx Session,
406 out_dir: &'a Option<PathBuf>,
407 out_file: &'a Option<PathBuf>,
408 arenas: &'tcx ty::CtxtArenas<'tcx>,
410 hir_map: &'a hir_map::Map<'tcx>,
411 analysis: &'a ty::CrateAnalysis<'static>,
412 resolutions: &'a Resolutions,
413 krate: &'a ast::Crate,
414 hir_crate: &'a hir::Crate,
418 crate_name: Some(crate_name),
419 arenas: Some(arenas),
420 cstore: Some(cstore),
421 ast_map: Some(hir_map),
422 analysis: Some(analysis),
423 resolutions: Some(resolutions),
424 expanded_crate: Some(krate),
425 hir_crate: Some(hir_crate),
426 out_file: out_file.as_ref().map(|s| &**s),
427 ..CompileState::empty(input, session, out_dir)
431 fn state_after_analysis(input: &'a Input,
432 session: &'tcx Session,
433 out_dir: &'a Option<PathBuf>,
434 out_file: &'a Option<PathBuf>,
435 krate: Option<&'a ast::Crate>,
436 hir_crate: &'a hir::Crate,
437 analysis: &'a ty::CrateAnalysis<'tcx>,
438 tcx: TyCtxt<'a, 'tcx, 'tcx>,
442 analysis: Some(analysis),
444 expanded_crate: krate,
445 hir_crate: Some(hir_crate),
446 crate_name: Some(crate_name),
447 out_file: out_file.as_ref().map(|s| &**s),
448 ..CompileState::empty(input, session, out_dir)
453 fn state_after_llvm(input: &'a Input,
454 session: &'tcx Session,
455 out_dir: &'a Option<PathBuf>,
456 out_file: &'a Option<PathBuf>,
457 trans: &'a trans::CrateTranslation)
461 out_file: out_file.as_ref().map(|s| &**s),
462 ..CompileState::empty(input, session, out_dir)
466 fn state_when_compilation_done(input: &'a Input,
467 session: &'tcx Session,
468 out_dir: &'a Option<PathBuf>,
469 out_file: &'a Option<PathBuf>)
472 out_file: out_file.as_ref().map(|s| &**s),
473 ..CompileState::empty(input, session, out_dir)
478 pub fn phase_1_parse_input<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
479 let continue_after_error = sess.opts.debugging_opts.continue_parse_after_error;
480 sess.diagnostic().set_continue_after_error(continue_after_error);
482 let krate = time(sess.time_passes(), "parsing", || {
484 Input::File(ref file) => {
485 parse::parse_crate_from_file(file, &sess.parse_sess)
487 Input::Str { ref input, ref name } => {
488 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
493 sess.diagnostic().set_continue_after_error(true);
495 if sess.opts.debugging_opts.ast_json_noexpand {
496 println!("{}", json::as_json(&krate));
499 if sess.opts.debugging_opts.input_stats {
500 println!("Lines of code: {}", sess.codemap().count_lines());
501 println!("Pre-expansion node count: {}", count_nodes(&krate));
504 if let Some(ref s) = sess.opts.debugging_opts.show_span {
505 syntax::show_span::run(sess.diagnostic(), s, &krate);
508 if sess.opts.debugging_opts.hir_stats {
509 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
515 fn count_nodes(krate: &ast::Crate) -> usize {
516 let mut counter = NodeCounter::new();
517 visit::walk_crate(&mut counter, krate);
521 // For continuing compilation after a parsed crate has been
524 pub struct ExpansionResult {
525 pub expanded_crate: ast::Crate,
526 pub defs: hir_map::Definitions,
527 pub analysis: ty::CrateAnalysis<'static>,
528 pub resolutions: Resolutions,
529 pub hir_forest: hir_map::Forest,
532 /// Run the "early phases" of the compiler: initial `cfg` processing,
533 /// loading compiler plugins (including those from `addl_plugins`),
534 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
535 /// harness if one is to be provided, injection of a dependency on the
536 /// standard library and prelude, and name resolution.
538 /// Returns `None` if we're aborting after handling -W help.
539 pub fn phase_2_configure_and_expand<F>(sess: &Session,
542 registry: Option<Registry>,
544 addl_plugins: Option<Vec<String>>,
545 make_glob_map: MakeGlobMap,
547 -> Result<ExpansionResult, usize>
548 where F: FnOnce(&ast::Crate) -> CompileResult,
550 let time_passes = sess.time_passes();
552 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
553 // these need to be set "early" so that expansion sees `quote` if enabled.
554 *sess.features.borrow_mut() = features;
556 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
557 *sess.crate_disambiguator.borrow_mut() = Symbol::intern(&compute_crate_disambiguator(sess));
559 time(time_passes, "recursion limit", || {
560 middle::recursion_limit::update_limits(sess, &krate);
563 krate = time(time_passes, "crate injection", || {
564 let alt_std_name = sess.opts.alt_std_name.clone();
565 syntax::std_inject::maybe_inject_crates_ref(&sess.parse_sess, krate, alt_std_name)
568 let mut addl_plugins = Some(addl_plugins);
569 let registrars = time(time_passes, "plugin loading", || {
570 plugin::load::load_plugins(sess,
574 addl_plugins.take().unwrap())
577 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
579 time(time_passes, "plugin registration", || {
580 if sess.features.borrow().rustc_diagnostic_macros {
581 registry.register_macro("__diagnostic_used",
582 diagnostics::plugin::expand_diagnostic_used);
583 registry.register_macro("__register_diagnostic",
584 diagnostics::plugin::expand_register_diagnostic);
585 registry.register_macro("__build_diagnostic_array",
586 diagnostics::plugin::expand_build_diagnostic_array);
589 for registrar in registrars {
590 registry.args_hidden = Some(registrar.args);
591 (registrar.fun)(&mut registry);
595 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
596 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
597 llvm_passes, attributes, mir_passes, .. } = registry;
599 sess.track_errors(|| {
600 let mut ls = sess.lint_store.borrow_mut();
601 for pass in early_lint_passes {
602 ls.register_early_pass(Some(sess), true, pass);
604 for pass in late_lint_passes {
605 ls.register_late_pass(Some(sess), true, pass);
608 for (name, to) in lint_groups {
609 ls.register_group(Some(sess), true, name, to);
612 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
613 sess.mir_passes.borrow_mut().extend(mir_passes);
614 *sess.plugin_attributes.borrow_mut() = attributes.clone();
617 // Lint plugins are registered; now we can process command line flags.
618 if sess.opts.describe_lints {
619 super::describe_lints(&sess.lint_store.borrow(), true);
622 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
624 // Currently, we ignore the name resolution data structures for the purposes of dependency
625 // tracking. Instead we will run name resolution and include its output in the hash of each
626 // item, much like we do for macro expansion. In other words, the hash reflects not just
627 // its contents but the results of name resolution on those contents. Hopefully we'll push
628 // this back at some point.
629 let _ignore = sess.dep_graph.in_ignore();
630 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
631 crate_loader.preprocess(&krate);
632 let resolver_arenas = Resolver::arenas();
634 Resolver::new(sess, &krate, make_glob_map, &mut crate_loader, &resolver_arenas);
635 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
636 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
638 krate = time(time_passes, "expansion", || {
639 // Windows dlls do not have rpaths, so they don't know how to find their
640 // dependencies. It's up to us to tell the system where to find all the
641 // dependent dlls. Note that this uses cfg!(windows) as opposed to
642 // targ_cfg because syntax extensions are always loaded for the host
643 // compiler, not for the target.
645 // This is somewhat of an inherently racy operation, however, as
646 // multiple threads calling this function could possibly continue
647 // extending PATH far beyond what it should. To solve this for now we
648 // just don't add any new elements to PATH which are already there
649 // within PATH. This is basically a targeted fix at #17360 for rustdoc
650 // which runs rustc in parallel but has been seen (#33844) to cause
651 // problems with PATH becoming too long.
652 let mut old_path = OsString::new();
654 old_path = env::var_os("PATH").unwrap_or(old_path);
655 let mut new_path = sess.host_filesearch(PathKind::All)
656 .get_dylib_search_paths();
657 for path in env::split_paths(&old_path) {
658 if !new_path.contains(&path) {
662 env::set_var("PATH", &env::join_paths(new_path).unwrap());
664 let features = sess.features.borrow();
665 let cfg = syntax::ext::expand::ExpansionConfig {
666 features: Some(&features),
667 recursion_limit: sess.recursion_limit.get(),
668 trace_mac: sess.opts.debugging_opts.trace_macros,
669 should_test: sess.opts.test,
670 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
672 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
673 let err_count = ecx.parse_sess.span_diagnostic.err_count();
675 let krate = ecx.monotonic_expander().expand_crate(krate);
677 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
678 ecx.parse_sess.span_diagnostic.abort_if_errors();
681 env::set_var("PATH", &old_path);
686 krate.exported_macros = mem::replace(&mut resolver.exported_macros, Vec::new());
688 krate = time(time_passes, "maybe building test harness", || {
689 syntax::test::modify_for_testing(&sess.parse_sess,
696 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
697 // bunch of checks in the `modify` function below. For now just skip this
698 // step entirely if we're rustdoc as it's not too useful anyway.
699 if !sess.opts.actually_rustdoc {
700 krate = time(time_passes, "maybe creating a macro crate", || {
701 let crate_types = sess.crate_types.borrow();
702 let num_crate_types = crate_types.len();
703 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
704 let is_test_crate = sess.opts.test;
705 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
712 &sess.features.borrow())
716 if sess.opts.debugging_opts.input_stats {
717 println!("Post-expansion node count: {}", count_nodes(&krate));
720 if sess.opts.debugging_opts.hir_stats {
721 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
724 if sess.opts.debugging_opts.ast_json {
725 println!("{}", json::as_json(&krate));
729 "checking for inline asm in case the target doesn't support it",
730 || no_asm::check_crate(sess, &krate));
732 // Needs to go *after* expansion to be able to check the results of macro expansion.
733 time(time_passes, "complete gated feature checking", || {
734 sess.track_errors(|| {
735 syntax::feature_gate::check_crate(&krate,
737 &sess.features.borrow(),
739 sess.opts.unstable_features);
743 time(sess.time_passes(),
745 || lint::check_ast_crate(sess, &krate));
747 time(sess.time_passes(),
749 || ast_validation::check_crate(sess, &krate));
751 time(sess.time_passes(), "name resolution", || -> CompileResult {
752 // Since import resolution will eventually happen in expansion,
753 // don't perform `after_expand` until after import resolution.
754 after_expand(&krate)?;
756 resolver.resolve_crate(&krate);
761 let hir_forest = time(sess.time_passes(), "lowering ast -> hir", || {
762 let hir_crate = lower_crate(sess, &krate, &mut resolver);
764 if sess.opts.debugging_opts.hir_stats {
765 hir_stats::print_hir_stats(&hir_crate);
768 hir_map::Forest::new(hir_crate, &sess.dep_graph)
771 // Discard hygiene data, which isn't required past lowering to HIR.
772 if !keep_hygiene_data(sess) {
773 syntax::ext::hygiene::reset_hygiene_data();
777 expanded_crate: krate,
778 defs: resolver.definitions,
779 analysis: ty::CrateAnalysis {
780 export_map: resolver.export_map,
781 access_levels: AccessLevels::default(),
782 reachable: NodeSet(),
783 name: crate_name.to_string(),
784 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
785 hir_ty_to_ty: NodeMap(),
787 resolutions: Resolutions {
788 freevars: resolver.freevars,
789 trait_map: resolver.trait_map,
790 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
792 hir_forest: hir_forest
796 /// Run the resolution, typechecking, region checking and other
797 /// miscellaneous analysis passes on the crate. Return various
798 /// structures carrying the results of the analysis.
799 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
800 hir_map: hir_map::Map<'tcx>,
801 mut analysis: ty::CrateAnalysis<'tcx>,
802 resolutions: Resolutions,
803 arenas: &'tcx ty::CtxtArenas<'tcx>,
807 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
808 ty::CrateAnalysis<'tcx>,
809 IncrementalHashesMap,
812 macro_rules! try_with_f {
813 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
817 f($t, $a, $h, Err(x));
824 let time_passes = sess.time_passes();
826 let lang_items = time(time_passes, "language item collection", || {
827 sess.track_errors(|| {
828 middle::lang_items::collect_language_items(&sess, &hir_map)
832 let named_region_map = time(time_passes,
833 "lifetime resolution",
834 || middle::resolve_lifetime::krate(sess, &hir_map))?;
837 "looking for entry point",
838 || middle::entry::find_entry_point(sess, &hir_map));
840 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
841 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
843 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
845 let region_map = time(time_passes,
847 || middle::region::resolve_crate(sess, &hir_map));
851 || loops::check_crate(sess, &hir_map));
854 "static item recursion checking",
855 || static_recursion::check_crate(sess, &hir_map))?;
857 let index = stability::Index::new(&hir_map);
859 TyCtxt::create_and_enter(sess,
869 let incremental_hashes_map =
871 "compute_incremental_hashes_map",
872 || rustc_incremental::compute_incremental_hashes_map(tcx));
875 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
877 time(time_passes, "stability index", || {
878 tcx.stability.borrow_mut().build(tcx)
882 "stability checking",
883 || stability::check_unstable_api_usage(tcx));
885 // passes are timed inside typeck
886 analysis.hir_ty_to_ty =
887 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
891 || consts::check_crate(tcx));
893 analysis.access_levels =
894 time(time_passes, "privacy checking", || {
895 rustc_privacy::check_crate(tcx, &analysis.export_map)
899 "intrinsic checking",
900 || middle::intrinsicck::check_crate(tcx));
904 || middle::effect::check_crate(tcx));
908 || check_match::check_crate(tcx));
910 // this must run before MIR dump, because
911 // "not all control paths return a value" is reported here.
913 // maybe move the check to a MIR pass?
916 || middle::liveness::check_crate(tcx));
920 || rvalues::check_crate(tcx));
924 || mir::mir_map::build_mir_for_crate(tcx));
926 if sess.opts.debugging_opts.mir_stats {
927 mir_stats::print_mir_stats(tcx, "PRE CLEANUP MIR STATS");
930 time(time_passes, "MIR cleanup and validation", || {
931 let mut passes = sess.mir_passes.borrow_mut();
932 // Push all the built-in validation passes.
933 // NB: if you’re adding an *optimisation* it ought to go to another set of passes
935 passes.push_hook(box mir::transform::dump_mir::DumpMir);
936 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("initial"));
938 box mir::transform::qualify_consts::QualifyAndPromoteConstants::default());
939 passes.push_pass(box mir::transform::type_check::TypeckMir);
941 box mir::transform::simplify_branches::SimplifyBranches::new("initial"));
942 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
943 // And run everything.
944 passes.run_passes(tcx);
949 || borrowck::check_crate(tcx));
951 // Avoid overwhelming user with errors if type checking failed.
952 // I'm not sure how helpful this is, to be honest, but it avoids
954 // lot of annoying errors in the compile-fail tests (basically,
955 // lint warnings and so on -- kindck used to do this abort, but
956 // kindck is gone now). -nmatsakis
957 if sess.err_count() > 0 {
958 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
963 "reachability checking",
964 || reachable::find_reachable(tcx, &analysis.access_levels));
966 time(time_passes, "death checking", || {
967 middle::dead::check_crate(tcx, &analysis.access_levels);
970 time(time_passes, "unused lib feature checking", || {
971 stability::check_unused_or_stable_features(tcx, &analysis.access_levels)
976 || lint::check_crate(tcx, &analysis.access_levels));
978 // The above three passes generate errors w/o aborting
979 if sess.err_count() > 0 {
980 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
983 Ok(f(tcx, analysis, incremental_hashes_map, Ok(())))
987 /// Run the translation phase to LLVM, after which the AST and analysis can
988 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
989 analysis: ty::CrateAnalysis,
990 incremental_hashes_map: &IncrementalHashesMap)
991 -> trans::CrateTranslation {
992 let time_passes = tcx.sess.time_passes();
995 "resolving dependency formats",
996 || dependency_format::calculate(&tcx.sess));
998 if tcx.sess.opts.debugging_opts.mir_stats {
999 mir_stats::print_mir_stats(tcx, "PRE OPTIMISATION MIR STATS");
1002 // Run the passes that transform the MIR into a more suitable form for translation to LLVM
1004 time(time_passes, "MIR optimisations", || {
1005 let mut passes = ::rustc::mir::transform::Passes::new();
1006 passes.push_hook(box mir::transform::dump_mir::DumpMir);
1007 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1008 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("no-landing-pads"));
1010 // From here on out, regions are gone.
1011 passes.push_pass(box mir::transform::erase_regions::EraseRegions);
1013 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1014 passes.push_pass(box borrowck::ElaborateDrops);
1015 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1016 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
1018 // No lifetime analysis based on borrowing can be done from here on out.
1019 passes.push_pass(box mir::transform::instcombine::InstCombine::new());
1020 passes.push_pass(box mir::transform::deaggregator::Deaggregator);
1021 passes.push_pass(box mir::transform::copy_prop::CopyPropagation);
1023 passes.push_pass(box mir::transform::simplify::SimplifyLocals);
1024 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1025 passes.push_pass(box mir::transform::dump_mir::Marker("PreTrans"));
1027 passes.run_passes(tcx);
1030 if tcx.sess.opts.debugging_opts.mir_stats {
1031 mir_stats::print_mir_stats(tcx, "POST OPTIMISATION MIR STATS");
1037 move || trans::trans_crate(tcx, analysis, &incremental_hashes_map));
1041 || rustc_incremental::assert_dep_graph(tcx));
1044 "serialize dep graph",
1045 || rustc_incremental::save_dep_graph(tcx,
1046 &incremental_hashes_map,
1047 translation.link.crate_hash));
1051 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1052 /// as a side effect.
1053 pub fn phase_5_run_llvm_passes(sess: &Session,
1054 trans: &trans::CrateTranslation,
1055 outputs: &OutputFilenames) -> CompileResult {
1056 if sess.opts.cg.no_integrated_as ||
1057 (sess.target.target.options.no_integrated_as &&
1058 (outputs.outputs.contains_key(&OutputType::Object) ||
1059 outputs.outputs.contains_key(&OutputType::Exe)))
1061 let output_types = OutputTypes::new(&[(OutputType::Assembly, None)]);
1062 time(sess.time_passes(),
1064 || write::run_passes(sess, trans, &output_types, outputs));
1066 write::run_assembler(sess, outputs);
1068 // HACK the linker expects the object file to be named foo.0.o but
1069 // `run_assembler` produces an object named just foo.o. Rename it if we
1070 // are going to build an executable
1071 if sess.opts.output_types.contains_key(&OutputType::Exe) {
1072 let f = outputs.path(OutputType::Object);
1074 f.with_file_name(format!("{}.0.o",
1075 f.file_stem().unwrap().to_string_lossy()))).unwrap();
1076 fs::remove_file(f).unwrap();
1079 // Remove assembly source, unless --save-temps was specified
1080 if !sess.opts.cg.save_temps {
1081 fs::remove_file(&outputs.temp_path(OutputType::Assembly, None)).unwrap();
1084 time(sess.time_passes(),
1086 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1089 time(sess.time_passes(),
1090 "serialize work products",
1091 move || rustc_incremental::save_work_products(sess));
1093 if sess.err_count() > 0 {
1094 Err(sess.err_count())
1100 /// Run the linker on any artifacts that resulted from the LLVM run.
1101 /// This should produce either a finished executable or library.
1102 pub fn phase_6_link_output(sess: &Session,
1103 trans: &trans::CrateTranslation,
1104 outputs: &OutputFilenames) {
1105 time(sess.time_passes(),
1107 || link::link_binary(sess, trans, outputs, &trans.link.crate_name.as_str()));
1110 fn escape_dep_filename(filename: &str) -> String {
1111 // Apparently clang and gcc *only* escape spaces:
1112 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1113 filename.replace(" ", "\\ ")
1116 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1117 let mut out_filenames = Vec::new();
1118 for output_type in sess.opts.output_types.keys() {
1119 let file = outputs.path(*output_type);
1120 match *output_type {
1121 OutputType::Exe => {
1122 for output in sess.crate_types.borrow().iter() {
1123 let p = link::filename_for_input(sess, *output, crate_name, outputs);
1124 out_filenames.push(p);
1128 out_filenames.push(file);
1133 // Write out dependency rules to the dep-info file if requested
1134 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1137 let deps_filename = outputs.path(OutputType::DepInfo);
1140 (|| -> io::Result<()> {
1141 // Build a list of files used to compile the output and
1142 // write Makefile-compatible dependency rules
1143 let files: Vec<String> = sess.codemap()
1147 .filter(|fmap| fmap.is_real_file())
1148 .filter(|fmap| !fmap.is_imported())
1149 .map(|fmap| escape_dep_filename(&fmap.name))
1151 let mut file = fs::File::create(&deps_filename)?;
1152 for path in &out_filenames {
1153 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1156 // Emit a fake target for each input file to the compilation. This
1157 // prevents `make` from spitting out an error if a file is later
1158 // deleted. For more info see #28735
1160 writeln!(file, "{}:", path)?;
1168 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1169 deps_filename.display(),
1175 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1176 // Unconditionally collect crate types from attributes to make them used
1177 let attr_types: Vec<config::CrateType> =
1180 if a.check_name("crate_type") {
1181 match a.value_str() {
1182 Some(ref n) if *n == "rlib" => {
1183 Some(config::CrateTypeRlib)
1185 Some(ref n) if *n == "metadata" => {
1186 Some(config::CrateTypeMetadata)
1188 Some(ref n) if *n == "dylib" => {
1189 Some(config::CrateTypeDylib)
1191 Some(ref n) if *n == "cdylib" => {
1192 Some(config::CrateTypeCdylib)
1194 Some(ref n) if *n == "lib" => {
1195 Some(config::default_lib_output())
1197 Some(ref n) if *n == "staticlib" => {
1198 Some(config::CrateTypeStaticlib)
1200 Some(ref n) if *n == "proc-macro" => {
1201 Some(config::CrateTypeProcMacro)
1203 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1205 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1208 "invalid `crate_type` value".to_string());
1212 session.struct_span_err(a.span, "`crate_type` requires a value")
1213 .note("for example: `#![crate_type=\"lib\"]`")
1224 // If we're generating a test executable, then ignore all other output
1225 // styles at all other locations
1226 if session.opts.test {
1227 return vec![config::CrateTypeExecutable];
1230 // Only check command line flags if present. If no types are specified by
1231 // command line, then reuse the empty `base` Vec to hold the types that
1232 // will be found in crate attributes.
1233 let mut base = session.opts.crate_types.clone();
1234 if base.is_empty() {
1235 base.extend(attr_types);
1236 if base.is_empty() {
1237 base.push(link::default_output_for_target(session));
1244 .filter(|crate_type| {
1245 let res = !link::invalid_output_for_target(session, *crate_type);
1248 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1250 session.opts.target_triple));
1258 pub fn compute_crate_disambiguator(session: &Session) -> String {
1259 use std::hash::Hasher;
1261 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1262 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1263 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1264 // should still be safe enough to avoid collisions in practice.
1265 // FIXME(mw): It seems that the crate_disambiguator is used everywhere as
1266 // a hex-string instead of raw bytes. We should really use the
1267 // smaller representation.
1268 let mut hasher = StableHasher::<Fingerprint>::new();
1270 let mut metadata = session.opts.cg.metadata.clone();
1271 // We don't want the crate_disambiguator to dependent on the order
1272 // -C metadata arguments, so sort them:
1274 // Every distinct -C metadata value is only incorporated once:
1277 hasher.write(b"metadata");
1278 for s in &metadata {
1279 // Also incorporate the length of a metadata string, so that we generate
1280 // different values for `-Cmetadata=ab -Cmetadata=c` and
1281 // `-Cmetadata=a -Cmetadata=bc`
1282 hasher.write_usize(s.len());
1283 hasher.write(s.as_bytes());
1286 // If this is an executable, add a special suffix, so that we don't get
1287 // symbol conflicts when linking against a library of the same name.
1288 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1290 format!("{}{}", hasher.finish().to_hex(), if is_exe { "-exe" } else {""})
1293 pub fn build_output_filenames(input: &Input,
1294 odir: &Option<PathBuf>,
1295 ofile: &Option<PathBuf>,
1296 attrs: &[ast::Attribute],
1298 -> OutputFilenames {
1301 // "-" as input file will cause the parser to read from stdin so we
1302 // have to make up a name
1303 // We want to toss everything after the final '.'
1304 let dirpath = match *odir {
1305 Some(ref d) => d.clone(),
1306 None => PathBuf::new(),
1309 // If a crate name is present, we use it as the link name
1310 let stem = sess.opts
1313 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1314 .unwrap_or(input.filestem());
1317 out_directory: dirpath,
1319 single_output_file: None,
1320 extra: sess.opts.cg.extra_filename.clone(),
1321 outputs: sess.opts.output_types.clone(),
1325 Some(ref out_file) => {
1326 let unnamed_output_types = sess.opts
1329 .filter(|a| a.is_none())
1331 let ofile = if unnamed_output_types > 1 {
1332 sess.warn("ignoring specified output filename because multiple outputs were \
1336 Some(out_file.clone())
1339 sess.warn("ignoring --out-dir flag due to -o flag.");
1342 let cur_dir = Path::new("");
1345 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1346 out_filestem: out_file.file_stem()
1347 .unwrap_or(OsStr::new(""))
1351 single_output_file: ofile,
1352 extra: sess.opts.cg.extra_filename.clone(),
1353 outputs: sess.opts.output_types.clone(),