1 use super::graphviz::write_mir_fn_graphviz;
2 use crate::transform::MirSource;
3 use rustc::mir::visit::Visitor;
5 use rustc::ty::{self, TyCtxt};
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8 use rustc_index::vec::Idx;
10 use std::fmt::Write as _;
12 use std::io::{self, Write};
13 use std::path::{Path, PathBuf};
15 const INDENT: &str = " ";
16 /// Alignment for lining up comments following MIR statements
17 pub(crate) const ALIGN: usize = 40;
19 /// An indication of where we are in the control flow graph. Used for printing
20 /// extra information in `dump_mir`
22 /// We have not started dumping the control flow graph, but we are about to.
25 /// We just finished dumping the control flow graph. This is right before EOF
28 /// We are about to start dumping the given basic block.
29 BeforeBlock(BasicBlock),
31 /// We are just about to dump the given statement or terminator.
32 BeforeLocation(Location),
34 /// We just dumped the given statement or terminator.
35 AfterLocation(Location),
37 /// We just dumped the terminator for a block but not the closing `}`.
38 AfterTerminator(BasicBlock),
41 /// If the session is properly configured, dumps a human-readable
42 /// representation of the mir into:
45 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
48 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
49 /// where `<filter>` takes the following forms:
51 /// - `all` -- dump MIR for all fns, all passes, all everything
52 /// - a filter defined by a set of substrings combined with `&` and `|`
53 /// (`&` has higher precedence). At least one of the `|`-separated groups
54 /// must match; an `|`-separated group matches if all of its `&`-separated
55 /// substrings are matched.
59 /// - `nll` == match if `nll` appears in the name
60 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
61 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
62 /// or `typeck` appears in the name.
63 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
64 /// or `typeck` and `bar` both appear in the name.
65 pub fn dump_mir<'tcx, F>(
67 pass_num: Option<&dyn Display>,
69 disambiguator: &dyn Display,
70 source: MirSource<'tcx>,
74 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
76 if !dump_enabled(tcx, pass_name, source) {
80 let node_path = ty::print::with_forced_impl_filename_line(|| {
81 // see notes on #41697 below
82 tcx.def_path_str(source.def_id())
84 dump_matched_mir_node(
96 pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, source: MirSource<'tcx>) -> bool {
97 let filters = match tcx.sess.opts.debugging_opts.dump_mir {
99 Some(ref filters) => filters,
101 let node_path = ty::print::with_forced_impl_filename_line(|| {
102 // see notes on #41697 below
103 tcx.def_path_str(source.def_id())
105 filters.split('|').any(|or_filter| {
106 or_filter.split('&').all(|and_filter| {
107 and_filter == "all" || pass_name.contains(and_filter) || node_path.contains(and_filter)
112 // #41697 -- we use `with_forced_impl_filename_line()` because
113 // `def_path_str()` would otherwise trigger `type_of`, and this can
114 // run while we are already attempting to evaluate `type_of`.
116 fn dump_matched_mir_node<'tcx, F>(
118 pass_num: Option<&dyn Display>,
121 disambiguator: &dyn Display,
122 source: MirSource<'tcx>,
126 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
128 let _: io::Result<()> = try {
129 let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, source)?;
130 writeln!(file, "// MIR for `{}`", node_path)?;
131 writeln!(file, "// source = {:?}", source)?;
132 writeln!(file, "// pass_name = {}", pass_name)?;
133 writeln!(file, "// disambiguator = {}", disambiguator)?;
134 if let Some(ref layout) = body.generator_layout {
135 writeln!(file, "// generator_layout = {:?}", layout)?;
138 extra_data(PassWhere::BeforeCFG, &mut file)?;
139 write_user_type_annotations(body, &mut file)?;
140 write_mir_fn(tcx, source, body, &mut extra_data, &mut file)?;
141 extra_data(PassWhere::AfterCFG, &mut file)?;
144 if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
145 let _: io::Result<()> = try {
147 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?;
148 write_mir_fn_graphviz(tcx, source.def_id(), body, false, &mut file)?;
153 /// Returns the path to the filename where we should dump a given MIR.
154 /// Also used by other bits of code (e.g., NLL inference) that dump
155 /// graphviz data or other things.
159 pass_num: Option<&dyn Display>,
161 disambiguator: &dyn Display,
162 source: MirSource<'tcx>,
164 let promotion_id = match source.promoted {
165 Some(id) => format!("-{:?}", id),
166 None => String::new(),
169 let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
173 None => ".-------".to_string(),
174 Some(pass_num) => format!(".{}", pass_num),
178 let mut file_path = PathBuf::new();
179 file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
181 let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
182 // All drop shims have the same DefId, so we have to add the type
183 // to get unique file names.
184 let shim_disambiguator = match source.instance {
185 ty::InstanceDef::DropGlue(_, Some(ty)) => {
186 // Unfortunately, pretty-printed typed are not very filename-friendly.
187 // We dome some filtering.
188 let mut s = ".".to_owned();
189 s.extend(ty.to_string().chars().filter_map(|c| match c {
191 ':' | '<' | '>' => Some('_'),
199 let file_name = format!(
200 "rustc.{}{}{}{}.{}.{}.{}",
201 item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator, extension,
204 file_path.push(&file_name);
209 /// Attempts to open a file where we should dump a given MIR or other
210 /// bit of MIR-related data. Used by `mir-dump`, but also by other
211 /// bits of code (e.g., NLL inference) that dump graphviz data or
212 /// other things, and hence takes the extension as an argument.
213 pub(crate) fn create_dump_file(
216 pass_num: Option<&dyn Display>,
218 disambiguator: &dyn Display,
219 source: MirSource<'tcx>,
220 ) -> io::Result<io::BufWriter<fs::File>> {
221 let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, source);
222 if let Some(parent) = file_path.parent() {
223 fs::create_dir_all(parent)?;
225 Ok(io::BufWriter::new(fs::File::create(&file_path)?))
228 /// Write out a human-readable textual representation for the given MIR.
229 pub fn write_mir_pretty<'tcx>(
231 single: Option<DefId>,
233 ) -> io::Result<()> {
234 writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
235 writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
237 let mut first = true;
238 for def_id in dump_mir_def_ids(tcx, single) {
239 let body = &tcx.optimized_mir(def_id);
244 // Put empty lines between all items
248 write_mir_fn(tcx, MirSource::item(def_id), body, &mut |_, _| Ok(()), w)?;
250 for (i, body) in tcx.promoted_mir(def_id).iter_enumerated() {
252 let src = MirSource { instance: ty::InstanceDef::Item(def_id), promoted: Some(i) };
253 write_mir_fn(tcx, src, body, &mut |_, _| Ok(()), w)?;
259 pub fn write_mir_fn<'tcx, F>(
261 src: MirSource<'tcx>,
267 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
269 write_mir_intro(tcx, src, body, w)?;
270 for block in body.basic_blocks().indices() {
271 extra_data(PassWhere::BeforeBlock(block), w)?;
272 write_basic_block(tcx, block, body, extra_data, w)?;
273 if block.index() + 1 != body.basic_blocks().len() {
282 /// Write out a human-readable textual representation for the given basic block.
283 pub fn write_basic_block<'tcx, F>(
291 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
293 let data = &body[block];
295 // Basic block label at the top.
296 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
297 writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
299 // List of statements in the middle.
300 let mut current_location = Location { block: block, statement_index: 0 };
301 for statement in &data.statements {
302 extra_data(PassWhere::BeforeLocation(current_location), w)?;
303 let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
309 comment(tcx, statement.source_info),
313 write_extra(tcx, w, |visitor| {
314 visitor.visit_statement(statement, current_location);
317 extra_data(PassWhere::AfterLocation(current_location), w)?;
319 current_location.statement_index += 1;
322 // Terminator at the bottom.
323 extra_data(PassWhere::BeforeLocation(current_location), w)?;
324 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
330 comment(tcx, data.terminator().source_info),
334 write_extra(tcx, w, |visitor| {
335 visitor.visit_terminator(data.terminator(), current_location);
338 extra_data(PassWhere::AfterLocation(current_location), w)?;
339 extra_data(PassWhere::AfterTerminator(block), w)?;
341 writeln!(w, "{}}}", INDENT)
344 /// After we print the main statement, we sometimes dump extra
345 /// information. There's often a lot of little things "nuzzled up" in
347 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
349 F: FnMut(&mut ExtraComments<'tcx>),
351 let mut extra_comments = ExtraComments { _tcx: tcx, comments: vec![] };
352 visit_op(&mut extra_comments);
353 for comment in extra_comments.comments {
354 writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
359 struct ExtraComments<'tcx> {
360 _tcx: TyCtxt<'tcx>, // don't need it now, but bet we will soon
361 comments: Vec<String>,
364 impl ExtraComments<'tcx> {
365 fn push(&mut self, lines: &str) {
366 for line in lines.split('\n') {
367 self.comments.push(line.to_string());
372 impl Visitor<'tcx> for ExtraComments<'tcx> {
373 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
374 self.super_constant(constant, location);
375 let Constant { span, user_ty, literal } = constant;
376 self.push("mir::Constant");
377 self.push(&format!("+ span: {:?}", span));
378 if let Some(user_ty) = user_ty {
379 self.push(&format!("+ user_ty: {:?}", user_ty));
381 self.push(&format!("+ literal: {:?}", literal));
384 fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
385 self.super_const(constant);
386 let ty::Const { ty, val, .. } = constant;
387 self.push("ty::Const");
388 self.push(&format!("+ ty: {:?}", ty));
389 self.push(&format!("+ val: {:?}", val));
392 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
393 self.super_rvalue(rvalue, location);
395 Rvalue::Aggregate(kind, _) => match **kind {
396 AggregateKind::Closure(def_id, substs) => {
397 self.push("closure");
398 self.push(&format!("+ def_id: {:?}", def_id));
399 self.push(&format!("+ substs: {:#?}", substs));
402 AggregateKind::Generator(def_id, substs, movability) => {
403 self.push("generator");
404 self.push(&format!("+ def_id: {:?}", def_id));
405 self.push(&format!("+ substs: {:#?}", substs));
406 self.push(&format!("+ movability: {:?}", movability));
409 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
411 self.push(&format!("+ user_ty: {:?}", user_ty));
422 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
423 format!("scope {} at {}", scope.index(), tcx.sess.source_map().span_to_string(span))
426 /// Prints local variables in a scope tree.
430 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
434 ) -> io::Result<()> {
435 let indent = depth * INDENT.len();
437 // Local variable debuginfo.
438 for var_debug_info in &body.var_debug_info {
439 if var_debug_info.source_info.scope != parent {
440 // Not declared in this scope.
444 let indented_debug_info = format!(
445 "{0:1$}debug {2} => {3:?};",
446 INDENT, indent, var_debug_info.name, var_debug_info.place,
454 comment(tcx, var_debug_info.source_info),
458 // Local variable types (including the user's name in a comment).
459 for (local, local_decl) in body.local_decls.iter_enumerated() {
460 if (1..body.arg_count + 1).contains(&local.index()) {
461 // Skip over argument locals, they're printed in the signature.
465 if local_decl.source_info.scope != parent {
466 // Not declared in this scope.
470 let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };
472 let mut indented_decl =
473 format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
474 for user_ty in local_decl.user_ty.projections() {
475 write!(indented_decl, " as {:?}", user_ty).unwrap();
477 indented_decl.push_str(";");
480 if local == RETURN_PLACE { format!(" return place") } else { String::new() };
484 "{0:1$} //{2} in {3}",
488 comment(tcx, local_decl.source_info),
492 let children = match scope_tree.get(&parent) {
493 Some(childs) => childs,
494 None => return Ok(()),
497 for &child in children {
498 assert_eq!(body.source_scopes[child].parent_scope, Some(parent));
499 writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
500 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
501 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
507 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
508 /// local variables (both user-defined bindings and compiler temporaries).
509 pub fn write_mir_intro<'tcx>(
511 src: MirSource<'tcx>,
514 ) -> io::Result<()> {
515 write_mir_sig(tcx, src, body, w)?;
518 // construct a scope tree and write it out
519 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
520 for (index, scope_data) in body.source_scopes.iter().enumerate() {
521 if let Some(parent) = scope_data.parent_scope {
522 scope_tree.entry(parent).or_default().push(SourceScope::new(index));
524 // Only the argument scope has no parent, because it's the root.
525 assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
529 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
531 // Add an empty line before the first block is printed.
539 src: MirSource<'tcx>,
542 ) -> io::Result<()> {
543 use rustc_hir::def::DefKind;
545 trace!("write_mir_sig: {:?}", src.instance);
546 let kind = tcx.def_kind(src.def_id());
547 let is_function = match kind {
548 Some(DefKind::Fn) | Some(DefKind::Method) | Some(DefKind::Ctor(..)) => true,
549 _ => tcx.is_closure(src.def_id()),
551 match (kind, src.promoted) {
552 (_, Some(i)) => write!(w, "{:?} in ", i)?,
553 (Some(DefKind::Const), _) | (Some(DefKind::AssocConst), _) => write!(w, "const ")?,
554 (Some(DefKind::Static), _) => {
555 write!(w, "static {}", if tcx.is_mutable_static(src.def_id()) { "mut " } else { "" })?
557 (_, _) if is_function => write!(w, "fn ")?,
558 (None, _) => {} // things like anon const, not an item
559 _ => bug!("Unexpected def kind {:?}", kind),
562 ty::print::with_forced_impl_filename_line(|| {
563 // see notes on #41697 elsewhere
564 write!(w, " {}", tcx.def_path_str(src.def_id()))
567 if src.promoted.is_none() && is_function {
570 // fn argument types.
571 for (i, arg) in body.args_iter().enumerate() {
575 write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
578 write!(w, ") -> {}", body.return_ty())?;
580 assert_eq!(body.arg_count, 0);
581 write!(w, ": {} =", body.return_ty())?;
584 if let Some(yield_ty) = body.yield_ty {
586 writeln!(w, "yields {}", yield_ty)?;
590 // Next thing that gets printed is the opening {
595 fn write_user_type_annotations(body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
596 if !body.user_type_annotations.is_empty() {
597 writeln!(w, "| User Type Annotations")?;
599 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
600 writeln!(w, "| {:?}: {:?} at {:?}", index.index(), annotation.user_ty, annotation.span)?;
602 if !body.user_type_annotations.is_empty() {
608 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
609 if let Some(i) = single { vec![i] } else { tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect() }