]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/dump_mir.rs
43fb0acf2dd86c5f146c1d494f36dd8bfd1294e6
[rust.git] / src / librustc_mir / transform / dump_mir.rs
1 // Copyright 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 //! This pass just dumps MIR at a specified point.
12
13 use std::borrow::Cow;
14 use std::fmt;
15 use std::fs::File;
16 use std::io;
17
18 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc::session::config::{OutputFilenames, OutputType};
20 use rustc::ty::TyCtxt;
21 use rustc::mir::transform::{DefIdPass, Pass, PassHook, MirSource};
22 use util as mir_util;
23
24 pub struct Marker(pub &'static str);
25
26 impl DefIdPass for Marker {
27     fn name<'a>(&'a self) -> Cow<'a, str> {
28         Cow::Borrowed(self.0)
29     }
30
31     fn run_pass<'a, 'tcx>(&self, _: TyCtxt<'a, 'tcx, 'tcx>, _: DefId) {
32         // no-op
33     }
34 }
35
36 pub struct Disambiguator {
37     is_after: bool
38 }
39
40 impl fmt::Display for Disambiguator {
41     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
42         let title = if self.is_after { "after" } else { "before" };
43         write!(formatter, "{}", title)
44     }
45 }
46
47 pub struct DumpMir;
48
49 impl PassHook for DumpMir {
50     fn on_mir_pass<'a, 'tcx>(
51         &self,
52         tcx: TyCtxt<'a, 'tcx, 'tcx>,
53         pass: &Pass,
54         pass_num: usize,
55         is_after: bool)
56     {
57         // No dump filters enabled.
58         if tcx.sess.opts.debugging_opts.dump_mir.is_none() {
59             return;
60         }
61
62         for &def_id in tcx.mir_keys(LOCAL_CRATE).iter() {
63             let id = tcx.hir.as_local_node_id(def_id).unwrap();
64             let source = MirSource::from_node(tcx, id);
65             let mir = tcx.item_mir(def_id);
66             mir_util::dump_mir(
67                 tcx,
68                 pass_num,
69                 &*pass.name(),
70                 &Disambiguator { is_after },
71                 source,
72                 &mir
73             );
74         }
75     }
76 }
77
78 pub fn emit_mir<'a, 'tcx>(
79     tcx: TyCtxt<'a, 'tcx, 'tcx>,
80     outputs: &OutputFilenames)
81     -> io::Result<()>
82 {
83     let path = outputs.path(OutputType::Mir);
84     let mut f = File::create(&path)?;
85     mir_util::write_mir_pretty(tcx, None, &mut f)?;
86     Ok(())
87 }