]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/pretty.rs
Add a query to get the `promoted`s for a `mir::Body`
[rust.git] / src / librustc_mir / util / pretty.rs
1 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
2 use rustc::mir::*;
3 use rustc::mir::visit::Visitor;
4 use rustc::ty::{self, TyCtxt};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::indexed_vec::Idx;
7 use std::fmt::Display;
8 use std::fmt::Write as _;
9 use std::fs;
10 use std::io::{self, Write};
11 use std::path::{Path, PathBuf};
12 use super::graphviz::write_mir_fn_graphviz;
13 use crate::transform::MirSource;
14
15 const INDENT: &str = "    ";
16 /// Alignment for lining up comments following MIR statements
17 pub(crate) const ALIGN: usize = 40;
18
19 /// An indication of where we are in the control flow graph. Used for printing
20 /// extra information in `dump_mir`
21 pub enum PassWhere {
22     /// We have not started dumping the control flow graph, but we are about to.
23     BeforeCFG,
24
25     /// We just finished dumping the control flow graph. This is right before EOF
26     AfterCFG,
27
28     /// We are about to start dumping the given basic block.
29     BeforeBlock(BasicBlock),
30
31     /// We are just about to dump the given statement or terminator.
32     BeforeLocation(Location),
33
34     /// We just dumped the given statement or terminator.
35     AfterLocation(Location),
36
37     /// We just dumped the terminator for a block but not the closing `}`.
38     AfterTerminator(BasicBlock),
39 }
40
41 /// If the session is properly configured, dumps a human-readable
42 /// representation of the mir into:
43 ///
44 /// ```text
45 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
46 /// ```
47 ///
48 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
49 /// where `<filter>` takes the following forms:
50 ///
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.
56 ///
57 /// Example:
58 ///
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>(
66     tcx: TyCtxt<'tcx>,
67     pass_num: Option<&dyn Display>,
68     pass_name: &str,
69     disambiguator: &dyn Display,
70     source: MirSource<'tcx>,
71     body: &Body<'tcx>,
72     extra_data: F,
73 ) where
74     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
75 {
76     if !dump_enabled(tcx, pass_name, source) {
77         return;
78     }
79
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())
83     });
84     dump_matched_mir_node(
85         tcx,
86         pass_num,
87         pass_name,
88         &node_path,
89         disambiguator,
90         source,
91         body,
92         extra_data,
93     );
94 }
95
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 {
98         None => return false,
99         Some(ref filters) => filters,
100     };
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())
104     });
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)
108         })
109     })
110 }
111
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`.
115
116 fn dump_matched_mir_node<'tcx, F>(
117     tcx: TyCtxt<'tcx>,
118     pass_num: Option<&dyn Display>,
119     pass_name: &str,
120     node_path: &str,
121     disambiguator: &dyn Display,
122     source: MirSource<'tcx>,
123     body: &Body<'tcx>,
124     mut extra_data: F,
125 ) where
126     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
127 {
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)?;
136         }
137         writeln!(file, "")?;
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)?;
142     };
143
144     if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
145         let _: io::Result<()> = try {
146             let mut file =
147                 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?;
148             write_mir_fn_graphviz(tcx, source.def_id(), body, &mut file)?;
149         };
150     }
151 }
152
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.
156 fn dump_path(
157     tcx: TyCtxt<'_>,
158     extension: &str,
159     pass_num: Option<&dyn Display>,
160     pass_name: &str,
161     disambiguator: &dyn Display,
162     source: MirSource<'tcx>,
163 ) -> PathBuf {
164     let promotion_id = match source.promoted {
165         Some(id) => format!("-{:?}", id),
166         None => String::new(),
167     };
168
169     let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
170         String::new()
171     } else {
172         match pass_num {
173             None => ".-------".to_string(),
174             Some(pass_num) => format!(".{}", pass_num),
175         }
176     };
177
178     let mut file_path = PathBuf::new();
179     file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
180
181     let item_name = tcx
182         .def_path(source.def_id())
183         .to_filename_friendly_no_crate();
184     // All drop shims have the same DefId, so we have to add the type
185     // to get unique file names.
186     let shim_disambiguator = match source.instance {
187         ty::InstanceDef::DropGlue(_, Some(ty)) => {
188             // Unfortunately, pretty-printed typed are not very filename-friendly.
189             // We dome some filtering.
190             let mut s = ".".to_owned();
191             s.extend(ty.to_string()
192                 .chars()
193                 .filter_map(|c| match c {
194                     ' ' => None,
195                     ':' | '<' | '>' => Some('_'),
196                     c => Some(c)
197                 }));
198             s
199         }
200         _ => String::new(),
201     };
202
203     let file_name = format!(
204         "rustc.{}{}{}{}.{}.{}.{}",
205         item_name,
206         shim_disambiguator,
207         promotion_id,
208         pass_num,
209         pass_name,
210         disambiguator,
211         extension,
212     );
213
214     file_path.push(&file_name);
215
216     file_path
217 }
218
219 /// Attempts to open a file where we should dump a given MIR or other
220 /// bit of MIR-related data. Used by `mir-dump`, but also by other
221 /// bits of code (e.g., NLL inference) that dump graphviz data or
222 /// other things, and hence takes the extension as an argument.
223 pub(crate) fn create_dump_file(
224     tcx: TyCtxt<'_>,
225     extension: &str,
226     pass_num: Option<&dyn Display>,
227     pass_name: &str,
228     disambiguator: &dyn Display,
229     source: MirSource<'tcx>,
230 ) -> io::Result<fs::File> {
231     let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, source);
232     if let Some(parent) = file_path.parent() {
233         fs::create_dir_all(parent)?;
234     }
235     fs::File::create(&file_path)
236 }
237
238 /// Write out a human-readable textual representation for the given MIR.
239 pub fn write_mir_pretty<'tcx>(
240     tcx: TyCtxt<'tcx>,
241     single: Option<DefId>,
242     w: &mut dyn Write,
243 ) -> io::Result<()> {
244     writeln!(
245         w,
246         "// WARNING: This output format is intended for human consumers only"
247     )?;
248     writeln!(
249         w,
250         "// and is subject to change without notice. Knock yourself out."
251     )?;
252
253     let mut first = true;
254     for def_id in dump_mir_def_ids(tcx, single) {
255         let body = &tcx.optimized_mir(def_id);
256
257         if first {
258             first = false;
259         } else {
260             // Put empty lines between all items
261             writeln!(w, "")?;
262         }
263
264         write_mir_fn(tcx, MirSource::item(def_id), body, &mut |_, _| Ok(()), w)?;
265
266         for (i, body) in tcx.promoted_mir(def_id).iter_enumerated() {
267             writeln!(w, "")?;
268             let src = MirSource {
269                 instance: ty::InstanceDef::Item(def_id),
270                 promoted: Some(i),
271             };
272             write_mir_fn(tcx, src, body, &mut |_, _| Ok(()), w)?;
273         }
274     }
275     Ok(())
276 }
277
278 pub fn write_mir_fn<'tcx, F>(
279     tcx: TyCtxt<'tcx>,
280     src: MirSource<'tcx>,
281     body: &Body<'tcx>,
282     extra_data: &mut F,
283     w: &mut dyn Write,
284 ) -> io::Result<()>
285 where
286     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
287 {
288     write_mir_intro(tcx, src, body, w)?;
289     for block in body.basic_blocks().indices() {
290         extra_data(PassWhere::BeforeBlock(block), w)?;
291         write_basic_block(tcx, block, body, extra_data, w)?;
292         if block.index() + 1 != body.basic_blocks().len() {
293             writeln!(w, "")?;
294         }
295     }
296
297     writeln!(w, "}}")?;
298     Ok(())
299 }
300
301 /// Write out a human-readable textual representation for the given basic block.
302 pub fn write_basic_block<'tcx, F>(
303     tcx: TyCtxt<'tcx>,
304     block: BasicBlock,
305     body: &Body<'tcx>,
306     extra_data: &mut F,
307     w: &mut dyn Write,
308 ) -> io::Result<()>
309 where
310     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
311 {
312     let data = &body[block];
313
314     // Basic block label at the top.
315     let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
316     writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
317
318     // List of statements in the middle.
319     let mut current_location = Location {
320         block: block,
321         statement_index: 0,
322     };
323     for statement in &data.statements {
324         extra_data(PassWhere::BeforeLocation(current_location), w)?;
325         let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
326         writeln!(
327             w,
328             "{:A$} // {:?}: {}",
329             indented_body,
330             current_location,
331             comment(tcx, statement.source_info),
332             A = ALIGN,
333         )?;
334
335         write_extra(tcx, w, |visitor| {
336             visitor.visit_statement(statement, current_location);
337         })?;
338
339         extra_data(PassWhere::AfterLocation(current_location), w)?;
340
341         current_location.statement_index += 1;
342     }
343
344     // Terminator at the bottom.
345     extra_data(PassWhere::BeforeLocation(current_location), w)?;
346     let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
347     writeln!(
348         w,
349         "{:A$} // {:?}: {}",
350         indented_terminator,
351         current_location,
352         comment(tcx, data.terminator().source_info),
353         A = ALIGN,
354     )?;
355
356     write_extra(tcx, w, |visitor| {
357         visitor.visit_terminator(data.terminator(), current_location);
358     })?;
359
360     extra_data(PassWhere::AfterLocation(current_location), w)?;
361     extra_data(PassWhere::AfterTerminator(block), w)?;
362
363     writeln!(w, "{}}}", INDENT)
364 }
365
366 /// After we print the main statement, we sometimes dump extra
367 /// information. There's often a lot of little things "nuzzled up" in
368 /// a statement.
369 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
370 where
371     F: FnMut(&mut ExtraComments<'tcx>),
372 {
373     let mut extra_comments = ExtraComments {
374         _tcx: tcx,
375         comments: vec![],
376     };
377     visit_op(&mut extra_comments);
378     for comment in extra_comments.comments {
379         writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
380     }
381     Ok(())
382 }
383
384 struct ExtraComments<'tcx> {
385     _tcx: TyCtxt<'tcx>, // don't need it now, but bet we will soon
386     comments: Vec<String>,
387 }
388
389 impl ExtraComments<'tcx> {
390     fn push(&mut self, lines: &str) {
391         for line in lines.split('\n') {
392             self.comments.push(line.to_string());
393         }
394     }
395 }
396
397 impl Visitor<'tcx> for ExtraComments<'tcx> {
398     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
399         self.super_constant(constant, location);
400         let Constant { span, ty, user_ty, literal } = constant;
401         self.push("mir::Constant");
402         self.push(&format!("+ span: {:?}", span));
403         self.push(&format!("+ ty: {:?}", ty));
404         if let Some(user_ty) = user_ty {
405             self.push(&format!("+ user_ty: {:?}", user_ty));
406         }
407         self.push(&format!("+ literal: {:?}", literal));
408     }
409
410     fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
411         self.super_const(constant);
412         let ty::Const { ty, val, .. } = constant;
413         self.push("ty::Const");
414         self.push(&format!("+ ty: {:?}", ty));
415         self.push(&format!("+ val: {:?}", val));
416     }
417
418     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
419         self.super_rvalue(rvalue, location);
420         match rvalue {
421             Rvalue::Aggregate(kind, _) => match **kind {
422                 AggregateKind::Closure(def_id, substs) => {
423                     self.push("closure");
424                     self.push(&format!("+ def_id: {:?}", def_id));
425                     self.push(&format!("+ substs: {:#?}", substs));
426                 }
427
428                 AggregateKind::Generator(def_id, substs, movability) => {
429                     self.push("generator");
430                     self.push(&format!("+ def_id: {:?}", def_id));
431                     self.push(&format!("+ substs: {:#?}", substs));
432                     self.push(&format!("+ movability: {:?}", movability));
433                 }
434
435                 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
436                     self.push("adt");
437                     self.push(&format!("+ user_ty: {:?}", user_ty));
438                 }
439
440                 _ => {}
441             },
442
443             _ => {}
444         }
445     }
446 }
447
448 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
449     format!(
450         "scope {} at {}",
451         scope.index(),
452         tcx.sess.source_map().span_to_string(span)
453     )
454 }
455
456 /// Prints local variables in a scope tree.
457 fn write_scope_tree(
458     tcx: TyCtxt<'_>,
459     body: &Body<'_>,
460     scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
461     w: &mut dyn Write,
462     parent: SourceScope,
463     depth: usize,
464 ) -> io::Result<()> {
465     let indent = depth * INDENT.len();
466
467     // Local variable types (including the user's name in a comment).
468     for (local, local_decl) in body.local_decls.iter_enumerated() {
469         if (1..body.arg_count+1).contains(&local.index()) {
470             // Skip over argument locals, they're printed in the signature.
471             continue;
472         }
473
474         if local_decl.source_info.scope != parent {
475             // Not declared in this scope.
476             continue;
477         }
478
479         let mut_str = if local_decl.mutability == Mutability::Mut {
480             "mut "
481         } else {
482             ""
483         };
484
485         let mut indented_decl = format!(
486             "{0:1$}let {2}{3:?}: {4:?}",
487             INDENT,
488             indent,
489             mut_str,
490             local,
491             local_decl.ty
492         );
493         for user_ty in local_decl.user_ty.projections() {
494             write!(indented_decl, " as {:?}", user_ty).unwrap();
495         }
496         indented_decl.push_str(";");
497
498         let local_name = if local == RETURN_PLACE {
499             format!(" return place")
500         } else if let Some(name) = local_decl.name {
501             format!(" \"{}\"", name)
502         } else {
503             String::new()
504         };
505
506         writeln!(
507             w,
508             "{0:1$} //{2} in {3}",
509             indented_decl,
510             ALIGN,
511             local_name,
512             comment(tcx, local_decl.source_info),
513         )?;
514     }
515
516     let children = match scope_tree.get(&parent) {
517         Some(childs) => childs,
518         None => return Ok(()),
519     };
520
521     for &child in children {
522         assert_eq!(body.source_scopes[child].parent_scope, Some(parent));
523         writeln!(w, "{0:1$}scope {2} {{", "", indent, child.index())?;
524         write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
525         writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
526     }
527
528     Ok(())
529 }
530
531 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
532 /// local variables (both user-defined bindings and compiler temporaries).
533 pub fn write_mir_intro<'tcx>(
534     tcx: TyCtxt<'tcx>,
535     src: MirSource<'tcx>,
536     body: &Body<'_>,
537     w: &mut dyn Write,
538 ) -> io::Result<()> {
539     write_mir_sig(tcx, src, body, w)?;
540     writeln!(w, "{{")?;
541
542     // construct a scope tree and write it out
543     let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
544     for (index, scope_data) in body.source_scopes.iter().enumerate() {
545         if let Some(parent) = scope_data.parent_scope {
546             scope_tree
547                 .entry(parent)
548                 .or_default()
549                 .push(SourceScope::new(index));
550         } else {
551             // Only the argument scope has no parent, because it's the root.
552             assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
553         }
554     }
555
556     write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
557
558     // Add an empty line before the first block is printed.
559     writeln!(w, "")?;
560
561     Ok(())
562 }
563
564 fn write_mir_sig(
565     tcx: TyCtxt<'_>,
566     src: MirSource<'tcx>,
567     body: &Body<'_>,
568     w: &mut dyn Write,
569 ) -> io::Result<()> {
570     use rustc::hir::def::DefKind;
571
572     trace!("write_mir_sig: {:?}", src.instance);
573     let kind = tcx.def_kind(src.def_id());
574     let is_function = match kind {
575         Some(DefKind::Fn)
576         | Some(DefKind::Method)
577         | Some(DefKind::Ctor(..)) => true,
578         _ => tcx.is_closure(src.def_id()),
579     };
580     match (kind, src.promoted) {
581         (_, Some(i)) => write!(w, "{:?} in ", i)?,
582         (Some(DefKind::Const), _)
583         | (Some(DefKind::AssocConst), _) => write!(w, "const ")?,
584         (Some(DefKind::Static), _) =>
585             write!(w, "static {}", if tcx.is_mutable_static(src.def_id()) { "mut " } else { "" })?,
586         (_, _) if is_function => write!(w, "fn ")?,
587         (None, _) => {}, // things like anon const, not an item
588         _ => bug!("Unexpected def kind {:?}", kind),
589     }
590
591     ty::print::with_forced_impl_filename_line(|| {
592         // see notes on #41697 elsewhere
593         write!(w, " {}", tcx.def_path_str(src.def_id()))
594     })?;
595
596     if src.promoted.is_none() && is_function {
597         write!(w, "(")?;
598
599         // fn argument types.
600         for (i, arg) in body.args_iter().enumerate() {
601             if i != 0 {
602                 write!(w, ", ")?;
603             }
604             write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
605         }
606
607         write!(w, ") -> {}", body.return_ty())?;
608     } else {
609         assert_eq!(body.arg_count, 0);
610         write!(w, ": {} =", body.return_ty())?;
611     }
612
613     if let Some(yield_ty) = body.yield_ty {
614         writeln!(w)?;
615         writeln!(w, "yields {}", yield_ty)?;
616     }
617
618     write!(w, " ")?;
619     // Next thing that gets printed is the opening {
620
621     Ok(())
622 }
623
624 fn write_user_type_annotations(body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
625     if !body.user_type_annotations.is_empty() {
626         writeln!(w, "| User Type Annotations")?;
627     }
628     for (index, annotation) in body.user_type_annotations.iter_enumerated() {
629         writeln!(w, "| {:?}: {:?} at {:?}", index.index(), annotation.user_ty, annotation.span)?;
630     }
631     if !body.user_type_annotations.is_empty() {
632         writeln!(w, "|")?;
633     }
634     Ok(())
635 }
636
637 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
638     if let Some(i) = single {
639         vec![i]
640     } else {
641         tcx.mir_keys(LOCAL_CRATE).iter().cloned().collect()
642     }
643 }