1 // Copyright 2014 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::hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc::mir::transform::{MirSuite, MirPassIndex, MirSource};
15 use rustc::ty::TyCtxt;
16 use rustc::ty::item_path;
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc_data_structures::indexed_vec::{Idx};
19 use std::fmt::Display;
21 use std::io::{self, Write};
22 use std::path::{PathBuf, Path};
24 const INDENT: &'static str = " ";
25 /// Alignment for lining up comments following MIR statements
26 const ALIGN: usize = 40;
28 /// If the session is properly configured, dumps a human-readable
29 /// representation of the mir into:
32 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
35 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
36 /// where `<filter>` takes the following forms:
38 /// - `all` -- dump MIR for all fns, all passes, all everything
39 /// - `substring1&substring2,...` -- `&`-separated list of substrings
40 /// that can appear in the pass-name or the `item_path_str` for the given
41 /// node-id. If any one of the substrings match, the data is dumped out.
42 pub fn dump_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
43 pass_num: Option<(MirSuite, MirPassIndex)>,
45 disambiguator: &Display,
48 if !dump_enabled(tcx, pass_name, source) {
52 let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below
53 tcx.item_path_str(tcx.hir.local_def_id(source.item_id()))
55 dump_matched_mir_node(tcx, pass_num, pass_name, &node_path,
56 disambiguator, source, mir);
57 for (index, promoted_mir) in mir.promoted.iter_enumerated() {
58 let promoted_source = MirSource::Promoted(source.item_id(), index);
59 dump_matched_mir_node(tcx, pass_num, pass_name, &node_path, disambiguator,
60 promoted_source, promoted_mir);
64 pub fn dump_enabled<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
68 let filters = match tcx.sess.opts.debugging_opts.dump_mir {
70 Some(ref filters) => filters,
72 let node_id = source.item_id();
73 let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below
74 tcx.item_path_str(tcx.hir.local_def_id(node_id))
79 pass_name.contains(filter) ||
80 node_path.contains(filter)
84 // #41697 -- we use `with_forced_impl_filename_line()` because
85 // `item_path_str()` would otherwise trigger `type_of`, and this can
86 // run while we are already attempting to evaluate `type_of`.
88 fn dump_matched_mir_node<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
89 pass_num: Option<(MirSuite, MirPassIndex)>,
92 disambiguator: &Display,
95 let promotion_id = match source {
96 MirSource::Promoted(_, id) => format!("-{:?}", id),
100 let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
104 None => format!(".-------"),
105 Some((suite, pass_num)) => format!(".{:03}-{:03}", suite.0, pass_num.0),
109 let mut file_path = PathBuf::new();
110 if let Some(ref file_dir) = tcx.sess.opts.debugging_opts.dump_mir_dir {
111 let p = Path::new(file_dir);
114 let _ = fs::create_dir_all(&file_path);
115 let file_name = format!("rustc.node{}{}{}.{}.{}.mir",
116 source.item_id(), promotion_id, pass_num, pass_name, disambiguator);
117 file_path.push(&file_name);
118 let _ = fs::File::create(&file_path).and_then(|mut file| {
119 writeln!(file, "// MIR for `{}`", node_path)?;
120 writeln!(file, "// source = {:?}", source)?;
121 writeln!(file, "// pass_name = {}", pass_name)?;
122 writeln!(file, "// disambiguator = {}", disambiguator)?;
124 write_mir_fn(tcx, source, mir, &mut file)?;
129 /// Write out a human-readable textual representation for the given MIR.
130 pub fn write_mir_pretty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
131 single: Option<DefId>,
135 writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
136 writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
138 let mut first = true;
139 for def_id in dump_mir_def_ids(tcx, single) {
140 let mir = &tcx.optimized_mir(def_id);
145 // Put empty lines between all items
149 let id = tcx.hir.as_local_node_id(def_id).unwrap();
150 let src = MirSource::from_node(tcx, id);
151 write_mir_fn(tcx, src, mir, w)?;
153 for (i, mir) in mir.promoted.iter_enumerated() {
155 write_mir_fn(tcx, MirSource::Promoted(id, i), mir, w)?;
161 pub fn write_mir_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
166 write_mir_intro(tcx, src, mir, w)?;
167 for block in mir.basic_blocks().indices() {
168 write_basic_block(tcx, block, mir, w)?;
169 if block.index() + 1 != mir.basic_blocks().len() {
178 /// Write out a human-readable textual representation for the given basic block.
179 fn write_basic_block(tcx: TyCtxt,
184 let data = &mir[block];
186 // Basic block label at the top.
187 writeln!(w, "{}{:?}: {{", INDENT, block)?;
189 // List of statements in the middle.
190 let mut current_location = Location { block: block, statement_index: 0 };
191 for statement in &data.statements {
192 let indented_mir = format!("{0}{0}{1:?};", INDENT, statement);
193 writeln!(w, "{0:1$} // {2}",
196 comment(tcx, statement.source_info))?;
198 current_location.statement_index += 1;
201 // Terminator at the bottom.
202 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
203 writeln!(w, "{0:1$} // {2}",
206 comment(tcx, data.terminator().source_info))?;
208 writeln!(w, "{}}}", INDENT)
211 fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
212 format!("scope {} at {}", scope.index(), tcx.sess.codemap().span_to_string(span))
215 /// Prints user-defined variables in a scope tree.
217 /// Returns the total number of variables printed.
218 fn write_scope_tree(tcx: TyCtxt,
220 scope_tree: &FxHashMap<VisibilityScope, Vec<VisibilityScope>>,
222 parent: VisibilityScope,
225 let indent = depth * INDENT.len();
227 let children = match scope_tree.get(&parent) {
228 Some(childs) => childs,
229 None => return Ok(()),
232 for &child in children {
233 let data = &mir.visibility_scopes[child];
234 assert_eq!(data.parent_scope, Some(parent));
235 writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
237 // User variable types (including the user's name in a comment).
238 for local in mir.vars_iter() {
239 let var = &mir.local_decls[local];
240 let (name, source_info) = if var.source_info.scope == child {
241 (var.name.unwrap(), var.source_info)
243 // Not a variable or not declared in this scope.
247 let mut_str = if var.mutability == Mutability::Mut {
253 let indent = indent + INDENT.len();
254 let indented_var = format!("{0:1$}let {2}{3:?}: {4};",
260 writeln!(w, "{0:1$} // \"{2}\" in {3}",
264 comment(tcx, source_info))?;
267 write_scope_tree(tcx, mir, scope_tree, w, child, depth + 1)?;
269 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
275 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
276 /// local variables (both user-defined bindings and compiler temporaries).
277 fn write_mir_intro<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
282 write_mir_sig(tcx, src, mir, w)?;
285 // construct a scope tree and write it out
286 let mut scope_tree: FxHashMap<VisibilityScope, Vec<VisibilityScope>> = FxHashMap();
287 for (index, scope_data) in mir.visibility_scopes.iter().enumerate() {
288 if let Some(parent) = scope_data.parent_scope {
289 scope_tree.entry(parent)
291 .push(VisibilityScope::new(index));
293 // Only the argument scope has no parent, because it's the root.
294 assert_eq!(index, ARGUMENT_VISIBILITY_SCOPE.index());
298 // Print return pointer
299 let indented_retptr = format!("{}let mut {:?}: {};",
303 writeln!(w, "{0:1$} // return pointer",
307 write_scope_tree(tcx, mir, &scope_tree, w, ARGUMENT_VISIBILITY_SCOPE, 1)?;
309 write_temp_decls(mir, w)?;
311 // Add an empty line before the first block is printed.
317 fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut Write)
321 MirSource::Fn(_) => write!(w, "fn")?,
322 MirSource::Const(_) => write!(w, "const")?,
323 MirSource::Static(_, hir::MutImmutable) => write!(w, "static")?,
324 MirSource::Static(_, hir::MutMutable) => write!(w, "static mut")?,
325 MirSource::Promoted(_, i) => write!(w, "{:?} in", i)?
328 item_path::with_forced_impl_filename_line(|| { // see notes on #41697 elsewhere
329 write!(w, " {}", tcx.node_path_str(src.item_id()))
332 if let MirSource::Fn(_) = src {
335 // fn argument types.
336 for (i, arg) in mir.args_iter().enumerate() {
340 write!(w, "{:?}: {}", Lvalue::Local(arg), mir.local_decls[arg].ty)?;
343 write!(w, ") -> {}", mir.return_ty)
345 assert_eq!(mir.arg_count, 0);
346 write!(w, ": {} =", mir.return_ty)
350 fn write_temp_decls(mir: &Mir, w: &mut Write) -> io::Result<()> {
351 // Compiler-introduced temporary types.
352 for temp in mir.temps_iter() {
353 writeln!(w, "{}let mut {:?}: {};", INDENT, temp, mir.local_decls[temp].ty)?;
359 pub fn dump_mir_def_ids(tcx: TyCtxt, single: Option<DefId>) -> Vec<DefId> {
360 if let Some(i) = single {
363 tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect()