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::common::time;
23 use rustc_borrowck as borrowck;
24 use rustc_resolve as resolve;
25 use rustc_metadata::macro_import;
26 use rustc_metadata::creader::LocalCrateReader;
27 use rustc_metadata::cstore::CStore;
28 use rustc_trans::back::link;
29 use rustc_trans::back::write;
30 use rustc_trans::trans;
31 use rustc_typeck as typeck;
33 use rustc_plugin::registry::Registry;
34 use rustc_plugin as plugin;
36 use rustc_front::lowering::{lower_crate, LoweringContext};
37 use rustc_passes::{no_asm, loops, consts, const_fn, rvalues, static_recursion};
38 use super::{Compilation, CompileResult, compile_result_from_err_count};
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::fold::Folder;
54 use syntax::parse::token;
55 use syntax::util::node_count::NodeCounter;
60 macro_rules! throw_if_errors {
62 let err_count = $tsess.err_count();
64 return Err(err_count);
69 pub fn compile_input(sess: &Session,
71 cfg: ast::CrateConfig,
73 outdir: &Option<PathBuf>,
74 output: &Option<PathBuf>,
75 addl_plugins: Option<Vec<String>>,
76 control: CompileController) -> CompileResult {
77 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
78 let state = $make_state;
79 (control.$point.callback)(state);
81 if control.$point.stop == Compilation::Stop {
82 return compile_result_from_err_count($tsess.err_count());
86 // We need nested scopes here, because the intermediate results can keep
87 // large chunks of memory alive and we want to free them as soon as
88 // possible to keep the peak memory usage low
89 let (outputs, trans) = {
90 let (outputs, expanded_crate, id) = {
91 let krate = phase_1_parse_input(sess, cfg, input);
93 controller_entry_point!(after_parse,
95 CompileState::state_after_parse(input, sess, outdir, &krate));
97 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
98 let id = link::find_crate_name(Some(sess), &krate.attrs, input);
99 let expanded_crate = try!(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)));
123 // Discard MTWT tables that aren't required past lowering to HIR.
124 if !sess.opts.debugging_opts.keep_mtwt_tables &&
125 !sess.opts.debugging_opts.save_analysis {
126 syntax::ext::mtwt::clear_tables();
129 let arenas = ty::CtxtArenas::new();
130 let hir_map = make_map(sess, &mut hir_forest);
132 write_out_deps(sess, &outputs, &id);
134 controller_entry_point!(after_write_deps,
136 CompileState::state_after_write_deps(input,
145 time(sess.time_passes(), "attribute checking", || {
146 front::check_attr::check_crate(sess, &expanded_crate);
149 time(sess.time_passes(),
151 || lint::check_ast_crate(sess, &expanded_crate));
153 let opt_crate = if sess.opts.debugging_opts.keep_ast ||
154 sess.opts.debugging_opts.save_analysis {
155 Some(&expanded_crate)
157 drop(expanded_crate);
161 try!(try!(phase_3_run_analysis_passes(sess,
166 control.make_glob_map,
167 |tcx, mir_map, analysis| {
170 CompileState::state_after_analysis(input,
180 (control.after_analysis.callback)(state);
182 throw_if_errors!(tcx.sess);
183 if control.after_analysis.stop == Compilation::Stop {
188 if log_enabled!(::log::INFO) {
189 println!("Pre-trans");
190 tcx.print_debug_stats();
192 let trans = phase_4_translate_to_llvm(tcx,
196 if log_enabled!(::log::INFO) {
197 println!("Post-trans");
198 tcx.print_debug_stats();
201 // Discard interned strings as they are no longer required.
202 token::get_ident_interner().clear();
208 try!(phase_5_run_llvm_passes(sess, &trans, &outputs));
210 controller_entry_point!(after_llvm,
212 CompileState::state_after_llvm(input, sess, outdir, &trans));
214 phase_6_link_output(sess, &trans, &outputs);
219 /// The name used for source code that doesn't originate in a file
220 /// (e.g. source from stdin or a string)
221 pub fn anon_src() -> String {
225 pub fn source_name(input: &Input) -> String {
227 // FIXME (#9639): This needs to handle non-utf8 paths
228 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
229 Input::Str(_) => anon_src(),
233 /// CompileController is used to customise compilation, it allows compilation to
234 /// be stopped and/or to call arbitrary code at various points in compilation.
235 /// It also allows for various flags to be set to influence what information gets
236 /// collected during compilation.
238 /// This is a somewhat higher level controller than a Session - the Session
239 /// controls what happens in each phase, whereas the CompileController controls
240 /// whether a phase is run at all and whether other code (from outside the
241 /// the compiler) is run between phases.
243 /// Note that if compilation is set to stop and a callback is provided for a
244 /// given entry point, the callback is called before compilation is stopped.
246 /// Expect more entry points to be added in the future.
247 pub struct CompileController<'a> {
248 pub after_parse: PhaseController<'a>,
249 pub after_expand: PhaseController<'a>,
250 pub after_write_deps: PhaseController<'a>,
251 pub after_analysis: PhaseController<'a>,
252 pub after_llvm: PhaseController<'a>,
254 pub make_glob_map: resolve::MakeGlobMap,
257 impl<'a> CompileController<'a> {
258 pub fn basic() -> CompileController<'a> {
260 after_parse: PhaseController::basic(),
261 after_expand: PhaseController::basic(),
262 after_write_deps: PhaseController::basic(),
263 after_analysis: PhaseController::basic(),
264 after_llvm: PhaseController::basic(),
265 make_glob_map: resolve::MakeGlobMap::No,
270 pub struct PhaseController<'a> {
271 pub stop: Compilation,
272 pub callback: Box<Fn(CompileState) -> () + 'a>,
275 impl<'a> PhaseController<'a> {
276 pub fn basic() -> PhaseController<'a> {
278 stop: Compilation::Continue,
279 callback: box |_| {},
284 /// State that is passed to a callback. What state is available depends on when
285 /// during compilation the callback is made. See the various constructor methods
286 /// (`state_*`) in the impl to see which data is provided for any given entry point.
287 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
288 pub input: &'a Input,
289 pub session: &'a Session,
290 pub cfg: Option<&'a ast::CrateConfig>,
291 pub krate: Option<&'a ast::Crate>,
292 pub crate_name: Option<&'a str>,
293 pub output_filenames: Option<&'a OutputFilenames>,
294 pub out_dir: Option<&'a Path>,
295 pub expanded_crate: Option<&'a ast::Crate>,
296 pub hir_crate: Option<&'a hir::Crate>,
297 pub ast_map: Option<&'a hir_map::Map<'ast>>,
298 pub mir_map: Option<&'a MirMap<'tcx>>,
299 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
300 pub tcx: Option<&'a ty::ctxt<'tcx>>,
301 pub lcx: Option<&'a LoweringContext<'a>>,
302 pub trans: Option<&'a trans::CrateTranslation>,
305 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
306 fn empty(input: &'a Input,
307 session: &'a Session,
308 out_dir: &'a Option<PathBuf>)
309 -> CompileState<'a, 'ast, 'tcx> {
313 out_dir: out_dir.as_ref().map(|s| &**s),
317 output_filenames: None,
318 expanded_crate: None,
329 fn state_after_parse(input: &'a Input,
330 session: &'a Session,
331 out_dir: &'a Option<PathBuf>,
332 krate: &'a ast::Crate)
333 -> CompileState<'a, 'ast, 'tcx> {
334 CompileState { krate: Some(krate), ..CompileState::empty(input, session, out_dir) }
337 fn state_after_expand(input: &'a Input,
338 session: &'a Session,
339 out_dir: &'a Option<PathBuf>,
340 expanded_crate: &'a ast::Crate,
342 -> CompileState<'a, 'ast, 'tcx> {
344 crate_name: Some(crate_name),
345 expanded_crate: Some(expanded_crate),
346 ..CompileState::empty(input, session, out_dir)
350 fn state_after_write_deps(input: &'a Input,
351 session: &'a Session,
352 out_dir: &'a Option<PathBuf>,
353 hir_map: &'a hir_map::Map<'ast>,
354 krate: &'a ast::Crate,
355 hir_crate: &'a hir::Crate,
357 lcx: &'a LoweringContext<'a>)
358 -> CompileState<'a, 'ast, 'tcx> {
360 crate_name: Some(crate_name),
361 ast_map: Some(hir_map),
363 hir_crate: Some(hir_crate),
365 ..CompileState::empty(input, session, out_dir)
369 fn state_after_analysis(input: &'a Input,
370 session: &'a Session,
371 out_dir: &'a Option<PathBuf>,
372 krate: Option<&'a ast::Crate>,
373 hir_crate: &'a hir::Crate,
374 analysis: &'a ty::CrateAnalysis,
375 mir_map: &'a MirMap<'tcx>,
376 tcx: &'a ty::ctxt<'tcx>,
377 lcx: &'a LoweringContext<'a>,
379 -> CompileState<'a, 'ast, 'tcx> {
381 analysis: Some(analysis),
382 mir_map: Some(mir_map),
385 hir_crate: Some(hir_crate),
387 crate_name: Some(crate_name),
388 ..CompileState::empty(input, session, out_dir)
393 fn state_after_llvm(input: &'a Input,
394 session: &'a Session,
395 out_dir: &'a Option<PathBuf>,
396 trans: &'a trans::CrateTranslation)
397 -> CompileState<'a, 'ast, 'tcx> {
398 CompileState { trans: Some(trans), ..CompileState::empty(input, session, out_dir) }
402 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input) -> ast::Crate {
403 // These may be left in an incoherent state after a previous compile.
404 // `clear_tables` and `get_ident_interner().clear()` can be used to free
405 // memory, but they do not restore the initial state.
406 syntax::ext::mtwt::reset_tables();
407 token::reset_ident_interner();
409 let krate = time(sess.time_passes(), "parsing", || {
411 Input::File(ref file) => {
412 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
414 Input::Str(ref src) => {
415 parse::parse_crate_from_source_str(anon_src().to_string(),
423 if sess.opts.debugging_opts.ast_json_noexpand {
424 println!("{}", json::as_json(&krate));
427 if sess.opts.debugging_opts.input_stats {
428 println!("Lines of code: {}", sess.codemap().count_lines());
429 println!("Pre-expansion node count: {}", count_nodes(&krate));
432 if let Some(ref s) = sess.opts.debugging_opts.show_span {
433 syntax::show_span::run(sess.diagnostic(), s, &krate);
439 fn count_nodes(krate: &ast::Crate) -> usize {
440 let mut counter = NodeCounter::new();
441 visit::walk_crate(&mut counter, krate);
445 // For continuing compilation after a parsed crate has been
448 /// Run the "early phases" of the compiler: initial `cfg` processing,
449 /// loading compiler plugins (including those from `addl_plugins`),
450 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
451 /// harness if one is to be provided and injection of a dependency on the
452 /// standard library and prelude.
454 /// Returns `None` if we're aborting after handling -W help.
455 pub fn phase_2_configure_and_expand(sess: &Session,
457 mut krate: ast::Crate,
459 addl_plugins: Option<Vec<String>>)
460 -> Result<ast::Crate, usize> {
461 let time_passes = sess.time_passes();
463 // strip before anything else because crate metadata may use #[cfg_attr]
464 // and so macros can depend on configuration variables, such as
466 // #[macro_use] #[cfg(foo)]
467 // mod bar { macro_rules! baz!(() => {{}}) }
469 // baz! should not use this definition unless foo is enabled.
471 let mut feature_gated_cfgs = vec![];
472 krate = try!(time(time_passes, "configuration 1", || {
473 sess.track_errors(|| {
474 syntax::config::strip_unconfigured_items(sess.diagnostic(),
476 &mut feature_gated_cfgs)
480 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
481 *sess.crate_metadata.borrow_mut() = collect_crate_metadata(sess, &krate.attrs);
483 time(time_passes, "recursion limit", || {
484 middle::recursion_limit::update_recursion_limit(sess, &krate);
487 try!(time(time_passes, "gated macro checking", || {
488 sess.track_errors(|| {
490 syntax::feature_gate::check_crate_macros(sess.codemap(),
491 &sess.parse_sess.span_diagnostic,
494 // these need to be set "early" so that expansion sees `quote` if enabled.
495 *sess.features.borrow_mut() = features;
500 krate = time(time_passes, "crate injection", || {
501 syntax::std_inject::maybe_inject_crates_ref(krate, sess.opts.alt_std_name.clone())
504 let macros = time(time_passes,
506 || macro_import::read_macro_defs(sess, &cstore, &krate));
508 let mut addl_plugins = Some(addl_plugins);
509 let registrars = time(time_passes, "plugin loading", || {
510 plugin::load::load_plugins(sess, &cstore, &krate, addl_plugins.take().unwrap())
513 let mut registry = Registry::new(sess, &krate);
515 time(time_passes, "plugin registration", || {
516 if sess.features.borrow().rustc_diagnostic_macros {
517 registry.register_macro("__diagnostic_used",
518 diagnostics::plugin::expand_diagnostic_used);
519 registry.register_macro("__register_diagnostic",
520 diagnostics::plugin::expand_register_diagnostic);
521 registry.register_macro("__build_diagnostic_array",
522 diagnostics::plugin::expand_build_diagnostic_array);
525 for registrar in registrars {
526 registry.args_hidden = Some(registrar.args);
527 (registrar.fun)(&mut registry);
531 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
532 llvm_passes, attributes, .. } = registry;
534 try!(sess.track_errors(|| {
535 let mut ls = sess.lint_store.borrow_mut();
536 for pass in early_lint_passes {
537 ls.register_early_pass(Some(sess), true, pass);
539 for pass in late_lint_passes {
540 ls.register_late_pass(Some(sess), true, pass);
543 for (name, to) in lint_groups {
544 ls.register_group(Some(sess), true, name, to);
547 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
548 *sess.plugin_attributes.borrow_mut() = attributes.clone();
551 // Lint plugins are registered; now we can process command line flags.
552 if sess.opts.describe_lints {
553 super::describe_lints(&*sess.lint_store.borrow(), true);
556 try!(sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess)));
558 krate = time(time_passes, "expansion", || {
559 // Windows dlls do not have rpaths, so they don't know how to find their
560 // dependencies. It's up to us to tell the system where to find all the
561 // dependent dlls. Note that this uses cfg!(windows) as opposed to
562 // targ_cfg because syntax extensions are always loaded for the host
563 // compiler, not for the target.
564 let mut _old_path = OsString::new();
566 _old_path = env::var_os("PATH").unwrap_or(_old_path);
567 let mut new_path = sess.host_filesearch(PathKind::All)
568 .get_dylib_search_paths();
569 new_path.extend(env::split_paths(&_old_path));
570 env::set_var("PATH", &env::join_paths(new_path).unwrap());
572 let features = sess.features.borrow();
573 let cfg = syntax::ext::expand::ExpansionConfig {
574 crate_name: crate_name.to_string(),
575 features: Some(&features),
576 recursion_limit: sess.recursion_limit.get(),
577 trace_mac: sess.opts.debugging_opts.trace_macros,
579 let mut ecx = syntax::ext::base::ExtCtxt::new(&sess.parse_sess,
580 krate.config.clone(),
582 &mut feature_gated_cfgs);
583 syntax_ext::register_builtins(&mut ecx.syntax_env);
584 let (ret, macro_names) = syntax::ext::expand::expand_crate(ecx,
589 env::set_var("PATH", &_old_path);
591 *sess.available_macros.borrow_mut() = macro_names;
595 // Needs to go *after* expansion to be able to check the results
596 // of macro expansion. This runs before #[cfg] to try to catch as
597 // much as possible (e.g. help the programmer avoid platform
598 // specific differences)
599 try!(time(time_passes, "complete gated feature checking 1", || {
600 sess.track_errors(|| {
601 let features = syntax::feature_gate::check_crate(sess.codemap(),
602 &sess.parse_sess.span_diagnostic,
605 sess.opts.unstable_features);
606 *sess.features.borrow_mut() = features;
610 // JBC: make CFG processing part of expansion to avoid this problem:
612 // strip again, in case expansion added anything with a #[cfg].
613 krate = try!(sess.track_errors(|| {
614 let krate = time(time_passes, "configuration 2", || {
615 syntax::config::strip_unconfigured_items(sess.diagnostic(),
617 &mut feature_gated_cfgs)
620 time(time_passes, "gated configuration checking", || {
621 let features = sess.features.borrow();
622 feature_gated_cfgs.sort();
623 feature_gated_cfgs.dedup();
624 for cfg in &feature_gated_cfgs {
625 cfg.check_and_emit(sess.diagnostic(), &features, sess.codemap());
632 krate = time(time_passes, "maybe building test harness", || {
633 syntax::test::modify_for_testing(&sess.parse_sess, &sess.opts.cfg, krate, sess.diagnostic())
636 krate = time(time_passes,
638 || syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
641 "checking that all macro invocations are gone",
642 || syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
645 "checking for inline asm in case the target doesn't support it",
646 || no_asm::check_crate(sess, &krate));
648 // One final feature gating of the true AST that gets compiled
649 // later, to make sure we've got everything (e.g. configuration
650 // can insert new attributes via `cfg_attr`)
651 try!(time(time_passes, "complete gated feature checking 2", || {
652 sess.track_errors(|| {
653 let features = syntax::feature_gate::check_crate(sess.codemap(),
654 &sess.parse_sess.span_diagnostic,
657 sess.opts.unstable_features);
658 *sess.features.borrow_mut() = features;
663 "const fn bodies and arguments",
664 || const_fn::check_crate(sess, &krate));
666 if sess.opts.debugging_opts.input_stats {
667 println!("Post-expansion node count: {}", count_nodes(&krate));
673 pub fn assign_node_ids(sess: &Session, krate: ast::Crate) -> ast::Crate {
674 struct NodeIdAssigner<'a> {
678 impl<'a> Folder for NodeIdAssigner<'a> {
679 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
680 assert_eq!(old_id, ast::DUMMY_NODE_ID);
681 self.sess.next_node_id()
685 let krate = time(sess.time_passes(),
686 "assigning node ids",
687 || NodeIdAssigner { sess: sess }.fold_crate(krate));
689 if sess.opts.debugging_opts.ast_json {
690 println!("{}", json::as_json(&krate));
696 pub fn make_map<'ast>(sess: &Session,
697 forest: &'ast mut hir_map::Forest)
698 -> hir_map::Map<'ast> {
699 // Construct the HIR map
700 time(sess.time_passes(),
702 move || hir_map::map_crate(forest))
705 /// Run the resolution, typechecking, region checking and other
706 /// miscellaneous analysis passes on the crate. Return various
707 /// structures carrying the results of the analysis.
708 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
710 hir_map: hir_map::Map<'tcx>,
711 arenas: &'tcx ty::CtxtArenas<'tcx>,
713 make_glob_map: resolve::MakeGlobMap,
716 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>, MirMap<'tcx>, ty::CrateAnalysis) -> R
718 let time_passes = sess.time_passes();
719 let krate = hir_map.krate();
722 "external crate/lib resolution",
723 || LocalCrateReader::new(sess, cstore, &hir_map).read_crates(krate));
725 let lang_items = try!(time(time_passes, "language item collection", || {
726 sess.track_errors(|| {
727 middle::lang_items::collect_language_items(&sess, &hir_map)
731 let resolve::CrateMap {
738 } = time(time_passes,
740 || resolve::resolve_crate(sess, &hir_map, make_glob_map));
742 let named_region_map = time(time_passes,
743 "lifetime resolution",
744 || middle::resolve_lifetime::krate(sess, krate, &def_map.borrow()));
747 "looking for entry point",
748 || middle::entry::find_entry_point(sess, &hir_map));
750 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
751 plugin::build::find_plugin_registrar(sess.diagnostic(), krate)
754 let region_map = time(time_passes,
756 || middle::region::resolve_crate(sess, krate));
760 || loops::check_crate(sess, krate));
763 "static item recursion checking",
764 || static_recursion::check_crate(sess, krate, &def_map.borrow(), &hir_map));
766 ty::ctxt::create_and_enter(sess,
774 stability::Index::new(krate),
776 // passes are timed inside typeck
777 typeck::check_crate(tcx, trait_map);
781 || consts::check_crate(tcx));
784 time(time_passes, "privacy checking", || {
785 rustc_privacy::check_crate(tcx,
790 // Do not move this check past lint
791 time(time_passes, "stability index", || {
792 tcx.stability.borrow_mut().build(tcx, krate, &access_levels)
796 "intrinsic checking",
797 || middle::intrinsicck::check_crate(tcx));
801 || middle::effect::check_crate(tcx));
805 || middle::check_match::check_crate(tcx));
810 || mir::mir_map::build_mir_for_crate(tcx));
814 || middle::liveness::check_crate(tcx));
818 || borrowck::check_crate(tcx));
822 || rvalues::check_crate(tcx));
824 // Avoid overwhelming user with errors if type checking failed.
825 // I'm not sure how helpful this is, to be honest, but it avoids
827 // lot of annoying errors in the compile-fail tests (basically,
828 // lint warnings and so on -- kindck used to do this abort, but
829 // kindck is gone now). -nmatsakis
830 throw_if_errors!(tcx.sess);
834 "reachability checking",
835 || reachable::find_reachable(tcx, &access_levels));
837 time(time_passes, "death checking", || {
838 middle::dead::check_crate(tcx, &access_levels);
841 let ref lib_features_used =
843 "stability checking",
844 || stability::check_unstable_api_usage(tcx));
846 time(time_passes, "unused lib feature checking", || {
847 stability::check_unused_or_stable_features(&tcx.sess,
853 || lint::check_crate(tcx, &access_levels));
855 // The above three passes generate errors w/o aborting
856 throw_if_errors!(tcx.sess);
861 export_map: export_map,
862 access_levels: access_levels,
863 reachable: reachable_map,
870 /// Run the translation phase to LLVM, after which the AST and analysis can
872 pub fn phase_4_translate_to_llvm<'tcx>(tcx: &ty::ctxt<'tcx>,
873 mut mir_map: MirMap<'tcx>,
874 analysis: ty::CrateAnalysis)
875 -> trans::CrateTranslation {
876 let time_passes = tcx.sess.time_passes();
879 "resolving dependency formats",
880 || dependency_format::calculate(&tcx.sess));
883 "erasing regions from MIR",
884 || mir::transform::erase_regions::erase_regions(tcx, &mut mir_map));
886 // Option dance to work around the lack of stack once closures.
889 move || trans::trans_crate(tcx, &mir_map, analysis))
892 /// Run LLVM itself, producing a bitcode file, assembly file or object file
893 /// as a side effect.
894 pub fn phase_5_run_llvm_passes(sess: &Session,
895 trans: &trans::CrateTranslation,
896 outputs: &OutputFilenames) -> CompileResult {
897 if sess.opts.cg.no_integrated_as {
898 let mut map = HashMap::new();
899 map.insert(OutputType::Assembly, None);
900 time(sess.time_passes(),
902 || write::run_passes(sess, trans, &map, outputs));
904 write::run_assembler(sess, outputs);
906 // Remove assembly source, unless --save-temps was specified
907 if !sess.opts.cg.save_temps {
908 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
911 time(sess.time_passes(),
913 || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
916 throw_if_errors!(sess);
920 /// Run the linker on any artifacts that resulted from the LLVM run.
921 /// This should produce either a finished executable or library.
922 pub fn phase_6_link_output(sess: &Session,
923 trans: &trans::CrateTranslation,
924 outputs: &OutputFilenames) {
925 time(sess.time_passes(),
927 || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
930 fn escape_dep_filename(filename: &str) -> String {
931 // Apparently clang and gcc *only* escape spaces:
932 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
933 filename.replace(" ", "\\ ")
936 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
937 let mut out_filenames = Vec::new();
938 for output_type in sess.opts.output_types.keys() {
939 let file = outputs.path(*output_type);
942 for output in sess.crate_types.borrow().iter() {
943 let p = link::filename_for_input(sess, *output, id, outputs);
944 out_filenames.push(p);
948 out_filenames.push(file);
953 // Write out dependency rules to the dep-info file if requested
954 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
957 let deps_filename = outputs.path(OutputType::DepInfo);
960 (|| -> io::Result<()> {
961 // Build a list of files used to compile the output and
962 // write Makefile-compatible dependency rules
963 let files: Vec<String> = sess.codemap()
967 .filter(|fmap| fmap.is_real_file())
968 .filter(|fmap| !fmap.is_imported())
969 .map(|fmap| escape_dep_filename(&fmap.name))
971 let mut file = try!(fs::File::create(&deps_filename));
972 for path in &out_filenames {
973 try!(write!(file, "{}: {}\n\n", path.display(), files.join(" ")));
976 // Emit a fake target for each input file to the compilation. This
977 // prevents `make` from spitting out an error if a file is later
978 // deleted. For more info see #28735
980 try!(writeln!(file, "{}:", path));
988 sess.fatal(&format!("error writing dependencies to `{}`: {}",
989 deps_filename.display(),
995 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
996 // Unconditionally collect crate types from attributes to make them used
997 let attr_types: Vec<config::CrateType> =
1000 if a.check_name("crate_type") {
1001 match a.value_str() {
1002 Some(ref n) if *n == "rlib" => {
1003 Some(config::CrateTypeRlib)
1005 Some(ref n) if *n == "dylib" => {
1006 Some(config::CrateTypeDylib)
1008 Some(ref n) if *n == "lib" => {
1009 Some(config::default_lib_output())
1011 Some(ref n) if *n == "staticlib" => {
1012 Some(config::CrateTypeStaticlib)
1014 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1016 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1019 "invalid `crate_type` value".to_string());
1023 session.struct_span_err(a.span, "`crate_type` requires a value")
1024 .note("for example: `#![crate_type=\"lib\"]`")
1035 // If we're generating a test executable, then ignore all other output
1036 // styles at all other locations
1037 if session.opts.test {
1038 return vec![config::CrateTypeExecutable];
1041 // Only check command line flags if present. If no types are specified by
1042 // command line, then reuse the empty `base` Vec to hold the types that
1043 // will be found in crate attributes.
1044 let mut base = session.opts.crate_types.clone();
1045 if base.is_empty() {
1046 base.extend(attr_types);
1047 if base.is_empty() {
1048 base.push(link::default_output_for_target(session));
1055 .filter(|crate_type| {
1056 let res = !link::invalid_output_for_target(session, *crate_type);
1059 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1061 session.opts.target_triple));
1069 pub fn collect_crate_metadata(session: &Session, _attrs: &[ast::Attribute]) -> Vec<String> {
1070 session.opts.cg.metadata.clone()
1073 pub fn build_output_filenames(input: &Input,
1074 odir: &Option<PathBuf>,
1075 ofile: &Option<PathBuf>,
1076 attrs: &[ast::Attribute],
1078 -> OutputFilenames {
1081 // "-" as input file will cause the parser to read from stdin so we
1082 // have to make up a name
1083 // We want to toss everything after the final '.'
1084 let dirpath = match *odir {
1085 Some(ref d) => d.clone(),
1086 None => PathBuf::new(),
1089 // If a crate name is present, we use it as the link name
1090 let stem = sess.opts
1093 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1094 .unwrap_or(input.filestem());
1097 out_directory: dirpath,
1099 single_output_file: None,
1100 extra: sess.opts.cg.extra_filename.clone(),
1101 outputs: sess.opts.output_types.clone(),
1105 Some(ref out_file) => {
1106 let unnamed_output_types = sess.opts
1109 .filter(|a| a.is_none())
1111 let ofile = if unnamed_output_types > 1 {
1112 sess.warn("ignoring specified output filename because multiple outputs were \
1116 Some(out_file.clone())
1119 sess.warn("ignoring --out-dir flag due to -o flag.");
1122 let cur_dir = Path::new("");
1125 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1126 out_filestem: out_file.file_stem()
1127 .unwrap_or(OsStr::new(""))
1131 single_output_file: ofile,
1132 extra: sess.opts.cg.extra_filename.clone(),
1133 outputs: sess.opts.output_types.clone(),