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::front::map as hir_map;
14 use rustc_mir::mir_map::MirMap;
15 use rustc::session::Session;
16 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
17 use rustc::session::search_paths::PathKind;
19 use rustc::middle::{stability, ty, reachable};
20 use rustc::middle::dependency_format;
22 use rustc::util::nodemap::NodeMap;
23 use rustc::util::common::time;
24 use rustc_borrowck as borrowck;
25 use rustc_resolve as resolve;
26 use rustc_metadata::macro_import;
27 use rustc_metadata::creader::LocalCrateReader;
28 use rustc_metadata::cstore::CStore;
29 use rustc_trans::back::link;
30 use rustc_trans::back::write;
31 use rustc_trans::trans;
32 use rustc_typeck as typeck;
34 use rustc_plugin::registry::Registry;
35 use rustc_plugin as plugin;
37 use rustc_front::lowering::{lower_crate, LoweringContext};
38 use super::Compilation;
42 use std::collections::HashMap;
44 use std::ffi::{OsString, OsStr};
46 use std::io::{self, Write};
47 use std::path::{Path, PathBuf};
48 use syntax::ast::{self, NodeIdAssigner};
50 use syntax::attr::AttrMetaMethods;
51 use syntax::diagnostics;
52 use syntax::feature_gate::UnstableFeatures;
53 use syntax::fold::Folder;
55 use syntax::parse::token;
56 use syntax::util::node_count::NodeCounter;
60 pub fn compile_input(sess: Session,
62 cfg: ast::CrateConfig,
64 outdir: &Option<PathBuf>,
65 output: &Option<PathBuf>,
66 addl_plugins: Option<Vec<String>>,
67 control: CompileController) {
68 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
69 let state = $make_state;
70 (control.$point.callback)(state);
72 $tsess.abort_if_errors();
73 if control.$point.stop == Compilation::Stop {
78 // We need nested scopes here, because the intermediate results can keep
79 // large chunks of memory alive and we want to free them as soon as
80 // possible to keep the peak memory usage low
82 let (outputs, expanded_crate, id) = {
83 let krate = phase_1_parse_input(&sess, cfg, input);
85 controller_entry_point!(after_parse,
87 CompileState::state_after_parse(input, &sess, outdir, &krate));
89 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, &sess);
90 let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
91 let expanded_crate = match phase_2_configure_and_expand(&sess,
100 (outputs, expanded_crate, id)
103 controller_entry_point!(after_expand,
105 CompileState::state_after_expand(input,
111 let expanded_crate = assign_node_ids(&sess, expanded_crate);
113 let lcx = LoweringContext::new(&sess, Some(&expanded_crate));
114 let mut hir_forest = time(sess.time_passes(),
115 "lowering ast -> hir",
116 || hir_map::Forest::new(lower_crate(&lcx, &expanded_crate)));
117 let arenas = ty::CtxtArenas::new();
118 let ast_map = make_map(&sess, &mut hir_forest);
120 write_out_deps(&sess, &outputs, &id);
122 controller_entry_point!(after_write_deps,
124 CompileState::state_after_write_deps(input,
133 time(sess.time_passes(), "attribute checking", || {
134 front::check_attr::check_crate(&sess, &expanded_crate);
137 time(sess.time_passes(),
139 || lint::check_ast_crate(&sess, &expanded_crate));
141 phase_3_run_analysis_passes(&sess,
146 control.make_glob_map,
147 |tcx, mir_map, analysis| {
151 CompileState::state_after_analysis(input,
161 (control.after_analysis.callback)(state);
163 tcx.sess.abort_if_errors();
164 if control.after_analysis.stop == Compilation::Stop {
169 if log_enabled!(::log::INFO) {
170 println!("Pre-trans");
171 tcx.print_debug_stats();
173 let trans = phase_4_translate_to_llvm(tcx,
177 if log_enabled!(::log::INFO) {
178 println!("Post-trans");
179 tcx.print_debug_stats();
182 // Discard interned strings as they are no longer required.
183 token::get_ident_interner().clear();
189 let (outputs, trans) = if let Ok(out) = result {
195 phase_5_run_llvm_passes(&sess, &trans, &outputs);
197 controller_entry_point!(after_llvm,
199 CompileState::state_after_llvm(input, &sess, outdir, &trans));
201 phase_6_link_output(&sess, &trans, &outputs);
204 /// The name used for source code that doesn't originate in a file
205 /// (e.g. source from stdin or a string)
206 pub fn anon_src() -> String {
210 pub fn source_name(input: &Input) -> String {
212 // FIXME (#9639): This needs to handle non-utf8 paths
213 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
214 Input::Str(_) => anon_src(),
218 /// CompileController is used to customise compilation, it allows compilation to
219 /// be stopped and/or to call arbitrary code at various points in compilation.
220 /// It also allows for various flags to be set to influence what information gets
221 /// collected during compilation.
223 /// This is a somewhat higher level controller than a Session - the Session
224 /// controls what happens in each phase, whereas the CompileController controls
225 /// whether a phase is run at all and whether other code (from outside the
226 /// the compiler) is run between phases.
228 /// Note that if compilation is set to stop and a callback is provided for a
229 /// given entry point, the callback is called before compilation is stopped.
231 /// Expect more entry points to be added in the future.
232 pub struct CompileController<'a> {
233 pub after_parse: PhaseController<'a>,
234 pub after_expand: PhaseController<'a>,
235 pub after_write_deps: PhaseController<'a>,
236 pub after_analysis: PhaseController<'a>,
237 pub after_llvm: PhaseController<'a>,
239 pub make_glob_map: resolve::MakeGlobMap,
242 impl<'a> CompileController<'a> {
243 pub fn basic() -> CompileController<'a> {
245 after_parse: PhaseController::basic(),
246 after_expand: PhaseController::basic(),
247 after_write_deps: PhaseController::basic(),
248 after_analysis: PhaseController::basic(),
249 after_llvm: PhaseController::basic(),
250 make_glob_map: resolve::MakeGlobMap::No,
255 pub struct PhaseController<'a> {
256 pub stop: Compilation,
257 pub callback: Box<Fn(CompileState) -> () + 'a>,
260 impl<'a> PhaseController<'a> {
261 pub fn basic() -> PhaseController<'a> {
263 stop: Compilation::Continue,
264 callback: box |_| {},
269 /// State that is passed to a callback. What state is available depends on when
270 /// during compilation the callback is made. See the various constructor methods
271 /// (`state_*`) in the impl to see which data is provided for any given entry point.
272 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
273 pub input: &'a Input,
274 pub session: &'a Session,
275 pub cfg: Option<&'a ast::CrateConfig>,
276 pub krate: Option<&'a ast::Crate>,
277 pub crate_name: Option<&'a str>,
278 pub output_filenames: Option<&'a OutputFilenames>,
279 pub out_dir: Option<&'a Path>,
280 pub expanded_crate: Option<&'a ast::Crate>,
281 pub hir_crate: Option<&'a hir::Crate>,
282 pub ast_map: Option<&'a hir_map::Map<'ast>>,
283 pub mir_map: Option<&'a MirMap<'tcx>>,
284 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
285 pub tcx: Option<&'a ty::ctxt<'tcx>>,
286 pub lcx: Option<&'a LoweringContext<'a>>,
287 pub trans: Option<&'a trans::CrateTranslation>,
290 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
291 fn empty(input: &'a Input,
292 session: &'a Session,
293 out_dir: &'a Option<PathBuf>)
294 -> CompileState<'a, 'ast, 'tcx> {
298 out_dir: out_dir.as_ref().map(|s| &**s),
302 output_filenames: None,
303 expanded_crate: None,
314 fn state_after_parse(input: &'a Input,
315 session: &'a Session,
316 out_dir: &'a Option<PathBuf>,
317 krate: &'a ast::Crate)
318 -> CompileState<'a, 'ast, 'tcx> {
319 CompileState { krate: Some(krate), ..CompileState::empty(input, session, out_dir) }
322 fn state_after_expand(input: &'a Input,
323 session: &'a Session,
324 out_dir: &'a Option<PathBuf>,
325 expanded_crate: &'a ast::Crate,
327 -> CompileState<'a, 'ast, 'tcx> {
329 crate_name: Some(crate_name),
330 expanded_crate: Some(expanded_crate),
331 ..CompileState::empty(input, session, out_dir)
335 fn state_after_write_deps(input: &'a Input,
336 session: &'a Session,
337 out_dir: &'a Option<PathBuf>,
338 ast_map: &'a hir_map::Map<'ast>,
339 krate: &'a ast::Crate,
340 hir_crate: &'a hir::Crate,
342 lcx: &'a LoweringContext<'a>)
343 -> CompileState<'a, 'ast, 'tcx> {
345 crate_name: Some(crate_name),
346 ast_map: Some(ast_map),
348 hir_crate: Some(hir_crate),
350 ..CompileState::empty(input, session, out_dir)
354 fn state_after_analysis(input: &'a Input,
355 session: &'a Session,
356 out_dir: &'a Option<PathBuf>,
357 krate: &'a ast::Crate,
358 hir_crate: &'a hir::Crate,
359 analysis: &'a ty::CrateAnalysis,
360 mir_map: &'a MirMap<'tcx>,
361 tcx: &'a ty::ctxt<'tcx>,
362 lcx: &'a LoweringContext<'a>,
364 -> CompileState<'a, 'ast, 'tcx> {
366 analysis: Some(analysis),
367 mir_map: Some(mir_map),
370 hir_crate: Some(hir_crate),
372 crate_name: Some(crate_name),
373 ..CompileState::empty(input, session, out_dir)
378 fn state_after_llvm(input: &'a Input,
379 session: &'a Session,
380 out_dir: &'a Option<PathBuf>,
381 trans: &'a trans::CrateTranslation)
382 -> CompileState<'a, 'ast, 'tcx> {
383 CompileState { trans: Some(trans), ..CompileState::empty(input, session, out_dir) }
387 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) -> ast::Crate {
388 // These may be left in an incoherent state after a previous compile.
389 // `clear_tables` and `get_ident_interner().clear()` can be used to free
390 // memory, but they do not restore the initial state.
391 syntax::ext::mtwt::reset_tables();
392 token::reset_ident_interner();
394 let krate = time(sess.time_passes(), "parsing", || {
396 Input::File(ref file) => {
397 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
399 Input::Str(ref src) => {
400 parse::parse_crate_from_source_str(anon_src().to_string(),
408 if sess.opts.debugging_opts.ast_json_noexpand {
409 println!("{}", json::as_json(&krate));
412 if sess.opts.debugging_opts.input_stats {
413 println!("Lines of code: {}", sess.codemap().count_lines());
414 println!("Pre-expansion node count: {}", count_nodes(&krate));
417 if let Some(ref s) = sess.opts.show_span {
418 syntax::show_span::run(sess.diagnostic(), s, &krate);
424 fn count_nodes(krate: &ast::Crate) -> usize {
425 let mut counter = NodeCounter::new();
426 visit::walk_crate(&mut counter, krate);
430 // For continuing compilation after a parsed crate has been
433 /// Run the "early phases" of the compiler: initial `cfg` processing,
434 /// loading compiler plugins (including those from `addl_plugins`),
435 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
436 /// harness if one is to be provided and injection of a dependency on the
437 /// standard library and prelude.
439 /// Returns `None` if we're aborting after handling -W help.
440 pub fn phase_2_configure_and_expand(sess: &Session,
442 mut krate: ast::Crate,
444 addl_plugins: Option<Vec<String>>)
445 -> Option<ast::Crate> {
446 let time_passes = sess.time_passes();
448 // strip before anything else because crate metadata may use #[cfg_attr]
449 // and so macros can depend on configuration variables, such as
451 // #[macro_use] #[cfg(foo)]
452 // mod bar { macro_rules! baz!(() => {{}}) }
454 // baz! should not use this definition unless foo is enabled.
456 let mut feature_gated_cfgs = vec![];
457 krate = time(time_passes, "configuration 1", || {
458 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, &mut feature_gated_cfgs)
461 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
462 *sess.crate_metadata.borrow_mut() = collect_crate_metadata(sess, &krate.attrs);
464 time(time_passes, "recursion limit", || {
465 middle::recursion_limit::update_recursion_limit(sess, &krate);
468 time(time_passes, "gated macro checking", || {
469 let features = syntax::feature_gate::check_crate_macros(sess.codemap(),
470 &sess.parse_sess.span_diagnostic,
473 // these need to be set "early" so that expansion sees `quote` if enabled.
474 *sess.features.borrow_mut() = features;
475 sess.abort_if_errors();
479 krate = time(time_passes, "crate injection", || {
480 syntax::std_inject::maybe_inject_crates_ref(krate, sess.opts.alt_std_name.clone())
483 let macros = time(time_passes,
485 || macro_import::read_macro_defs(sess, &cstore, &krate));
487 let mut addl_plugins = Some(addl_plugins);
488 let registrars = time(time_passes, "plugin loading", || {
489 plugin::load::load_plugins(sess, &cstore, &krate, addl_plugins.take().unwrap())
492 let mut registry = Registry::new(sess, &krate);
494 time(time_passes, "plugin registration", || {
495 if sess.features.borrow().rustc_diagnostic_macros {
496 registry.register_macro("__diagnostic_used",
497 diagnostics::plugin::expand_diagnostic_used);
498 registry.register_macro("__register_diagnostic",
499 diagnostics::plugin::expand_register_diagnostic);
500 registry.register_macro("__build_diagnostic_array",
501 diagnostics::plugin::expand_build_diagnostic_array);
504 for registrar in registrars {
505 registry.args_hidden = Some(registrar.args);
506 (registrar.fun)(&mut registry);
510 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
511 llvm_passes, attributes, .. } = registry;
514 let mut ls = sess.lint_store.borrow_mut();
515 for pass in early_lint_passes {
516 ls.register_early_pass(Some(sess), true, pass);
518 for pass in late_lint_passes {
519 ls.register_late_pass(Some(sess), true, pass);
522 for (name, to) in lint_groups {
523 ls.register_group(Some(sess), true, name, to);
526 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
527 *sess.plugin_attributes.borrow_mut() = attributes.clone();
530 // Lint plugins are registered; now we can process command line flags.
531 if sess.opts.describe_lints {
532 super::describe_lints(&*sess.lint_store.borrow(), true);
535 sess.lint_store.borrow_mut().process_command_line(sess);
537 // Abort if there are errors from lint processing or a plugin registrar.
538 sess.abort_if_errors();
540 krate = time(time_passes, "expansion", || {
541 // Windows dlls do not have rpaths, so they don't know how to find their
542 // dependencies. It's up to us to tell the system where to find all the
543 // dependent dlls. Note that this uses cfg!(windows) as opposed to
544 // targ_cfg because syntax extensions are always loaded for the host
545 // compiler, not for the target.
546 let mut _old_path = OsString::new();
548 _old_path = env::var_os("PATH").unwrap_or(_old_path);
549 let mut new_path = sess.host_filesearch(PathKind::All)
550 .get_dylib_search_paths();
551 new_path.extend(env::split_paths(&_old_path));
552 env::set_var("PATH", &env::join_paths(new_path).unwrap());
554 let features = sess.features.borrow();
555 let cfg = syntax::ext::expand::ExpansionConfig {
556 crate_name: crate_name.to_string(),
557 features: Some(&features),
558 recursion_limit: sess.recursion_limit.get(),
559 trace_mac: sess.opts.debugging_opts.trace_macros,
561 let (ret, macro_names) = syntax::ext::expand::expand_crate(&sess.parse_sess,
565 &mut feature_gated_cfgs,
568 env::set_var("PATH", &_old_path);
570 *sess.available_macros.borrow_mut() = macro_names;
574 // Needs to go *after* expansion to be able to check the results
575 // of macro expansion. This runs before #[cfg] to try to catch as
576 // much as possible (e.g. help the programmer avoid platform
577 // specific differences)
578 time(time_passes, "complete gated feature checking 1", || {
579 let features = syntax::feature_gate::check_crate(sess.codemap(),
580 &sess.parse_sess.span_diagnostic,
583 sess.opts.unstable_features);
584 *sess.features.borrow_mut() = features;
585 sess.abort_if_errors();
588 // JBC: make CFG processing part of expansion to avoid this problem:
590 // strip again, in case expansion added anything with a #[cfg].
591 krate = time(time_passes, "configuration 2", || {
592 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate, &mut feature_gated_cfgs)
595 time(time_passes, "gated configuration checking", || {
596 let features = sess.features.borrow();
597 feature_gated_cfgs.sort();
598 feature_gated_cfgs.dedup();
599 for cfg in &feature_gated_cfgs {
600 cfg.check_and_emit(sess.diagnostic(), &features);
604 krate = time(time_passes, "maybe building test harness", || {
605 syntax::test::modify_for_testing(&sess.parse_sess, &sess.opts.cfg, krate, sess.diagnostic())
608 krate = time(time_passes,
610 || syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
613 "checking that all macro invocations are gone",
614 || syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
617 "checking for inline asm in case the target doesn't support it",
618 || middle::check_no_asm::check_crate(sess, &krate));
620 // One final feature gating of the true AST that gets compiled
621 // later, to make sure we've got everything (e.g. configuration
622 // can insert new attributes via `cfg_attr`)
623 time(time_passes, "complete gated feature checking 2", || {
624 let features = syntax::feature_gate::check_crate(sess.codemap(),
625 &sess.parse_sess.span_diagnostic,
628 sess.opts.unstable_features);
629 *sess.features.borrow_mut() = features;
630 sess.abort_if_errors();
633 if sess.opts.debugging_opts.input_stats {
634 println!("Post-expansion node count: {}", count_nodes(&krate));
640 pub fn assign_node_ids(sess: &Session, krate: ast::Crate) -> ast::Crate {
641 struct NodeIdAssigner<'a> {
645 impl<'a> Folder for NodeIdAssigner<'a> {
646 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
647 assert_eq!(old_id, ast::DUMMY_NODE_ID);
648 self.sess.next_node_id()
652 let krate = time(sess.time_passes(),
653 "assigning node ids",
654 || NodeIdAssigner { sess: sess }.fold_crate(krate));
656 if sess.opts.debugging_opts.ast_json {
657 println!("{}", json::as_json(&krate));
663 pub fn make_map<'ast>(sess: &Session,
664 forest: &'ast mut front::map::Forest)
665 -> front::map::Map<'ast> {
666 // Construct the 'ast'-map
667 let map = time(sess.time_passes(),
669 move || front::map::map_crate(forest));
674 /// Run the resolution, typechecking, region checking and other
675 /// miscellaneous analysis passes on the crate. Return various
676 /// structures carrying the results of the analysis.
677 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
679 ast_map: front::map::Map<'tcx>,
680 arenas: &'tcx ty::CtxtArenas<'tcx>,
682 make_glob_map: resolve::MakeGlobMap,
685 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>, MirMap<'tcx>, ty::CrateAnalysis) -> R
687 let time_passes = sess.time_passes();
688 let krate = ast_map.krate();
691 "external crate/lib resolution",
692 || LocalCrateReader::new(sess, cstore, &ast_map).read_crates(krate));
694 let lang_items = time(time_passes,
695 "language item collection",
696 || middle::lang_items::collect_language_items(&sess, &ast_map));
698 let resolve::CrateMap {
705 } = time(time_passes,
707 || resolve::resolve_crate(sess, &ast_map, make_glob_map));
709 // Discard MTWT tables that aren't required past resolution.
710 // FIXME: get rid of uses of MTWT tables in typeck, mir and trans and clear them
711 if !sess.opts.debugging_opts.keep_mtwt_tables {
712 // syntax::ext::mtwt::clear_tables();
715 let named_region_map = time(time_passes,
716 "lifetime resolution",
717 || middle::resolve_lifetime::krate(sess, krate, &def_map.borrow()));
720 "looking for entry point",
721 || middle::entry::find_entry_point(sess, &ast_map));
723 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
724 plugin::build::find_plugin_registrar(sess.diagnostic(), krate)
727 let region_map = time(time_passes,
729 || middle::region::resolve_crate(sess, krate));
733 || middle::check_loop::check_crate(sess, krate));
736 "static item recursion checking",
737 || middle::check_static_recursion::check_crate(sess, krate, &def_map.borrow(), &ast_map));
739 ty::ctxt::create_and_enter(sess,
747 stability::Index::new(krate),
749 // passes are timed inside typeck
750 typeck::check_crate(tcx, trait_map);
754 || middle::check_const::check_crate(tcx));
757 time(time_passes, "privacy checking", || {
758 rustc_privacy::check_crate(tcx,
763 // Do not move this check past lint
764 time(time_passes, "stability index", || {
765 tcx.stability.borrow_mut().build(tcx, krate, &access_levels)
769 "intrinsic checking",
770 || middle::intrinsicck::check_crate(tcx));
774 || middle::effect::check_crate(tcx));
778 || middle::check_match::check_crate(tcx));
780 let mir_map = match tcx.sess.opts.unstable_features {
781 UnstableFeatures::Disallow => {
782 // use this as a shorthand for beta/stable, and skip
783 // MIR construction there until known regressions are
787 UnstableFeatures::Allow | UnstableFeatures::Cheat => {
790 || mir::mir_map::build_mir_for_crate(tcx))
796 || middle::liveness::check_crate(tcx));
800 || borrowck::check_crate(tcx));
804 || middle::check_rvalues::check_crate(tcx, krate));
806 // Avoid overwhelming user with errors if type checking failed.
807 // I'm not sure how helpful this is, to be honest, but it avoids
809 // lot of annoying errors in the compile-fail tests (basically,
810 // lint warnings and so on -- kindck used to do this abort, but
811 // kindck is gone now). -nmatsakis
812 tcx.sess.abort_if_errors();
816 "reachability checking",
817 || reachable::find_reachable(tcx, &access_levels));
819 time(time_passes, "death checking", || {
820 middle::dead::check_crate(tcx, &access_levels);
823 let ref lib_features_used =
825 "stability checking",
826 || stability::check_unstable_api_usage(tcx));
828 time(time_passes, "unused lib feature checking", || {
829 stability::check_unused_or_stable_features(&tcx.sess,
835 || lint::check_crate(tcx, &access_levels));
837 // The above three passes generate errors w/o aborting
838 tcx.sess.abort_if_errors();
843 export_map: export_map,
844 access_levels: access_levels,
845 reachable: reachable_map,
852 /// Run the translation phase to LLVM, after which the AST and analysis can
854 pub fn phase_4_translate_to_llvm<'tcx>(tcx: &ty::ctxt<'tcx>,
855 mut mir_map: MirMap<'tcx>,
856 analysis: ty::CrateAnalysis)
857 -> trans::CrateTranslation {
858 let time_passes = tcx.sess.time_passes();
861 "resolving dependency formats",
862 || dependency_format::calculate(&tcx.sess));
865 "erasing regions from MIR",
866 || mir::transform::erase_regions::erase_regions(tcx, &mut mir_map));
868 // Option dance to work around the lack of stack once closures.
871 move || trans::trans_crate(tcx, &mir_map, analysis))
874 /// Run LLVM itself, producing a bitcode file, assembly file or object file
875 /// as a side effect.
876 pub fn phase_5_run_llvm_passes(sess: &Session,
877 trans: &trans::CrateTranslation,
878 outputs: &OutputFilenames) {
879 if sess.opts.cg.no_integrated_as {
880 let mut map = HashMap::new();
881 map.insert(OutputType::Assembly, None);
882 time(sess.time_passes(),
884 || write::run_passes(sess, trans, &map, outputs));
886 write::run_assembler(sess, outputs);
888 // Remove assembly source, unless --save-temps was specified
889 if !sess.opts.cg.save_temps {
890 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
893 time(sess.time_passes(),
895 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
898 sess.abort_if_errors();
901 /// Run the linker on any artifacts that resulted from the LLVM run.
902 /// This should produce either a finished executable or library.
903 pub fn phase_6_link_output(sess: &Session,
904 trans: &trans::CrateTranslation,
905 outputs: &OutputFilenames) {
906 time(sess.time_passes(),
908 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
911 fn escape_dep_filename(filename: &str) -> String {
912 // Apparently clang and gcc *only* escape spaces:
913 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
914 filename.replace(" ", "\\ ")
917 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
918 let mut out_filenames = Vec::new();
919 for output_type in sess.opts.output_types.keys() {
920 let file = outputs.path(*output_type);
923 for output in sess.crate_types.borrow().iter() {
924 let p = link::filename_for_input(sess, *output, id, outputs);
925 out_filenames.push(p);
929 out_filenames.push(file);
934 // Write out dependency rules to the dep-info file if requested
935 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
938 let deps_filename = outputs.path(OutputType::DepInfo);
941 (|| -> io::Result<()> {
942 // Build a list of files used to compile the output and
943 // write Makefile-compatible dependency rules
944 let files: Vec<String> = sess.codemap()
948 .filter(|fmap| fmap.is_real_file())
949 .filter(|fmap| !fmap.is_imported())
950 .map(|fmap| escape_dep_filename(&fmap.name))
952 let mut file = try!(fs::File::create(&deps_filename));
953 for path in &out_filenames {
954 try!(write!(file, "{}: {}\n\n", path.display(), files.join(" ")));
957 // Emit a fake target for each input file to the compilation. This
958 // prevents `make` from spitting out an error if a file is later
959 // deleted. For more info see #28735
961 try!(writeln!(file, "{}:", path));
969 sess.fatal(&format!("error writing dependencies to `{}`: {}",
970 deps_filename.display(),
976 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
977 // Unconditionally collect crate types from attributes to make them used
978 let attr_types: Vec<config::CrateType> =
981 if a.check_name("crate_type") {
982 match a.value_str() {
983 Some(ref n) if *n == "rlib" => {
984 Some(config::CrateTypeRlib)
986 Some(ref n) if *n == "dylib" => {
987 Some(config::CrateTypeDylib)
989 Some(ref n) if *n == "lib" => {
990 Some(config::default_lib_output())
992 Some(ref n) if *n == "staticlib" => {
993 Some(config::CrateTypeStaticlib)
995 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
997 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1000 "invalid `crate_type` value".to_string());
1004 session.span_err(a.span, "`crate_type` requires a value");
1005 session.note("for example: `#![crate_type=\"lib\"]`");
1015 // If we're generating a test executable, then ignore all other output
1016 // styles at all other locations
1017 if session.opts.test {
1018 return vec![config::CrateTypeExecutable];
1021 // Only check command line flags if present. If no types are specified by
1022 // command line, then reuse the empty `base` Vec to hold the types that
1023 // will be found in crate attributes.
1024 let mut base = session.opts.crate_types.clone();
1025 if base.is_empty() {
1026 base.extend(attr_types);
1027 if base.is_empty() {
1028 base.push(link::default_output_for_target(session));
1035 .filter(|crate_type| {
1036 let res = !link::invalid_output_for_target(session, *crate_type);
1039 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1041 session.opts.target_triple));
1049 pub fn collect_crate_metadata(session: &Session, _attrs: &[ast::Attribute]) -> Vec<String> {
1050 session.opts.cg.metadata.clone()
1053 pub fn build_output_filenames(input: &Input,
1054 odir: &Option<PathBuf>,
1055 ofile: &Option<PathBuf>,
1056 attrs: &[ast::Attribute],
1058 -> OutputFilenames {
1061 // "-" as input file will cause the parser to read from stdin so we
1062 // have to make up a name
1063 // We want to toss everything after the final '.'
1064 let dirpath = match *odir {
1065 Some(ref d) => d.clone(),
1066 None => PathBuf::new(),
1069 // If a crate name is present, we use it as the link name
1070 let stem = sess.opts
1073 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1074 .unwrap_or(input.filestem());
1077 out_directory: dirpath,
1079 single_output_file: None,
1080 extra: sess.opts.cg.extra_filename.clone(),
1081 outputs: sess.opts.output_types.clone(),
1085 Some(ref out_file) => {
1086 let unnamed_output_types = sess.opts
1089 .filter(|a| a.is_none())
1091 let ofile = if unnamed_output_types > 1 {
1092 sess.warn("ignoring specified output filename because multiple outputs were \
1096 Some(out_file.clone())
1099 sess.warn("ignoring --out-dir flag due to -o flag.");
1102 let cur_dir = Path::new("");
1105 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1106 out_filestem: out_file.file_stem()
1107 .unwrap_or(OsStr::new(""))
1111 single_output_file: ofile,
1112 extra: sess.opts.cg.extra_filename.clone(),
1113 outputs: sess.opts.output_types.clone(),