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;
20 use rustc::metadata::creader::LocalCrateReader;
21 use rustc::middle::{stability, ty, reachable};
22 use rustc::middle::dependency_format;
24 use rustc::plugin::registry::Registry;
26 use rustc::util::nodemap::NodeMap;
27 use rustc::util::common::time;
28 use rustc_borrowck as borrowck;
29 use rustc_resolve as resolve;
30 use rustc_trans::back::link;
31 use rustc_trans::back::write;
32 use rustc_trans::trans;
33 use rustc_typeck as typeck;
36 use rustc_front::lowering::{lower_crate, LoweringContext};
37 use super::Compilation;
41 use std::collections::HashMap;
43 use std::ffi::{OsString, OsStr};
45 use std::io::{self, Write};
46 use std::path::{Path, PathBuf};
47 use syntax::ast::{self, NodeIdAssigner};
49 use syntax::attr::AttrMetaMethods;
50 use syntax::diagnostics;
51 use syntax::feature_gate::UnstableFeatures;
52 use syntax::fold::Folder;
54 use syntax::parse::token;
57 pub fn compile_input(sess: Session,
58 cfg: ast::CrateConfig,
60 outdir: &Option<PathBuf>,
61 output: &Option<PathBuf>,
62 addl_plugins: Option<Vec<String>>,
63 control: CompileController) {
64 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
65 let state = $make_state;
66 (control.$point.callback)(state);
68 $tsess.abort_if_errors();
69 if control.$point.stop == Compilation::Stop {
74 // We need nested scopes here, because the intermediate results can keep
75 // large chunks of memory alive and we want to free them as soon as
76 // possible to keep the peak memory usage low
78 let (outputs, expanded_crate, id) = {
79 let krate = phase_1_parse_input(&sess, cfg, input);
81 controller_entry_point!(after_parse,
83 CompileState::state_after_parse(input,
88 let outputs = build_output_filenames(input,
93 let id = link::find_crate_name(Some(&sess),
97 = match phase_2_configure_and_expand(&sess,
105 (outputs, expanded_crate, id)
108 controller_entry_point!(after_expand,
110 CompileState::state_after_expand(input,
116 let expanded_crate = assign_node_ids(&sess, expanded_crate);
118 let lcx = LoweringContext::new(&sess, Some(&expanded_crate));
119 let mut hir_forest = time(sess.time_passes(),
120 "lowering ast -> hir",
121 || hir_map::Forest::new(lower_crate(&lcx, &expanded_crate)));
122 let arenas = ty::CtxtArenas::new();
123 let ast_map = make_map(&sess, &mut hir_forest);
125 write_out_deps(&sess, &outputs, &id);
127 controller_entry_point!(after_write_deps,
129 CompileState::state_after_write_deps(input,
138 time(sess.time_passes(), "attribute checking", || {
139 front::check_attr::check_crate(&sess, &expanded_crate);
142 time(sess.time_passes(), "early lint checks", || {
143 lint::check_ast_crate(&sess, &expanded_crate)
146 phase_3_run_analysis_passes(&sess,
150 control.make_glob_map,
151 |tcx, mir_map, analysis| {
154 let state = CompileState::state_after_analysis(input,
163 (control.after_analysis.callback)(state);
165 tcx.sess.abort_if_errors();
166 if control.after_analysis.stop == Compilation::Stop {
171 if log_enabled!(::log::INFO) {
172 println!("Pre-trans");
173 tcx.print_debug_stats();
175 let trans = phase_4_translate_to_llvm(tcx, &mir_map, analysis);
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,
204 phase_6_link_output(&sess, &trans, &outputs);
207 /// The name used for source code that doesn't originate in a file
208 /// (e.g. source from stdin or a string)
209 pub fn anon_src() -> String {
213 pub fn source_name(input: &Input) -> String {
215 // FIXME (#9639): This needs to handle non-utf8 paths
216 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
217 Input::Str(_) => anon_src()
221 /// CompileController is used to customise compilation, it allows compilation to
222 /// be stopped and/or to call arbitrary code at various points in compilation.
223 /// It also allows for various flags to be set to influence what information gets
224 /// collected during compilation.
226 /// This is a somewhat higher level controller than a Session - the Session
227 /// controls what happens in each phase, whereas the CompileController controls
228 /// whether a phase is run at all and whether other code (from outside the
229 /// the compiler) is run between phases.
231 /// Note that if compilation is set to stop and a callback is provided for a
232 /// given entry point, the callback is called before compilation is stopped.
234 /// Expect more entry points to be added in the future.
235 pub struct CompileController<'a> {
236 pub after_parse: PhaseController<'a>,
237 pub after_expand: PhaseController<'a>,
238 pub after_write_deps: PhaseController<'a>,
239 pub after_analysis: PhaseController<'a>,
240 pub after_llvm: PhaseController<'a>,
242 pub make_glob_map: resolve::MakeGlobMap,
245 impl<'a> CompileController<'a> {
246 pub fn basic() -> CompileController<'a> {
248 after_parse: PhaseController::basic(),
249 after_expand: PhaseController::basic(),
250 after_write_deps: PhaseController::basic(),
251 after_analysis: PhaseController::basic(),
252 after_llvm: PhaseController::basic(),
253 make_glob_map: resolve::MakeGlobMap::No,
258 pub struct PhaseController<'a> {
259 pub stop: Compilation,
260 pub callback: Box<Fn(CompileState) -> () + 'a>,
263 impl<'a> PhaseController<'a> {
264 pub fn basic() -> PhaseController<'a> {
266 stop: Compilation::Continue,
267 callback: box |_| {},
272 /// State that is passed to a callback. What state is available depends on when
273 /// during compilation the callback is made. See the various constructor methods
274 /// (`state_*`) in the impl to see which data is provided for any given entry point.
275 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
276 pub input: &'a Input,
277 pub session: &'a Session,
278 pub cfg: Option<&'a ast::CrateConfig>,
279 pub krate: Option<&'a ast::Crate>,
280 pub crate_name: Option<&'a str>,
281 pub output_filenames: Option<&'a OutputFilenames>,
282 pub out_dir: Option<&'a Path>,
283 pub expanded_crate: Option<&'a ast::Crate>,
284 pub hir_crate: Option<&'a hir::Crate>,
285 pub ast_map: Option<&'a hir_map::Map<'ast>>,
286 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
287 pub tcx: Option<&'a ty::ctxt<'tcx>>,
288 pub lcx: Option<&'a LoweringContext<'a>>,
289 pub trans: Option<&'a trans::CrateTranslation>,
292 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
293 fn empty(input: &'a Input,
294 session: &'a Session,
295 out_dir: &'a Option<PathBuf>)
296 -> CompileState<'a, 'ast, 'tcx> {
300 out_dir: out_dir.as_ref().map(|s| &**s),
304 output_filenames: None,
305 expanded_crate: None,
315 fn state_after_parse(input: &'a Input,
316 session: &'a Session,
317 out_dir: &'a Option<PathBuf>,
318 krate: &'a ast::Crate)
319 -> CompileState<'a, 'ast, 'tcx> {
322 .. CompileState::empty(input, session, out_dir)
326 fn state_after_expand(input: &'a Input,
327 session: &'a Session,
328 out_dir: &'a Option<PathBuf>,
329 expanded_crate: &'a ast::Crate,
331 -> CompileState<'a, 'ast, 'tcx> {
333 crate_name: Some(crate_name),
334 expanded_crate: Some(expanded_crate),
335 .. CompileState::empty(input, session, out_dir)
339 fn state_after_write_deps(input: &'a Input,
340 session: &'a Session,
341 out_dir: &'a Option<PathBuf>,
342 ast_map: &'a hir_map::Map<'ast>,
343 krate: &'a ast::Crate,
344 hir_crate: &'a hir::Crate,
346 lcx: &'a LoweringContext<'a>)
347 -> CompileState<'a, 'ast, 'tcx> {
349 crate_name: Some(crate_name),
350 ast_map: Some(ast_map),
352 hir_crate: Some(hir_crate),
354 .. CompileState::empty(input, session, out_dir)
358 fn state_after_analysis(input: &'a Input,
359 session: &'a Session,
360 out_dir: &'a Option<PathBuf>,
361 krate: &'a ast::Crate,
362 hir_crate: &'a hir::Crate,
363 analysis: &'a ty::CrateAnalysis,
364 tcx: &'a ty::ctxt<'tcx>,
365 lcx: &'a LoweringContext<'a>,
367 -> CompileState<'a, 'ast, 'tcx> {
369 analysis: Some(analysis),
372 hir_crate: Some(hir_crate),
374 crate_name: Some(crate_name),
375 .. CompileState::empty(input, session, out_dir)
380 fn state_after_llvm(input: &'a Input,
381 session: &'a Session,
382 out_dir: &'a Option<PathBuf>,
383 trans: &'a trans::CrateTranslation)
384 -> CompileState<'a, 'ast, 'tcx> {
387 .. CompileState::empty(input, session, out_dir)
392 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
394 // These may be left in an incoherent state after a previous compile.
395 // `clear_tables` and `get_ident_interner().clear()` can be used to free
396 // memory, but they do not restore the initial state.
397 syntax::ext::mtwt::reset_tables();
398 token::reset_ident_interner();
400 let krate = time(sess.time_passes(), "parsing", || {
402 Input::File(ref file) => {
403 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
405 Input::Str(ref src) => {
406 parse::parse_crate_from_source_str(anon_src().to_string(),
414 if sess.opts.debugging_opts.ast_json_noexpand {
415 println!("{}", json::as_json(&krate));
418 if let Some(ref s) = sess.opts.show_span {
419 syntax::show_span::run(sess.diagnostic(), s, &krate);
425 // For continuing compilation after a parsed crate has been
428 /// Run the "early phases" of the compiler: initial `cfg` processing,
429 /// loading compiler plugins (including those from `addl_plugins`),
430 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
431 /// harness if one is to be provided and injection of a dependency on the
432 /// standard library and prelude.
434 /// Returns `None` if we're aborting after handling -W help.
435 pub fn phase_2_configure_and_expand(sess: &Session,
436 mut krate: ast::Crate,
438 addl_plugins: Option<Vec<String>>)
439 -> Option<ast::Crate> {
440 let time_passes = sess.time_passes();
442 // strip before anything else because crate metadata may use #[cfg_attr]
443 // and so macros can depend on configuration variables, such as
445 // #[macro_use] #[cfg(foo)]
446 // mod bar { macro_rules! baz!(() => {{}}) }
448 // baz! should not use this definition unless foo is enabled.
450 let mut feature_gated_cfgs = vec![];
451 krate = time(time_passes, "configuration 1", ||
452 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
453 &mut feature_gated_cfgs));
455 *sess.crate_types.borrow_mut() =
456 collect_crate_types(sess, &krate.attrs);
457 *sess.crate_metadata.borrow_mut() =
458 collect_crate_metadata(sess, &krate.attrs);
460 time(time_passes, "recursion limit", || {
461 middle::recursion_limit::update_recursion_limit(sess, &krate);
464 time(time_passes, "gated macro checking", || {
466 syntax::feature_gate::check_crate_macros(sess.codemap(),
467 &sess.parse_sess.span_diagnostic,
470 // these need to be set "early" so that expansion sees `quote` if enabled.
471 *sess.features.borrow_mut() = features;
472 sess.abort_if_errors();
476 krate = time(time_passes, "crate injection", ||
477 syntax::std_inject::maybe_inject_crates_ref(krate,
478 sess.opts.alt_std_name.clone()));
480 let macros = time(time_passes, "macro loading", ||
481 metadata::macro_import::read_macro_defs(sess, &krate));
483 let mut addl_plugins = Some(addl_plugins);
484 let registrars = time(time_passes, "plugin loading", ||
485 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
487 let mut registry = Registry::new(sess, &krate);
489 time(time_passes, "plugin registration", || {
490 if sess.features.borrow().rustc_diagnostic_macros {
491 registry.register_macro("__diagnostic_used",
492 diagnostics::plugin::expand_diagnostic_used);
493 registry.register_macro("__register_diagnostic",
494 diagnostics::plugin::expand_register_diagnostic);
495 registry.register_macro("__build_diagnostic_array",
496 diagnostics::plugin::expand_build_diagnostic_array);
499 for registrar in registrars {
500 registry.args_hidden = Some(registrar.args);
501 (registrar.fun)(&mut registry);
505 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
506 llvm_passes, attributes, .. } = registry;
509 let mut ls = sess.lint_store.borrow_mut();
510 for pass in early_lint_passes {
511 ls.register_early_pass(Some(sess), true, pass);
513 for pass in late_lint_passes {
514 ls.register_late_pass(Some(sess), true, pass);
517 for (name, to) in lint_groups {
518 ls.register_group(Some(sess), true, name, to);
521 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
522 *sess.plugin_attributes.borrow_mut() = attributes.clone();
525 // Lint plugins are registered; now we can process command line flags.
526 if sess.opts.describe_lints {
527 super::describe_lints(&*sess.lint_store.borrow(), true);
530 sess.lint_store.borrow_mut().process_command_line(sess);
532 // Abort if there are errors from lint processing or a plugin registrar.
533 sess.abort_if_errors();
535 krate = time(time_passes, "expansion", || {
536 // Windows dlls do not have rpaths, so they don't know how to find their
537 // dependencies. It's up to us to tell the system where to find all the
538 // dependent dlls. Note that this uses cfg!(windows) as opposed to
539 // targ_cfg because syntax extensions are always loaded for the host
540 // compiler, not for the target.
541 let mut _old_path = OsString::new();
543 _old_path = env::var_os("PATH").unwrap_or(_old_path);
544 let mut new_path = sess.host_filesearch(PathKind::All)
545 .get_dylib_search_paths();
546 new_path.extend(env::split_paths(&_old_path));
547 env::set_var("PATH", &env::join_paths(new_path).unwrap());
549 let features = sess.features.borrow();
550 let cfg = syntax::ext::expand::ExpansionConfig {
551 crate_name: crate_name.to_string(),
552 features: Some(&features),
553 recursion_limit: sess.recursion_limit.get(),
554 trace_mac: sess.opts.debugging_opts.trace_macros,
556 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
560 &mut feature_gated_cfgs,
563 env::set_var("PATH", &_old_path);
568 // Needs to go *after* expansion to be able to check the results
569 // of macro expansion. This runs before #[cfg] to try to catch as
570 // much as possible (e.g. help the programmer avoid platform
571 // specific differences)
572 time(time_passes, "complete gated feature checking 1", || {
574 syntax::feature_gate::check_crate(sess.codemap(),
575 &sess.parse_sess.span_diagnostic,
577 sess.opts.unstable_features);
578 *sess.features.borrow_mut() = features;
579 sess.abort_if_errors();
582 // JBC: make CFG processing part of expansion to avoid this problem:
584 // strip again, in case expansion added anything with a #[cfg].
585 krate = time(time_passes, "configuration 2", ||
586 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
587 &mut feature_gated_cfgs));
589 time(time_passes, "gated configuration checking", || {
590 let features = sess.features.borrow();
591 feature_gated_cfgs.sort();
592 feature_gated_cfgs.dedup();
593 for cfg in &feature_gated_cfgs {
594 cfg.check_and_emit(sess.diagnostic(), &features);
598 krate = time(time_passes, "maybe building test harness", ||
599 syntax::test::modify_for_testing(&sess.parse_sess,
604 krate = time(time_passes, "prelude injection", ||
605 syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
607 time(time_passes, "checking that all macro invocations are gone", ||
608 syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
610 time(time_passes, "checking for inline asm in case the target doesn't support it", ||
611 middle::check_no_asm::check_crate(sess, &krate));
613 // One final feature gating of the true AST that gets compiled
614 // later, to make sure we've got everything (e.g. configuration
615 // can insert new attributes via `cfg_attr`)
616 time(time_passes, "complete gated feature checking 2", || {
618 syntax::feature_gate::check_crate(sess.codemap(),
619 &sess.parse_sess.span_diagnostic,
621 sess.opts.unstable_features);
622 *sess.features.borrow_mut() = features;
623 sess.abort_if_errors();
629 pub fn assign_node_ids(sess: &Session,
630 krate: ast::Crate) -> ast::Crate {
631 struct NodeIdAssigner<'a> {
635 impl<'a> Folder for NodeIdAssigner<'a> {
636 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
637 assert_eq!(old_id, ast::DUMMY_NODE_ID);
638 self.sess.next_node_id()
642 let krate = time(sess.time_passes(),
643 "assigning node ids",
644 || NodeIdAssigner { sess: sess }.fold_crate(krate));
646 if sess.opts.debugging_opts.ast_json {
647 println!("{}", json::as_json(&krate));
653 pub fn make_map<'ast>(sess: &Session,
654 forest: &'ast mut front::map::Forest)
655 -> front::map::Map<'ast> {
656 // Construct the 'ast'-map
657 let map = time(sess.time_passes(),
659 move || front::map::map_crate(forest));
664 /// Run the resolution, typechecking, region checking and other
665 /// miscellaneous analysis passes on the crate. Return various
666 /// structures carrying the results of the analysis.
667 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
668 ast_map: front::map::Map<'tcx>,
669 arenas: &'tcx ty::CtxtArenas<'tcx>,
671 make_glob_map: resolve::MakeGlobMap,
674 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
676 ty::CrateAnalysis) -> R
678 let time_passes = sess.time_passes();
679 let krate = ast_map.krate();
681 time(time_passes, "external crate/lib resolution", ||
682 LocalCrateReader::new(sess, &ast_map).read_crates(krate));
684 let lang_items = time(time_passes, "language item collection", ||
685 middle::lang_items::collect_language_items(&sess, &ast_map));
687 let resolve::CrateMap {
695 time(time_passes, "resolution",
696 || resolve::resolve_crate(sess, &ast_map, make_glob_map));
698 // Discard MTWT tables that aren't required past resolution.
699 if !sess.opts.debugging_opts.keep_mtwt_tables {
700 syntax::ext::mtwt::clear_tables();
703 let named_region_map = time(time_passes, "lifetime resolution",
704 || middle::resolve_lifetime::krate(sess, krate, &def_map));
706 time(time_passes, "looking for entry point",
707 || middle::entry::find_entry_point(sess, &ast_map));
709 sess.plugin_registrar_fn.set(
710 time(time_passes, "looking for plugin registrar", ||
711 plugin::build::find_plugin_registrar(
712 sess.diagnostic(), krate)));
714 let region_map = time(time_passes, "region resolution", ||
715 middle::region::resolve_crate(sess, krate));
717 time(time_passes, "loop checking", ||
718 middle::check_loop::check_crate(sess, krate));
720 time(time_passes, "static item recursion checking", ||
721 middle::check_static_recursion::check_crate(sess, krate, &def_map, &ast_map));
723 ty::ctxt::create_and_enter(sess,
731 stability::Index::new(krate),
734 // passes are timed inside typeck
735 typeck::check_crate(tcx, trait_map);
737 time(time_passes, "const checking", ||
738 middle::check_const::check_crate(tcx));
740 let (exported_items, public_items) =
741 time(time_passes, "privacy checking", ||
742 rustc_privacy::check_crate(tcx, &export_map, external_exports));
744 // Do not move this check past lint
745 time(time_passes, "stability index", ||
746 tcx.stability.borrow_mut().build(tcx, krate, &public_items));
748 time(time_passes, "intrinsic checking", ||
749 middle::intrinsicck::check_crate(tcx));
751 time(time_passes, "effect checking", ||
752 middle::effect::check_crate(tcx));
754 time(time_passes, "match checking", ||
755 middle::check_match::check_crate(tcx));
757 let mir_map = match tcx.sess.opts.unstable_features {
758 UnstableFeatures::Disallow => {
759 // use this as a shorthand for beta/stable, and skip
760 // MIR construction there until known regressions are
764 UnstableFeatures::Allow | UnstableFeatures::Cheat => {
765 time(time_passes, "MIR dump", ||
766 mir::mir_map::build_mir_for_crate(tcx))
770 time(time_passes, "liveness checking", ||
771 middle::liveness::check_crate(tcx));
773 time(time_passes, "borrow checking", ||
774 borrowck::check_crate(tcx));
776 time(time_passes, "rvalue checking", ||
777 middle::check_rvalues::check_crate(tcx, krate));
779 // Avoid overwhelming user with errors if type checking failed.
780 // I'm not sure how helpful this is, to be honest, but it avoids a
781 // lot of annoying errors in the compile-fail tests (basically,
782 // lint warnings and so on -- kindck used to do this abort, but
783 // kindck is gone now). -nmatsakis
784 tcx.sess.abort_if_errors();
787 time(time_passes, "reachability checking", ||
788 reachable::find_reachable(tcx, &exported_items));
790 time(time_passes, "death checking", || {
791 middle::dead::check_crate(tcx,
796 let ref lib_features_used =
797 time(time_passes, "stability checking", ||
798 stability::check_unstable_api_usage(tcx));
800 time(time_passes, "unused lib feature checking", ||
801 stability::check_unused_or_stable_features(
802 &tcx.sess, lib_features_used));
804 time(time_passes, "lint checking", ||
805 lint::check_crate(tcx, krate, &exported_items));
807 // The above three passes generate errors w/o aborting
808 tcx.sess.abort_if_errors();
810 f(tcx, mir_map, ty::CrateAnalysis {
811 export_map: export_map,
812 exported_items: exported_items,
813 public_items: public_items,
814 reachable: reachable_map,
821 /// Run the translation phase to LLVM, after which the AST and analysis can
823 pub fn phase_4_translate_to_llvm<'tcx>(tcx: &ty::ctxt<'tcx>,
824 mir_map: &MirMap<'tcx>,
825 analysis: ty::CrateAnalysis)
826 -> trans::CrateTranslation {
827 let time_passes = tcx.sess.time_passes();
829 time(time_passes, "resolving dependency formats", ||
830 dependency_format::calculate(&tcx.sess));
832 // Option dance to work around the lack of stack once closures.
833 time(time_passes, "translation", move ||
834 trans::trans_crate(tcx, mir_map, analysis))
837 /// Run LLVM itself, producing a bitcode file, assembly file or object file
838 /// as a side effect.
839 pub fn phase_5_run_llvm_passes(sess: &Session,
840 trans: &trans::CrateTranslation,
841 outputs: &OutputFilenames) {
842 if sess.opts.cg.no_integrated_as {
843 let mut map = HashMap::new();
844 map.insert(OutputType::Assembly, None);
845 time(sess.time_passes(), "LLVM passes", ||
846 write::run_passes(sess, trans, &map, outputs));
848 write::run_assembler(sess, outputs);
850 // Remove assembly source, unless --save-temps was specified
851 if !sess.opts.cg.save_temps {
852 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
855 time(sess.time_passes(), "LLVM passes", ||
856 write::run_passes(sess,
858 &sess.opts.output_types,
862 sess.abort_if_errors();
865 /// Run the linker on any artifacts that resulted from the LLVM run.
866 /// This should produce either a finished executable or library.
867 pub fn phase_6_link_output(sess: &Session,
868 trans: &trans::CrateTranslation,
869 outputs: &OutputFilenames) {
870 time(sess.time_passes(), "linking", ||
871 link::link_binary(sess,
874 &trans.link.crate_name));
877 fn escape_dep_filename(filename: &str) -> String {
878 // Apparently clang and gcc *only* escape spaces:
879 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
880 filename.replace(" ", "\\ ")
883 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
884 let mut out_filenames = Vec::new();
885 for output_type in sess.opts.output_types.keys() {
886 let file = outputs.path(*output_type);
889 for output in sess.crate_types.borrow().iter() {
890 let p = link::filename_for_input(sess, *output, id,
892 out_filenames.push(p);
895 _ => { out_filenames.push(file); }
899 // Write out dependency rules to the dep-info file if requested
900 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
903 let deps_filename = outputs.path(OutputType::DepInfo);
905 let result = (|| -> io::Result<()> {
906 // Build a list of files used to compile the output and
907 // write Makefile-compatible dependency rules
908 let files: Vec<String> = sess.codemap().files.borrow()
910 .filter(|fmap| fmap.is_real_file())
911 .filter(|fmap| !fmap.is_imported())
912 .map(|fmap| escape_dep_filename(&fmap.name))
914 let mut file = try!(fs::File::create(&deps_filename));
915 for path in &out_filenames {
917 "{}: {}\n\n", path.display(), files.join(" ")));
920 // Emit a fake target for each input file to the compilation. This
921 // prevents `make` from spitting out an error if a file is later
922 // deleted. For more info see #28735
924 try!(writeln!(file, "{}:", path));
932 sess.fatal(&format!("error writing dependencies to `{}`: {}",
933 deps_filename.display(), e));
938 pub fn collect_crate_types(session: &Session,
939 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
940 // Unconditionally collect crate types from attributes to make them used
941 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
942 if a.check_name("crate_type") {
943 match a.value_str() {
944 Some(ref n) if *n == "rlib" => {
945 Some(config::CrateTypeRlib)
947 Some(ref n) if *n == "dylib" => {
948 Some(config::CrateTypeDylib)
950 Some(ref n) if *n == "lib" => {
951 Some(config::default_lib_output())
953 Some(ref n) if *n == "staticlib" => {
954 Some(config::CrateTypeStaticlib)
956 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
958 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
961 "invalid `crate_type` \
966 session.span_err(a.span, "`crate_type` requires a value");
967 session.note("for example: `#![crate_type=\"lib\"]`");
976 // If we're generating a test executable, then ignore all other output
977 // styles at all other locations
978 if session.opts.test {
979 return vec!(config::CrateTypeExecutable)
982 // Only check command line flags if present. If no types are specified by
983 // command line, then reuse the empty `base` Vec to hold the types that
984 // will be found in crate attributes.
985 let mut base = session.opts.crate_types.clone();
987 base.extend(attr_types);
989 base.push(link::default_output_for_target(session));
995 base.into_iter().filter(|crate_type| {
996 let res = !link::invalid_output_for_target(session, *crate_type);
999 session.warn(&format!("dropping unsupported crate type `{}` \
1001 *crate_type, session.opts.target_triple));
1008 pub fn collect_crate_metadata(session: &Session,
1009 _attrs: &[ast::Attribute]) -> Vec<String> {
1010 session.opts.cg.metadata.clone()
1013 pub fn build_output_filenames(input: &Input,
1014 odir: &Option<PathBuf>,
1015 ofile: &Option<PathBuf>,
1016 attrs: &[ast::Attribute],
1018 -> OutputFilenames {
1021 // "-" as input file will cause the parser to read from stdin so we
1022 // have to make up a name
1023 // We want to toss everything after the final '.'
1024 let dirpath = match *odir {
1025 Some(ref d) => d.clone(),
1026 None => PathBuf::new()
1029 // If a crate name is present, we use it as the link name
1030 let stem = sess.opts.crate_name.clone().or_else(|| {
1031 attr::find_crate_name(attrs).map(|n| n.to_string())
1032 }).unwrap_or(input.filestem());
1035 out_directory: dirpath,
1037 single_output_file: None,
1038 extra: sess.opts.cg.extra_filename.clone(),
1039 outputs: sess.opts.output_types.clone(),
1043 Some(ref out_file) => {
1044 let unnamed_output_types = sess.opts.output_types.values()
1045 .filter(|a| a.is_none())
1047 let ofile = if unnamed_output_types > 1 {
1048 sess.warn("ignoring specified output filename because multiple \
1049 outputs were requested");
1052 Some(out_file.clone())
1055 sess.warn("ignoring --out-dir flag due to -o flag.");
1058 let cur_dir = Path::new("");
1061 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1062 out_filestem: out_file.file_stem().unwrap_or(OsStr::new(""))
1063 .to_str().unwrap().to_string(),
1064 single_output_file: ofile,
1065 extra: sess.opts.cg.extra_filename.clone(),
1066 outputs: sess.opts.output_types.clone(),