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;
15 use rustc_data_structures::blake2b::Blake2bHasher;
16 use rustc_data_structures::fmt_wrap::FmtWrap;
17 use rustc::ty::util::ArchIndependentHasher;
19 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
20 use rustc::session::config::{self, Input, OutputFilenames, OutputType,
22 use rustc::session::search_paths::PathKind;
24 use rustc::middle::{self, dependency_format, stability, reachable};
25 use rustc::middle::privacy::AccessLevels;
26 use rustc::ty::{self, TyCtxt};
27 use rustc::util::common::time;
28 use rustc::util::nodemap::NodeSet;
29 use rustc_borrowck as borrowck;
30 use rustc_incremental::{self, IncrementalHashesMap};
31 use rustc_resolve::{MakeGlobMap, Resolver};
32 use rustc_metadata::creader::CrateLoader;
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,
41 static_recursion, hir_stats};
42 use rustc_const_eval::check_match;
43 use super::Compilation;
49 use std::ffi::{OsString, OsStr};
51 use std::io::{self, Write};
52 use std::path::{Path, PathBuf};
53 use syntax::{ast, diagnostics, visit};
55 use syntax::ext::base::ExtCtxt;
56 use syntax::parse::{self, PResult, token};
57 use syntax::util::node_count::NodeCounter;
64 pub struct Resolutions {
66 pub freevars: FreevarMap,
67 pub trait_map: TraitMap,
68 pub maybe_unused_trait_imports: NodeSet,
71 pub fn compile_input(sess: &Session,
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, input) {
98 Err(mut parse_error) => {
104 let (krate, registry) = {
105 let mut compile_state = CompileState::state_after_parse(input,
111 controller_entry_point!(after_parse,
116 (compile_state.krate.unwrap(), compile_state.registry)
119 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
120 let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
121 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
122 phase_2_configure_and_expand(
123 sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
125 let mut state = CompileState::state_after_expand(
126 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
128 controller_entry_point!(after_expand, sess, state, Ok(()));
134 write_out_deps(sess, &outputs, &crate_name);
136 let arenas = ty::CtxtArenas::new();
138 // Construct the HIR map
139 let hir_map = time(sess.time_passes(),
141 || hir_map::map_crate(&mut hir_forest, defs));
144 let _ignore = hir_map.dep_graph.in_ignore();
145 controller_entry_point!(after_hir_lowering,
147 CompileState::state_after_hir_lowering(input,
162 time(sess.time_passes(), "attribute checking", || {
163 hir::check_attr::check_crate(sess, &expanded_crate);
166 let opt_crate = if keep_ast(sess) {
167 Some(&expanded_crate)
169 drop(expanded_crate);
173 phase_3_run_analysis_passes(sess,
179 |tcx, analysis, incremental_hashes_map, result| {
181 // Eventually, we will want to track plugins.
182 let _ignore = tcx.dep_graph.in_ignore();
184 let mut state = CompileState::state_after_analysis(input,
193 (control.after_analysis.callback)(&mut state);
195 if control.after_analysis.stop == Compilation::Stop {
196 return result.and_then(|_| Err(0usize));
202 if log_enabled!(::log::INFO) {
203 println!("Pre-trans");
204 tcx.print_debug_stats();
206 let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map);
208 if log_enabled!(::log::INFO) {
209 println!("Post-trans");
210 tcx.print_debug_stats();
213 // Discard interned strings as they are no longer required.
214 token::clear_ident_interner();
220 let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
222 controller_entry_point!(after_llvm,
224 CompileState::state_after_llvm(input, sess, outdir, output, &trans),
228 write::cleanup_llvm(&trans);
230 phase_6_link_output(sess, &trans, &outputs);
232 // Now that we won't touch anything in the incremental compilation directory
233 // any more, we can finalize it (which involves renaming it)
234 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
236 if sess.opts.debugging_opts.perf_stats {
237 sess.print_perf_stats();
240 controller_entry_point!(compilation_done,
242 CompileState::state_when_compilation_done(input, sess, outdir, output),
248 fn keep_hygiene_data(sess: &Session) -> bool {
249 sess.opts.debugging_opts.keep_hygiene_data
252 fn keep_ast(sess: &Session) -> bool {
253 sess.opts.debugging_opts.keep_ast ||
254 sess.opts.debugging_opts.save_analysis ||
255 sess.opts.debugging_opts.save_analysis_csv ||
256 sess.opts.debugging_opts.save_analysis_api
259 /// The name used for source code that doesn't originate in a file
260 /// (e.g. source from stdin or a string)
261 pub fn anon_src() -> String {
265 pub fn source_name(input: &Input) -> String {
267 // FIXME (#9639): This needs to handle non-utf8 paths
268 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
269 Input::Str { ref name, .. } => name.clone(),
273 /// CompileController is used to customise compilation, it allows compilation to
274 /// be stopped and/or to call arbitrary code at various points in compilation.
275 /// It also allows for various flags to be set to influence what information gets
276 /// collected during compilation.
278 /// This is a somewhat higher level controller than a Session - the Session
279 /// controls what happens in each phase, whereas the CompileController controls
280 /// whether a phase is run at all and whether other code (from outside the
281 /// the compiler) is run between phases.
283 /// Note that if compilation is set to stop and a callback is provided for a
284 /// given entry point, the callback is called before compilation is stopped.
286 /// Expect more entry points to be added in the future.
287 pub struct CompileController<'a> {
288 pub after_parse: PhaseController<'a>,
289 pub after_expand: PhaseController<'a>,
290 pub after_hir_lowering: PhaseController<'a>,
291 pub after_analysis: PhaseController<'a>,
292 pub after_llvm: PhaseController<'a>,
293 pub compilation_done: PhaseController<'a>,
295 pub make_glob_map: MakeGlobMap,
298 impl<'a> CompileController<'a> {
299 pub fn basic() -> CompileController<'a> {
301 after_parse: PhaseController::basic(),
302 after_expand: PhaseController::basic(),
303 after_hir_lowering: PhaseController::basic(),
304 after_analysis: PhaseController::basic(),
305 after_llvm: PhaseController::basic(),
306 compilation_done: PhaseController::basic(),
307 make_glob_map: MakeGlobMap::No,
312 pub struct PhaseController<'a> {
313 pub stop: Compilation,
314 // If true then the compiler will try to run the callback even if the phase
315 // ends with an error. Note that this is not always possible.
316 pub run_callback_on_error: bool,
317 pub callback: Box<Fn(&mut CompileState) + 'a>,
320 impl<'a> PhaseController<'a> {
321 pub fn basic() -> PhaseController<'a> {
323 stop: Compilation::Continue,
324 run_callback_on_error: false,
325 callback: box |_| {},
330 /// State that is passed to a callback. What state is available depends on when
331 /// during compilation the callback is made. See the various constructor methods
332 /// (`state_*`) in the impl to see which data is provided for any given entry point.
333 pub struct CompileState<'a, 'b, 'ast: 'a, 'tcx: 'b> where 'ast: 'tcx {
334 pub input: &'a Input,
335 pub session: &'ast Session,
336 pub krate: Option<ast::Crate>,
337 pub registry: Option<Registry<'a>>,
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 analysis: Option<&'a ty::CrateAnalysis<'a>>,
349 pub tcx: Option<TyCtxt<'b, 'tcx, 'tcx>>,
350 pub trans: Option<&'a trans::CrateTranslation>,
353 impl<'a, 'b, 'ast, 'tcx> CompileState<'a, 'b, 'ast, 'tcx> {
354 fn empty(input: &'a Input,
355 session: &'ast Session,
356 out_dir: &'a Option<PathBuf>)
357 -> CompileState<'a, 'b, 'ast, 'tcx> {
361 out_dir: out_dir.as_ref().map(|s| &**s),
368 output_filenames: None,
369 expanded_crate: None,
379 fn state_after_parse(input: &'a Input,
380 session: &'ast Session,
381 out_dir: &'a Option<PathBuf>,
382 out_file: &'a Option<PathBuf>,
385 -> CompileState<'a, 'b, 'ast, 'tcx> {
387 // Initialize the registry before moving `krate`
388 registry: Some(Registry::new(&session, krate.span)),
390 cstore: Some(cstore),
391 out_file: out_file.as_ref().map(|s| &**s),
392 ..CompileState::empty(input, session, out_dir)
396 fn state_after_expand(input: &'a Input,
397 session: &'ast Session,
398 out_dir: &'a Option<PathBuf>,
399 out_file: &'a Option<PathBuf>,
401 expanded_crate: &'a ast::Crate,
403 -> CompileState<'a, 'b, 'ast, 'tcx> {
405 crate_name: Some(crate_name),
406 cstore: Some(cstore),
407 expanded_crate: Some(expanded_crate),
408 out_file: out_file.as_ref().map(|s| &**s),
409 ..CompileState::empty(input, session, out_dir)
413 fn state_after_hir_lowering(input: &'a Input,
414 session: &'ast Session,
415 out_dir: &'a Option<PathBuf>,
416 out_file: &'a Option<PathBuf>,
417 arenas: &'ast ty::CtxtArenas<'ast>,
419 hir_map: &'a hir_map::Map<'ast>,
420 analysis: &'a ty::CrateAnalysis,
421 resolutions: &'a Resolutions,
422 krate: &'a ast::Crate,
423 hir_crate: &'a hir::Crate,
425 -> CompileState<'a, 'b, 'ast, 'tcx> {
427 crate_name: Some(crate_name),
428 arenas: Some(arenas),
429 cstore: Some(cstore),
430 ast_map: Some(hir_map),
431 analysis: Some(analysis),
432 resolutions: Some(resolutions),
433 expanded_crate: Some(krate),
434 hir_crate: Some(hir_crate),
435 out_file: out_file.as_ref().map(|s| &**s),
436 ..CompileState::empty(input, session, out_dir)
440 fn state_after_analysis(input: &'a Input,
441 session: &'ast Session,
442 out_dir: &'a Option<PathBuf>,
443 out_file: &'a Option<PathBuf>,
444 krate: Option<&'a ast::Crate>,
445 hir_crate: &'a hir::Crate,
446 analysis: &'a ty::CrateAnalysis<'a>,
447 tcx: TyCtxt<'b, 'tcx, 'tcx>,
449 -> CompileState<'a, 'b, 'ast, 'tcx> {
451 analysis: Some(analysis),
453 expanded_crate: krate,
454 hir_crate: Some(hir_crate),
455 crate_name: Some(crate_name),
456 out_file: out_file.as_ref().map(|s| &**s),
457 ..CompileState::empty(input, session, out_dir)
462 fn state_after_llvm(input: &'a Input,
463 session: &'ast Session,
464 out_dir: &'a Option<PathBuf>,
465 out_file: &'a Option<PathBuf>,
466 trans: &'a trans::CrateTranslation)
467 -> CompileState<'a, 'b, 'ast, 'tcx> {
470 out_file: out_file.as_ref().map(|s| &**s),
471 ..CompileState::empty(input, session, out_dir)
475 fn state_when_compilation_done(input: &'a Input,
476 session: &'ast Session,
477 out_dir: &'a Option<PathBuf>,
478 out_file: &'a Option<PathBuf>)
479 -> CompileState<'a, 'b, 'ast, 'tcx> {
481 out_file: out_file.as_ref().map(|s| &**s),
482 ..CompileState::empty(input, session, out_dir)
487 pub fn phase_1_parse_input<'a>(sess: &'a Session, input: &Input) -> PResult<'a, ast::Crate> {
488 let continue_after_error = sess.opts.debugging_opts.continue_parse_after_error;
489 sess.diagnostic().set_continue_after_error(continue_after_error);
491 let krate = time(sess.time_passes(), "parsing", || {
493 Input::File(ref file) => {
494 parse::parse_crate_from_file(file, &sess.parse_sess)
496 Input::Str { ref input, ref name } => {
497 parse::parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
502 sess.diagnostic().set_continue_after_error(true);
504 if sess.opts.debugging_opts.ast_json_noexpand {
505 println!("{}", json::as_json(&krate));
508 if sess.opts.debugging_opts.input_stats {
509 println!("Lines of code: {}", sess.codemap().count_lines());
510 println!("Pre-expansion node count: {}", count_nodes(&krate));
513 if let Some(ref s) = sess.opts.debugging_opts.show_span {
514 syntax::show_span::run(sess.diagnostic(), s, &krate);
517 if sess.opts.debugging_opts.hir_stats {
518 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
524 fn count_nodes(krate: &ast::Crate) -> usize {
525 let mut counter = NodeCounter::new();
526 visit::walk_crate(&mut counter, krate);
530 // For continuing compilation after a parsed crate has been
533 pub struct ExpansionResult<'a> {
534 pub expanded_crate: ast::Crate,
535 pub defs: hir_map::Definitions,
536 pub analysis: ty::CrateAnalysis<'a>,
537 pub resolutions: Resolutions,
538 pub hir_forest: hir_map::Forest,
541 /// Run the "early phases" of the compiler: initial `cfg` processing,
542 /// loading compiler plugins (including those from `addl_plugins`),
543 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
544 /// harness if one is to be provided, injection of a dependency on the
545 /// standard library and prelude, and name resolution.
547 /// Returns `None` if we're aborting after handling -W help.
548 pub fn phase_2_configure_and_expand<'a, F>(sess: &Session,
551 registry: Option<Registry>,
553 addl_plugins: Option<Vec<String>>,
554 make_glob_map: MakeGlobMap,
556 -> Result<ExpansionResult<'a>, usize>
557 where F: FnOnce(&ast::Crate) -> CompileResult,
559 let time_passes = sess.time_passes();
561 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
562 // these need to be set "early" so that expansion sees `quote` if enabled.
563 *sess.features.borrow_mut() = features;
565 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
566 *sess.crate_disambiguator.borrow_mut() =
567 token::intern(&compute_crate_disambiguator(sess)).as_str();
569 time(time_passes, "recursion limit", || {
570 middle::recursion_limit::update_recursion_limit(sess, &krate);
573 krate = time(time_passes, "crate injection", || {
574 let alt_std_name = sess.opts.alt_std_name.clone();
575 syntax::std_inject::maybe_inject_crates_ref(&sess.parse_sess, krate, alt_std_name)
578 let mut addl_plugins = Some(addl_plugins);
579 let registrars = time(time_passes, "plugin loading", || {
580 plugin::load::load_plugins(sess,
584 addl_plugins.take().unwrap())
587 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
589 time(time_passes, "plugin registration", || {
590 if sess.features.borrow().rustc_diagnostic_macros {
591 registry.register_macro("__diagnostic_used",
592 diagnostics::plugin::expand_diagnostic_used);
593 registry.register_macro("__register_diagnostic",
594 diagnostics::plugin::expand_register_diagnostic);
595 registry.register_macro("__build_diagnostic_array",
596 diagnostics::plugin::expand_build_diagnostic_array);
599 for registrar in registrars {
600 registry.args_hidden = Some(registrar.args);
601 (registrar.fun)(&mut registry);
605 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
606 llvm_passes, attributes, mir_passes, .. } = registry;
608 sess.track_errors(|| {
609 let mut ls = sess.lint_store.borrow_mut();
610 for pass in early_lint_passes {
611 ls.register_early_pass(Some(sess), true, pass);
613 for pass in late_lint_passes {
614 ls.register_late_pass(Some(sess), true, pass);
617 for (name, to) in lint_groups {
618 ls.register_group(Some(sess), true, name, to);
621 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
622 sess.mir_passes.borrow_mut().extend(mir_passes);
623 *sess.plugin_attributes.borrow_mut() = attributes.clone();
626 // Lint plugins are registered; now we can process command line flags.
627 if sess.opts.describe_lints {
628 super::describe_lints(&sess.lint_store.borrow(), true);
631 sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
633 // Currently, we ignore the name resolution data structures for the purposes of dependency
634 // tracking. Instead we will run name resolution and include its output in the hash of each
635 // item, much like we do for macro expansion. In other words, the hash reflects not just
636 // its contents but the results of name resolution on those contents. Hopefully we'll push
637 // this back at some point.
638 let _ignore = sess.dep_graph.in_ignore();
639 let mut crate_loader = CrateLoader::new(sess, &cstore, crate_name);
640 crate_loader.preprocess(&krate);
641 let resolver_arenas = Resolver::arenas();
643 Resolver::new(sess, &krate, make_glob_map, &mut crate_loader, &resolver_arenas);
644 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
646 krate = time(time_passes, "expansion", || {
647 // Windows dlls do not have rpaths, so they don't know how to find their
648 // dependencies. It's up to us to tell the system where to find all the
649 // dependent dlls. Note that this uses cfg!(windows) as opposed to
650 // targ_cfg because syntax extensions are always loaded for the host
651 // compiler, not for the target.
653 // This is somewhat of an inherently racy operation, however, as
654 // multiple threads calling this function could possibly continue
655 // extending PATH far beyond what it should. To solve this for now we
656 // just don't add any new elements to PATH which are already there
657 // within PATH. This is basically a targeted fix at #17360 for rustdoc
658 // which runs rustc in parallel but has been seen (#33844) to cause
659 // problems with PATH becoming too long.
660 let mut old_path = OsString::new();
662 old_path = env::var_os("PATH").unwrap_or(old_path);
663 let mut new_path = sess.host_filesearch(PathKind::All)
664 .get_dylib_search_paths();
665 for path in env::split_paths(&old_path) {
666 if !new_path.contains(&path) {
670 env::set_var("PATH", &env::join_paths(new_path).unwrap());
672 let features = sess.features.borrow();
673 let cfg = syntax::ext::expand::ExpansionConfig {
674 features: Some(&features),
675 recursion_limit: sess.recursion_limit.get(),
676 trace_mac: sess.opts.debugging_opts.trace_macros,
677 should_test: sess.opts.test,
678 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
680 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
681 let err_count = ecx.parse_sess.span_diagnostic.err_count();
683 let krate = ecx.monotonic_expander().expand_crate(krate);
685 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
686 ecx.parse_sess.span_diagnostic.abort_if_errors();
689 env::set_var("PATH", &old_path);
694 krate.exported_macros = mem::replace(&mut resolver.exported_macros, Vec::new());
696 krate = time(time_passes, "maybe building test harness", || {
697 syntax::test::modify_for_testing(&sess.parse_sess,
704 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
705 // bunch of checks in the `modify` function below. For now just skip this
706 // step entirely if we're rustdoc as it's not too useful anyway.
707 if !sess.opts.actually_rustdoc {
708 krate = time(time_passes, "maybe creating a macro crate", || {
709 let crate_types = sess.crate_types.borrow();
710 let num_crate_types = crate_types.len();
711 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
712 let is_test_crate = sess.opts.test;
713 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
720 &sess.features.borrow())
724 if sess.opts.debugging_opts.input_stats {
725 println!("Post-expansion node count: {}", count_nodes(&krate));
728 if sess.opts.debugging_opts.hir_stats {
729 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
732 if sess.opts.debugging_opts.ast_json {
733 println!("{}", json::as_json(&krate));
737 "checking for inline asm in case the target doesn't support it",
738 || no_asm::check_crate(sess, &krate));
740 // Needs to go *after* expansion to be able to check the results of macro expansion.
741 time(time_passes, "complete gated feature checking", || {
742 sess.track_errors(|| {
743 syntax::feature_gate::check_crate(&krate,
745 &sess.features.borrow(),
747 sess.opts.unstable_features);
751 time(sess.time_passes(),
753 || lint::check_ast_crate(sess, &krate));
755 time(sess.time_passes(),
757 || ast_validation::check_crate(sess, &krate));
759 time(sess.time_passes(), "name resolution", || -> CompileResult {
760 // Since import resolution will eventually happen in expansion,
761 // don't perform `after_expand` until after import resolution.
762 after_expand(&krate)?;
764 resolver.resolve_crate(&krate);
769 let hir_forest = time(sess.time_passes(), "lowering ast -> hir", || {
770 let hir_crate = lower_crate(sess, &krate, &mut resolver);
772 if sess.opts.debugging_opts.hir_stats {
773 hir_stats::print_hir_stats(&hir_crate);
776 hir_map::Forest::new(hir_crate, &sess.dep_graph)
779 // Discard hygiene data, which isn't required past lowering to HIR.
780 if !keep_hygiene_data(sess) {
781 syntax::ext::hygiene::reset_hygiene_data();
785 expanded_crate: krate,
786 defs: resolver.definitions,
787 analysis: ty::CrateAnalysis {
788 export_map: resolver.export_map,
789 access_levels: AccessLevels::default(),
790 reachable: NodeSet(),
792 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
794 resolutions: Resolutions {
795 def_map: resolver.def_map,
796 freevars: resolver.freevars,
797 trait_map: resolver.trait_map,
798 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
800 hir_forest: hir_forest
804 /// Run the resolution, typechecking, region checking and other
805 /// miscellaneous analysis passes on the crate. Return various
806 /// structures carrying the results of the analysis.
807 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
808 hir_map: hir_map::Map<'tcx>,
809 mut analysis: ty::CrateAnalysis,
810 resolutions: Resolutions,
811 arenas: &'tcx ty::CtxtArenas<'tcx>,
815 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
817 IncrementalHashesMap,
820 macro_rules! try_with_f {
821 ($e: expr, ($t: expr, $a: expr, $h: expr)) => {
825 f($t, $a, $h, Err(x));
832 let time_passes = sess.time_passes();
834 let lang_items = time(time_passes, "language item collection", || {
835 sess.track_errors(|| {
836 middle::lang_items::collect_language_items(&sess, &hir_map)
840 let named_region_map = time(time_passes,
841 "lifetime resolution",
842 || middle::resolve_lifetime::krate(sess,
844 &resolutions.def_map))?;
847 "looking for entry point",
848 || middle::entry::find_entry_point(sess, &hir_map));
850 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
851 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
853 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
855 let region_map = time(time_passes,
857 || middle::region::resolve_crate(sess, &hir_map));
861 || loops::check_crate(sess, &hir_map));
864 "static item recursion checking",
865 || static_recursion::check_crate(sess, &resolutions.def_map, &hir_map))?;
867 let index = stability::Index::new(&hir_map);
869 TyCtxt::create_and_enter(sess,
872 resolutions.trait_map,
875 resolutions.freevars,
876 resolutions.maybe_unused_trait_imports,
882 let incremental_hashes_map =
884 "compute_incremental_hashes_map",
885 || rustc_incremental::compute_incremental_hashes_map(tcx));
888 || rustc_incremental::load_dep_graph(tcx, &incremental_hashes_map));
890 // passes are timed inside typeck
891 try_with_f!(typeck::check_crate(tcx), (tcx, analysis, incremental_hashes_map));
895 || consts::check_crate(tcx));
897 analysis.access_levels =
898 time(time_passes, "privacy checking", || {
899 rustc_privacy::check_crate(tcx, &analysis.export_map)
902 // Do not move this check past lint
903 time(time_passes, "stability index", || {
904 tcx.stability.borrow_mut().build(tcx, &analysis.access_levels)
908 "intrinsic checking",
909 || middle::intrinsicck::check_crate(tcx));
913 || middle::effect::check_crate(tcx));
917 || check_match::check_crate(tcx));
919 // this must run before MIR dump, because
920 // "not all control paths return a value" is reported here.
922 // maybe move the check to a MIR pass?
925 || middle::liveness::check_crate(tcx));
929 || rvalues::check_crate(tcx));
933 || mir::mir_map::build_mir_for_crate(tcx));
935 time(time_passes, "MIR cleanup and validation", || {
936 let mut passes = sess.mir_passes.borrow_mut();
937 // Push all the built-in validation passes.
938 // NB: if you’re adding an *optimisation* it ought to go to another set of passes
940 passes.push_hook(box mir::transform::dump_mir::DumpMir);
941 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("initial"));
943 box mir::transform::qualify_consts::QualifyAndPromoteConstants::default());
944 passes.push_pass(box mir::transform::type_check::TypeckMir);
946 box mir::transform::simplify_branches::SimplifyBranches::new("initial"));
947 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("qualify-consts"));
948 // And run everything.
949 passes.run_passes(tcx);
954 || borrowck::check_crate(tcx));
956 // Avoid overwhelming user with errors if type checking failed.
957 // I'm not sure how helpful this is, to be honest, but it avoids
959 // lot of annoying errors in the compile-fail tests (basically,
960 // lint warnings and so on -- kindck used to do this abort, but
961 // kindck is gone now). -nmatsakis
962 if sess.err_count() > 0 {
963 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
968 "reachability checking",
969 || reachable::find_reachable(tcx, &analysis.access_levels));
971 time(time_passes, "death checking", || {
972 middle::dead::check_crate(tcx, &analysis.access_levels);
975 let ref lib_features_used =
977 "stability checking",
978 || stability::check_unstable_api_usage(tcx));
980 time(time_passes, "unused lib feature checking", || {
981 stability::check_unused_or_stable_features(&tcx.sess,
987 || lint::check_crate(tcx, &analysis.access_levels));
989 // The above three passes generate errors w/o aborting
990 if sess.err_count() > 0 {
991 return Ok(f(tcx, analysis, incremental_hashes_map, Err(sess.err_count())));
994 Ok(f(tcx, analysis, incremental_hashes_map, Ok(())))
998 /// Run the translation phase to LLVM, after which the AST and analysis can
999 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1000 analysis: ty::CrateAnalysis,
1001 incremental_hashes_map: &IncrementalHashesMap)
1002 -> trans::CrateTranslation {
1003 let time_passes = tcx.sess.time_passes();
1006 "resolving dependency formats",
1007 || dependency_format::calculate(&tcx.sess));
1009 // Run the passes that transform the MIR into a more suitable form for translation to LLVM
1011 time(time_passes, "MIR optimisations", || {
1012 let mut passes = ::rustc::mir::transform::Passes::new();
1013 passes.push_hook(box mir::transform::dump_mir::DumpMir);
1014 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1015 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("no-landing-pads"));
1017 // From here on out, regions are gone.
1018 passes.push_pass(box mir::transform::erase_regions::EraseRegions);
1020 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1021 passes.push_pass(box borrowck::ElaborateDrops);
1022 passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1023 passes.push_pass(box mir::transform::simplify::SimplifyCfg::new("elaborate-drops"));
1025 // No lifetime analysis based on borrowing can be done from here on out.
1026 passes.push_pass(box mir::transform::instcombine::InstCombine::new());
1027 passes.push_pass(box mir::transform::deaggregator::Deaggregator);
1028 passes.push_pass(box mir::transform::copy_prop::CopyPropagation);
1030 passes.push_pass(box mir::transform::simplify::SimplifyLocals);
1031 passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1032 passes.push_pass(box mir::transform::dump_mir::Marker("PreTrans"));
1034 passes.run_passes(tcx);
1040 move || trans::trans_crate(tcx, analysis, &incremental_hashes_map));
1044 || rustc_incremental::assert_dep_graph(tcx));
1047 "serialize dep graph",
1048 || rustc_incremental::save_dep_graph(tcx,
1049 &incremental_hashes_map,
1050 translation.link.crate_hash));
1054 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1055 /// as a side effect.
1056 pub fn phase_5_run_llvm_passes(sess: &Session,
1057 trans: &trans::CrateTranslation,
1058 outputs: &OutputFilenames) -> CompileResult {
1059 if sess.opts.cg.no_integrated_as ||
1060 (sess.target.target.options.no_integrated_as &&
1061 (outputs.outputs.contains_key(&OutputType::Object) ||
1062 outputs.outputs.contains_key(&OutputType::Exe)))
1064 let output_types = OutputTypes::new(&[(OutputType::Assembly, None)]);
1065 time(sess.time_passes(),
1067 || write::run_passes(sess, trans, &output_types, outputs));
1069 write::run_assembler(sess, outputs);
1071 // HACK the linker expects the object file to be named foo.0.o but
1072 // `run_assembler` produces an object named just foo.o. Rename it if we
1073 // are going to build an executable
1074 if sess.opts.output_types.contains_key(&OutputType::Exe) {
1075 let f = outputs.path(OutputType::Object);
1077 f.with_file_name(format!("{}.0.o",
1078 f.file_stem().unwrap().to_string_lossy()))).unwrap();
1079 fs::remove_file(f).unwrap();
1082 // Remove assembly source, unless --save-temps was specified
1083 if !sess.opts.cg.save_temps {
1084 fs::remove_file(&outputs.temp_path(OutputType::Assembly, None)).unwrap();
1087 time(sess.time_passes(),
1089 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1092 time(sess.time_passes(),
1093 "serialize work products",
1094 move || rustc_incremental::save_work_products(sess));
1096 if sess.err_count() > 0 {
1097 Err(sess.err_count())
1103 /// Run the linker on any artifacts that resulted from the LLVM run.
1104 /// This should produce either a finished executable or library.
1105 pub fn phase_6_link_output(sess: &Session,
1106 trans: &trans::CrateTranslation,
1107 outputs: &OutputFilenames) {
1108 time(sess.time_passes(),
1110 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
1113 fn escape_dep_filename(filename: &str) -> String {
1114 // Apparently clang and gcc *only* escape spaces:
1115 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1116 filename.replace(" ", "\\ ")
1119 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, crate_name: &str) {
1120 let mut out_filenames = Vec::new();
1121 for output_type in sess.opts.output_types.keys() {
1122 let file = outputs.path(*output_type);
1123 match *output_type {
1124 OutputType::Exe => {
1125 for output in sess.crate_types.borrow().iter() {
1126 let p = link::filename_for_input(sess, *output, crate_name, outputs);
1127 out_filenames.push(p);
1131 out_filenames.push(file);
1136 // Write out dependency rules to the dep-info file if requested
1137 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1140 let deps_filename = outputs.path(OutputType::DepInfo);
1143 (|| -> io::Result<()> {
1144 // Build a list of files used to compile the output and
1145 // write Makefile-compatible dependency rules
1146 let files: Vec<String> = sess.codemap()
1150 .filter(|fmap| fmap.is_real_file())
1151 .filter(|fmap| !fmap.is_imported())
1152 .map(|fmap| escape_dep_filename(&fmap.name))
1154 let mut file = fs::File::create(&deps_filename)?;
1155 for path in &out_filenames {
1156 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1159 // Emit a fake target for each input file to the compilation. This
1160 // prevents `make` from spitting out an error if a file is later
1161 // deleted. For more info see #28735
1163 writeln!(file, "{}:", path)?;
1171 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1172 deps_filename.display(),
1178 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1179 // Unconditionally collect crate types from attributes to make them used
1180 let attr_types: Vec<config::CrateType> =
1183 if a.check_name("crate_type") {
1184 match a.value_str() {
1185 Some(ref n) if *n == "rlib" => {
1186 Some(config::CrateTypeRlib)
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 = ArchIndependentHasher::new(Blake2bHasher::new(128 / 8, &[]));
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 let mut hash_state = hasher.into_inner();
1287 let hash_bytes = hash_state.finalize();
1289 // If this is an executable, add a special suffix, so that we don't get
1290 // symbol conflicts when linking against a library of the same name.
1291 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1293 format!("{:x}{}", FmtWrap(hash_bytes), if is_exe { "-exe" } else {""})
1296 pub fn build_output_filenames(input: &Input,
1297 odir: &Option<PathBuf>,
1298 ofile: &Option<PathBuf>,
1299 attrs: &[ast::Attribute],
1301 -> OutputFilenames {
1304 // "-" as input file will cause the parser to read from stdin so we
1305 // have to make up a name
1306 // We want to toss everything after the final '.'
1307 let dirpath = match *odir {
1308 Some(ref d) => d.clone(),
1309 None => PathBuf::new(),
1312 // If a crate name is present, we use it as the link name
1313 let stem = sess.opts
1316 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1317 .unwrap_or(input.filestem());
1320 out_directory: dirpath,
1322 single_output_file: None,
1323 extra: sess.opts.cg.extra_filename.clone(),
1324 outputs: sess.opts.output_types.clone(),
1328 Some(ref out_file) => {
1329 let unnamed_output_types = sess.opts
1332 .filter(|a| a.is_none())
1334 let ofile = if unnamed_output_types > 1 {
1335 sess.warn("ignoring specified output filename because multiple outputs were \
1339 Some(out_file.clone())
1342 sess.warn("ignoring --out-dir flag due to -o flag.");
1345 let cur_dir = Path::new("");
1348 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1349 out_filestem: out_file.file_stem()
1350 .unwrap_or(OsStr::new(""))
1354 single_output_file: ofile,
1355 extra: sess.opts.cg.extra_filename.clone(),
1356 outputs: sess.opts.output_types.clone(),
1362 // For use by the `rusti` project (https://github.com/murarth/rusti).
1363 pub fn reset_thread_local_state() {
1364 // These may be left in an incoherent state after a previous compile.
1365 syntax::ext::hygiene::reset_hygiene_data();
1366 // `clear_ident_interner` can be used to free memory, but it does not restore the initial state.
1367 token::reset_ident_interner();