]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/driver.rs
Pass the mir map to trans
[rust.git] / src / librustc_driver / driver.rs
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.
4 //
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.
10
11 use rustc::front;
12 use rustc::front::map as hir_map;
13 use rustc_mir as mir;
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;
18 use rustc::lint;
19 use rustc::metadata;
20 use rustc::metadata::creader::LocalCrateReader;
21 use rustc::middle::{stability, ty, reachable};
22 use rustc::middle::dependency_format;
23 use rustc::middle;
24 use rustc::plugin::registry::Registry;
25 use rustc::plugin;
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;
34 use rustc_privacy;
35 use rustc_front::hir;
36 use rustc_front::lowering::{lower_crate, LoweringContext};
37 use super::Compilation;
38
39 use serialize::json;
40
41 use std::collections::HashMap;
42 use std::env;
43 use std::ffi::{OsString, OsStr};
44 use std::fs;
45 use std::io::{self, Write};
46 use std::path::{Path, PathBuf};
47 use syntax::ast::{self, NodeIdAssigner};
48 use syntax::attr;
49 use syntax::attr::AttrMetaMethods;
50 use syntax::diagnostics;
51 use syntax::feature_gate::UnstableFeatures;
52 use syntax::fold::Folder;
53 use syntax::parse;
54 use syntax::parse::token;
55 use syntax;
56
57 pub fn compile_input(sess: Session,
58                      cfg: ast::CrateConfig,
59                      input: &Input,
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);
67
68         $tsess.abort_if_errors();
69         if control.$point.stop == Compilation::Stop {
70             return;
71         }
72     })}
73
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
77     let result = {
78         let (outputs, expanded_crate, id) = {
79             let krate = phase_1_parse_input(&sess, cfg, input);
80
81             controller_entry_point!(after_parse,
82                                     sess,
83                                     CompileState::state_after_parse(input,
84                                                                     &sess,
85                                                                     outdir,
86                                                                     &krate));
87
88             let outputs = build_output_filenames(input,
89                                                  outdir,
90                                                  output,
91                                                  &krate.attrs,
92                                                  &sess);
93             let id = link::find_crate_name(Some(&sess),
94                                            &krate.attrs,
95                                            input);
96             let expanded_crate
97                 = match phase_2_configure_and_expand(&sess,
98                                                      krate,
99                                                      &id[..],
100                                                      addl_plugins) {
101                     None => return,
102                     Some(k) => k
103                 };
104
105             (outputs, expanded_crate, id)
106         };
107
108         controller_entry_point!(after_expand,
109                                 sess,
110                                 CompileState::state_after_expand(input,
111                                                                  &sess,
112                                                                  outdir,
113                                                                  &expanded_crate,
114                                                                  &id[..]));
115
116         let expanded_crate = assign_node_ids(&sess, expanded_crate);
117         // Lower ast -> hir.
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);
124
125         write_out_deps(&sess, &outputs, &id);
126
127         controller_entry_point!(after_write_deps,
128                                 sess,
129                                 CompileState::state_after_write_deps(input,
130                                                                      &sess,
131                                                                      outdir,
132                                                                      &ast_map,
133                                                                      &expanded_crate,
134                                                                      &ast_map.krate(),
135                                                                      &id[..],
136                                                                      &lcx));
137
138         time(sess.time_passes(), "attribute checking", || {
139             front::check_attr::check_crate(&sess, &expanded_crate);
140         });
141
142         time(sess.time_passes(), "early lint checks", || {
143             lint::check_ast_crate(&sess, &expanded_crate)
144         });
145
146         phase_3_run_analysis_passes(&sess,
147                                     ast_map,
148                                     &arenas,
149                                     &id,
150                                     control.make_glob_map,
151                                     |tcx, mir_map, analysis| {
152
153             {
154                 let state = CompileState::state_after_analysis(input,
155                                                                &tcx.sess,
156                                                                outdir,
157                                                                &expanded_crate,
158                                                                tcx.map.krate(),
159                                                                &analysis,
160                                                                tcx,
161                                                                &lcx,
162                                                                &id);
163                 (control.after_analysis.callback)(state);
164
165                 tcx.sess.abort_if_errors();
166                 if control.after_analysis.stop == Compilation::Stop {
167                     return Err(());
168                 }
169             }
170
171             if log_enabled!(::log::INFO) {
172                 println!("Pre-trans");
173                 tcx.print_debug_stats();
174             }
175             let trans = phase_4_translate_to_llvm(tcx, &mir_map, analysis);
176
177             if log_enabled!(::log::INFO) {
178                 println!("Post-trans");
179                 tcx.print_debug_stats();
180             }
181
182             // Discard interned strings as they are no longer required.
183             token::get_ident_interner().clear();
184
185             Ok((outputs, trans))
186         })
187     };
188
189     let (outputs, trans) = if let Ok(out) = result {
190         out
191     } else {
192         return;
193     };
194
195     phase_5_run_llvm_passes(&sess, &trans, &outputs);
196
197     controller_entry_point!(after_llvm,
198                             sess,
199                             CompileState::state_after_llvm(input,
200                                                            &sess,
201                                                            outdir,
202                                                            &trans));
203
204     phase_6_link_output(&sess, &trans, &outputs);
205 }
206
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 {
210     "<anon>".to_string()
211 }
212
213 pub fn source_name(input: &Input) -> String {
214     match *input {
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()
218     }
219 }
220
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.
225 ///
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.
230 ///
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.
233 ///
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>,
241
242     pub make_glob_map: resolve::MakeGlobMap,
243 }
244
245 impl<'a> CompileController<'a> {
246     pub fn basic() -> CompileController<'a> {
247         CompileController {
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,
254         }
255     }
256 }
257
258 pub struct PhaseController<'a> {
259     pub stop: Compilation,
260     pub callback: Box<Fn(CompileState) -> () + 'a>,
261 }
262
263 impl<'a> PhaseController<'a> {
264     pub fn basic() -> PhaseController<'a> {
265         PhaseController {
266             stop: Compilation::Continue,
267             callback: box |_| {},
268         }
269     }
270 }
271
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>,
290 }
291
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> {
297         CompileState {
298             input: input,
299             session: session,
300             out_dir: out_dir.as_ref().map(|s| &**s),
301             cfg: None,
302             krate: None,
303             crate_name: None,
304             output_filenames: None,
305             expanded_crate: None,
306             hir_crate: None,
307             ast_map: None,
308             analysis: None,
309             tcx: None,
310             lcx: None,
311             trans: None,
312         }
313     }
314
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> {
320         CompileState {
321             krate: Some(krate),
322             .. CompileState::empty(input, session, out_dir)
323         }
324     }
325
326     fn state_after_expand(input: &'a Input,
327                           session: &'a Session,
328                           out_dir: &'a Option<PathBuf>,
329                           expanded_crate: &'a ast::Crate,
330                           crate_name: &'a str)
331                           -> CompileState<'a, 'ast, 'tcx> {
332         CompileState {
333             crate_name: Some(crate_name),
334             expanded_crate: Some(expanded_crate),
335             .. CompileState::empty(input, session, out_dir)
336         }
337     }
338
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,
345                               crate_name: &'a str,
346                               lcx: &'a LoweringContext<'a>)
347                               -> CompileState<'a, 'ast, 'tcx> {
348         CompileState {
349             crate_name: Some(crate_name),
350             ast_map: Some(ast_map),
351             krate: Some(krate),
352             hir_crate: Some(hir_crate),
353             lcx: Some(lcx),
354             .. CompileState::empty(input, session, out_dir)
355         }
356     }
357
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>,
366                             crate_name: &'a str)
367                             -> CompileState<'a, 'ast, 'tcx> {
368         CompileState {
369             analysis: Some(analysis),
370             tcx: Some(tcx),
371             krate: Some(krate),
372             hir_crate: Some(hir_crate),
373             lcx: Some(lcx),
374             crate_name: Some(crate_name),
375             .. CompileState::empty(input, session, out_dir)
376         }
377     }
378
379
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> {
385         CompileState {
386             trans: Some(trans),
387             .. CompileState::empty(input, session, out_dir)
388         }
389     }
390 }
391
392 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
393     -> ast::Crate {
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();
399
400     let krate = time(sess.time_passes(), "parsing", || {
401         match *input {
402             Input::File(ref file) => {
403                 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
404             }
405             Input::Str(ref src) => {
406                 parse::parse_crate_from_source_str(anon_src().to_string(),
407                                                    src.to_string(),
408                                                    cfg.clone(),
409                                                    &sess.parse_sess)
410             }
411         }
412     });
413
414     if sess.opts.debugging_opts.ast_json_noexpand {
415         println!("{}", json::as_json(&krate));
416     }
417
418     if let Some(ref s) = sess.opts.show_span {
419         syntax::show_span::run(sess.diagnostic(), s, &krate);
420     }
421
422     krate
423 }
424
425 // For continuing compilation after a parsed crate has been
426 // modified
427
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.
433 ///
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,
437                                     crate_name: &str,
438                                     addl_plugins: Option<Vec<String>>)
439                                     -> Option<ast::Crate> {
440     let time_passes = sess.time_passes();
441
442     // strip before anything else because crate metadata may use #[cfg_attr]
443     // and so macros can depend on configuration variables, such as
444     //
445     //   #[macro_use] #[cfg(foo)]
446     //   mod bar { macro_rules! baz!(() => {{}}) }
447     //
448     // baz! should not use this definition unless foo is enabled.
449
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));
454
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);
459
460     time(time_passes, "recursion limit", || {
461         middle::recursion_limit::update_recursion_limit(sess, &krate);
462     });
463
464     time(time_passes, "gated macro checking", || {
465         let features =
466             syntax::feature_gate::check_crate_macros(sess.codemap(),
467                                                      &sess.parse_sess.span_diagnostic,
468                                                      &krate);
469
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();
473     });
474
475
476     krate = time(time_passes, "crate injection", ||
477                  syntax::std_inject::maybe_inject_crates_ref(krate,
478                                                              sess.opts.alt_std_name.clone()));
479
480     let macros = time(time_passes, "macro loading", ||
481         metadata::macro_import::read_macro_defs(sess, &krate));
482
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()));
486
487     let mut registry = Registry::new(sess, &krate);
488
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);
497         }
498
499         for registrar in registrars {
500             registry.args_hidden = Some(registrar.args);
501             (registrar.fun)(&mut registry);
502         }
503     });
504
505     let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
506                    llvm_passes, attributes, .. } = registry;
507
508     {
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);
512         }
513         for pass in late_lint_passes {
514             ls.register_late_pass(Some(sess), true, pass);
515         }
516
517         for (name, to) in lint_groups {
518             ls.register_group(Some(sess), true, name, to);
519         }
520
521         *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
522         *sess.plugin_attributes.borrow_mut() = attributes.clone();
523     }
524
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);
528         return None;
529     }
530     sess.lint_store.borrow_mut().process_command_line(sess);
531
532     // Abort if there are errors from lint processing or a plugin registrar.
533     sess.abort_if_errors();
534
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();
542         if cfg!(windows) {
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());
548         }
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,
555         };
556         let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
557                                           cfg,
558                                           macros,
559                                           syntax_exts,
560                                           &mut feature_gated_cfgs,
561                                           krate);
562         if cfg!(windows) {
563             env::set_var("PATH", &_old_path);
564         }
565         ret
566     });
567
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", || {
573         let features =
574             syntax::feature_gate::check_crate(sess.codemap(),
575                                               &sess.parse_sess.span_diagnostic,
576                                               &krate, &attributes,
577                                               sess.opts.unstable_features);
578         *sess.features.borrow_mut() = features;
579         sess.abort_if_errors();
580     });
581
582     // JBC: make CFG processing part of expansion to avoid this problem:
583
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));
588
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);
595         }
596     });
597
598     krate = time(time_passes, "maybe building test harness", ||
599                  syntax::test::modify_for_testing(&sess.parse_sess,
600                                                   &sess.opts.cfg,
601                                                   krate,
602                                                   sess.diagnostic()));
603
604     krate = time(time_passes, "prelude injection", ||
605                  syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
606
607     time(time_passes, "checking that all macro invocations are gone", ||
608          syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
609
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));
612
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", || {
617         let features =
618             syntax::feature_gate::check_crate(sess.codemap(),
619                                               &sess.parse_sess.span_diagnostic,
620                                               &krate, &attributes,
621                                               sess.opts.unstable_features);
622         *sess.features.borrow_mut() = features;
623         sess.abort_if_errors();
624     });
625
626     Some(krate)
627 }
628
629 pub fn assign_node_ids(sess: &Session,
630                        krate: ast::Crate) -> ast::Crate {
631     struct NodeIdAssigner<'a> {
632         sess: &'a Session
633     }
634
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()
639         }
640     }
641
642     let krate = time(sess.time_passes(),
643                      "assigning node ids",
644                      || NodeIdAssigner { sess: sess }.fold_crate(krate));
645
646     if sess.opts.debugging_opts.ast_json {
647         println!("{}", json::as_json(&krate));
648     }
649
650     krate
651 }
652
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(),
658                    "indexing hir",
659                    move || front::map::map_crate(forest));
660
661     map
662 }
663
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>,
670                                                name: &str,
671                                                make_glob_map: resolve::MakeGlobMap,
672                                                f: F)
673                                                -> R
674                                                where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
675                                                                        MirMap<'tcx>,
676                                                                        ty::CrateAnalysis) -> R
677 {
678     let time_passes = sess.time_passes();
679     let krate = ast_map.krate();
680
681     time(time_passes, "external crate/lib resolution", ||
682          LocalCrateReader::new(sess, &ast_map).read_crates(krate));
683
684     let lang_items = time(time_passes, "language item collection", ||
685                           middle::lang_items::collect_language_items(&sess, &ast_map));
686
687     let resolve::CrateMap {
688         def_map,
689         freevars,
690         export_map,
691         trait_map,
692         external_exports,
693         glob_map,
694     } =
695         time(time_passes, "resolution",
696              || resolve::resolve_crate(sess, &ast_map, make_glob_map));
697
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();
701     }
702
703     let named_region_map = time(time_passes, "lifetime resolution",
704                                 || middle::resolve_lifetime::krate(sess, krate, &def_map));
705
706     time(time_passes, "looking for entry point",
707          || middle::entry::find_entry_point(sess, &ast_map));
708
709     sess.plugin_registrar_fn.set(
710         time(time_passes, "looking for plugin registrar", ||
711             plugin::build::find_plugin_registrar(
712                 sess.diagnostic(), krate)));
713
714     let region_map = time(time_passes, "region resolution", ||
715                           middle::region::resolve_crate(sess, krate));
716
717     time(time_passes, "loop checking", ||
718          middle::check_loop::check_crate(sess, krate));
719
720     time(time_passes, "static item recursion checking", ||
721          middle::check_static_recursion::check_crate(sess, krate, &def_map, &ast_map));
722
723     ty::ctxt::create_and_enter(sess,
724                                arenas,
725                                def_map,
726                                named_region_map,
727                                ast_map,
728                                freevars,
729                                region_map,
730                                lang_items,
731                                stability::Index::new(krate),
732                                |tcx| {
733
734         // passes are timed inside typeck
735         typeck::check_crate(tcx, trait_map);
736
737         time(time_passes, "const checking", ||
738             middle::check_const::check_crate(tcx));
739
740         let (exported_items, public_items) =
741                 time(time_passes, "privacy checking", ||
742                     rustc_privacy::check_crate(tcx, &export_map, external_exports));
743
744         // Do not move this check past lint
745         time(time_passes, "stability index", ||
746             tcx.stability.borrow_mut().build(tcx, krate, &public_items));
747
748         time(time_passes, "intrinsic checking", ||
749             middle::intrinsicck::check_crate(tcx));
750
751         time(time_passes, "effect checking", ||
752             middle::effect::check_crate(tcx));
753
754         time(time_passes, "match checking", ||
755             middle::check_match::check_crate(tcx));
756
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
761                 // addressed
762                 NodeMap()
763             }
764             UnstableFeatures::Allow | UnstableFeatures::Cheat => {
765                 time(time_passes, "MIR dump", ||
766                      mir::mir_map::build_mir_for_crate(tcx))
767             }
768         };
769
770         time(time_passes, "liveness checking", ||
771             middle::liveness::check_crate(tcx));
772
773         time(time_passes, "borrow checking", ||
774             borrowck::check_crate(tcx));
775
776         time(time_passes, "rvalue checking", ||
777             middle::check_rvalues::check_crate(tcx, krate));
778
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();
785
786         let reachable_map =
787             time(time_passes, "reachability checking", ||
788                 reachable::find_reachable(tcx, &exported_items));
789
790         time(time_passes, "death checking", || {
791             middle::dead::check_crate(tcx,
792                                       &exported_items,
793                                       &reachable_map)
794         });
795
796         let ref lib_features_used =
797             time(time_passes, "stability checking", ||
798                 stability::check_unstable_api_usage(tcx));
799
800         time(time_passes, "unused lib feature checking", ||
801             stability::check_unused_or_stable_features(
802                 &tcx.sess, lib_features_used));
803
804         time(time_passes, "lint checking", ||
805             lint::check_crate(tcx, krate, &exported_items));
806
807         // The above three passes generate errors w/o aborting
808         tcx.sess.abort_if_errors();
809
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,
815             name: name,
816             glob_map: glob_map,
817         })
818     })
819 }
820
821 /// Run the translation phase to LLVM, after which the AST and analysis can
822 /// be discarded.
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();
828
829     time(time_passes, "resolving dependency formats", ||
830          dependency_format::calculate(&tcx.sess));
831
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))
835 }
836
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));
847
848         write::run_assembler(sess, outputs);
849
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();
853         }
854     } else {
855         time(sess.time_passes(), "LLVM passes", ||
856             write::run_passes(sess,
857                               trans,
858                               &sess.opts.output_types,
859                               outputs));
860     }
861
862     sess.abort_if_errors();
863 }
864
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,
872                            trans,
873                            outputs,
874                            &trans.link.crate_name));
875 }
876
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(" ", "\\ ")
881 }
882
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);
887         match *output_type {
888             OutputType::Exe => {
889                 for output in sess.crate_types.borrow().iter() {
890                     let p = link::filename_for_input(sess, *output, id,
891                                                      outputs);
892                     out_filenames.push(p);
893                 }
894             }
895             _ => { out_filenames.push(file); }
896         }
897     }
898
899     // Write out dependency rules to the dep-info file if requested
900     if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
901         return
902     }
903     let deps_filename = outputs.path(OutputType::DepInfo);
904
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()
909                                    .iter()
910                                    .filter(|fmap| fmap.is_real_file())
911                                    .filter(|fmap| !fmap.is_imported())
912                                    .map(|fmap| escape_dep_filename(&fmap.name))
913                                    .collect();
914         let mut file = try!(fs::File::create(&deps_filename));
915         for path in &out_filenames {
916             try!(write!(file,
917                         "{}: {}\n\n", path.display(), files.join(" ")));
918         }
919
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
923         for path in files {
924             try!(writeln!(file, "{}:", path));
925         }
926         Ok(())
927     })();
928
929     match result {
930         Ok(()) => {}
931         Err(e) => {
932             sess.fatal(&format!("error writing dependencies to `{}`: {}",
933                                deps_filename.display(), e));
934         }
935     }
936 }
937
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)
946                 }
947                 Some(ref n) if *n == "dylib" => {
948                     Some(config::CrateTypeDylib)
949                 }
950                 Some(ref n) if *n == "lib" => {
951                     Some(config::default_lib_output())
952                 }
953                 Some(ref n) if *n == "staticlib" => {
954                     Some(config::CrateTypeStaticlib)
955                 }
956                 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
957                 Some(_) => {
958                     session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
959                                      ast::CRATE_NODE_ID,
960                                      a.span,
961                                      "invalid `crate_type` \
962                                       value".to_string());
963                     None
964                 }
965                 _ => {
966                     session.span_err(a.span, "`crate_type` requires a value");
967                     session.note("for example: `#![crate_type=\"lib\"]`");
968                     None
969                 }
970             }
971         } else {
972             None
973         }
974     }).collect();
975
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)
980     }
981
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();
986     if base.is_empty() {
987         base.extend(attr_types);
988         if base.is_empty() {
989             base.push(link::default_output_for_target(session));
990         }
991         base.sort();
992         base.dedup();
993     }
994
995     base.into_iter().filter(|crate_type| {
996         let res = !link::invalid_output_for_target(session, *crate_type);
997
998         if !res {
999             session.warn(&format!("dropping unsupported crate type `{}` \
1000                                    for target `{}`",
1001                                  *crate_type, session.opts.target_triple));
1002         }
1003
1004         res
1005     }).collect()
1006 }
1007
1008 pub fn collect_crate_metadata(session: &Session,
1009                               _attrs: &[ast::Attribute]) -> Vec<String> {
1010     session.opts.cg.metadata.clone()
1011 }
1012
1013 pub fn build_output_filenames(input: &Input,
1014                               odir: &Option<PathBuf>,
1015                               ofile: &Option<PathBuf>,
1016                               attrs: &[ast::Attribute],
1017                               sess: &Session)
1018                            -> OutputFilenames {
1019     match *ofile {
1020         None => {
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()
1027             };
1028
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());
1033
1034             OutputFilenames {
1035                 out_directory: dirpath,
1036                 out_filestem: stem,
1037                 single_output_file: None,
1038                 extra: sess.opts.cg.extra_filename.clone(),
1039                 outputs: sess.opts.output_types.clone(),
1040             }
1041         }
1042
1043         Some(ref out_file) => {
1044             let unnamed_output_types = sess.opts.output_types.values()
1045                                            .filter(|a| a.is_none())
1046                                            .count();
1047             let ofile = if unnamed_output_types > 1 {
1048                 sess.warn("ignoring specified output filename because multiple \
1049                            outputs were requested");
1050                 None
1051             } else {
1052                 Some(out_file.clone())
1053             };
1054             if *odir != None {
1055                 sess.warn("ignoring --out-dir flag due to -o flag.");
1056             }
1057
1058             let cur_dir = Path::new("");
1059
1060             OutputFilenames {
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(),
1067             }
1068         }
1069     }
1070 }