]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/util/pretty.rs
Rollup merge of #69607 - GuillaumeGomez:cleanup-e0376, r=Dylan-DPC
[rust.git] / src / librustc_mir / util / pretty.rs
1 use super::graphviz::write_mir_fn_graphviz;
2 use crate::transform::MirSource;
3 use rustc::mir::visit::Visitor;
4 use rustc::mir::*;
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;
9 use std::fmt::Display;
10 use std::fmt::Write as _;
11 use std::fs;
12 use std::io::{self, Write};
13 use std::path::{Path, PathBuf};
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, false, &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.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 {
190                 ' ' => None,
191                 ':' | '<' | '>' => Some('_'),
192                 c => Some(c),
193             }));
194             s
195         }
196         _ => String::new(),
197     };
198
199     let file_name = format!(
200         "rustc.{}{}{}{}.{}.{}.{}",
201         item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator, extension,
202     );
203
204     file_path.push(&file_name);
205
206     file_path
207 }
208
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(
214     tcx: TyCtxt<'_>,
215     extension: &str,
216     pass_num: Option<&dyn Display>,
217     pass_name: &str,
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)?;
224     }
225     Ok(io::BufWriter::new(fs::File::create(&file_path)?))
226 }
227
228 /// Write out a human-readable textual representation for the given MIR.
229 pub fn write_mir_pretty<'tcx>(
230     tcx: TyCtxt<'tcx>,
231     single: Option<DefId>,
232     w: &mut dyn Write,
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.")?;
236
237     let mut first = true;
238     for def_id in dump_mir_def_ids(tcx, single) {
239         let body = &tcx.optimized_mir(def_id);
240
241         if first {
242             first = false;
243         } else {
244             // Put empty lines between all items
245             writeln!(w, "")?;
246         }
247
248         write_mir_fn(tcx, MirSource::item(def_id), body, &mut |_, _| Ok(()), w)?;
249
250         for (i, body) in tcx.promoted_mir(def_id).iter_enumerated() {
251             writeln!(w, "")?;
252             let src = MirSource { instance: ty::InstanceDef::Item(def_id), promoted: Some(i) };
253             write_mir_fn(tcx, src, body, &mut |_, _| Ok(()), w)?;
254         }
255     }
256     Ok(())
257 }
258
259 pub fn write_mir_fn<'tcx, F>(
260     tcx: TyCtxt<'tcx>,
261     src: MirSource<'tcx>,
262     body: &Body<'tcx>,
263     extra_data: &mut F,
264     w: &mut dyn Write,
265 ) -> io::Result<()>
266 where
267     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
268 {
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() {
274             writeln!(w, "")?;
275         }
276     }
277
278     writeln!(w, "}}")?;
279     Ok(())
280 }
281
282 /// Write out a human-readable textual representation for the given basic block.
283 pub fn write_basic_block<'tcx, F>(
284     tcx: TyCtxt<'tcx>,
285     block: BasicBlock,
286     body: &Body<'tcx>,
287     extra_data: &mut F,
288     w: &mut dyn Write,
289 ) -> io::Result<()>
290 where
291     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
292 {
293     let data = &body[block];
294
295     // Basic block label at the top.
296     let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
297     writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
298
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);
304         writeln!(
305             w,
306             "{:A$} // {:?}: {}",
307             indented_body,
308             current_location,
309             comment(tcx, statement.source_info),
310             A = ALIGN,
311         )?;
312
313         write_extra(tcx, w, |visitor| {
314             visitor.visit_statement(statement, current_location);
315         })?;
316
317         extra_data(PassWhere::AfterLocation(current_location), w)?;
318
319         current_location.statement_index += 1;
320     }
321
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);
325     writeln!(
326         w,
327         "{:A$} // {:?}: {}",
328         indented_terminator,
329         current_location,
330         comment(tcx, data.terminator().source_info),
331         A = ALIGN,
332     )?;
333
334     write_extra(tcx, w, |visitor| {
335         visitor.visit_terminator(data.terminator(), current_location);
336     })?;
337
338     extra_data(PassWhere::AfterLocation(current_location), w)?;
339     extra_data(PassWhere::AfterTerminator(block), w)?;
340
341     writeln!(w, "{}}}", INDENT)
342 }
343
344 /// After we print the main statement, we sometimes dump extra
345 /// information. There's often a lot of little things "nuzzled up" in
346 /// a statement.
347 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
348 where
349     F: FnMut(&mut ExtraComments<'tcx>),
350 {
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)?;
355     }
356     Ok(())
357 }
358
359 struct ExtraComments<'tcx> {
360     _tcx: TyCtxt<'tcx>, // don't need it now, but bet we will soon
361     comments: Vec<String>,
362 }
363
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());
368         }
369     }
370 }
371
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));
380         }
381         self.push(&format!("+ literal: {:?}", literal));
382     }
383
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));
390     }
391
392     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
393         self.super_rvalue(rvalue, location);
394         match rvalue {
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));
400                 }
401
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));
407                 }
408
409                 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
410                     self.push("adt");
411                     self.push(&format!("+ user_ty: {:?}", user_ty));
412                 }
413
414                 _ => {}
415             },
416
417             _ => {}
418         }
419     }
420 }
421
422 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
423     format!("scope {} at {}", scope.index(), tcx.sess.source_map().span_to_string(span))
424 }
425
426 /// Prints local variables in a scope tree.
427 fn write_scope_tree(
428     tcx: TyCtxt<'_>,
429     body: &Body<'_>,
430     scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
431     w: &mut dyn Write,
432     parent: SourceScope,
433     depth: usize,
434 ) -> io::Result<()> {
435     let indent = depth * INDENT.len();
436
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.
441             continue;
442         }
443
444         let indented_debug_info = format!(
445             "{0:1$}debug {2} => {3:?};",
446             INDENT, indent, var_debug_info.name, var_debug_info.place,
447         );
448
449         writeln!(
450             w,
451             "{0:1$} // in {2}",
452             indented_debug_info,
453             ALIGN,
454             comment(tcx, var_debug_info.source_info),
455         )?;
456     }
457
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.
462             continue;
463         }
464
465         if local_decl.source_info.scope != parent {
466             // Not declared in this scope.
467             continue;
468         }
469
470         let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };
471
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();
476         }
477         indented_decl.push_str(";");
478
479         let local_name =
480             if local == RETURN_PLACE { " return place".to_string() } else { String::new() };
481
482         writeln!(
483             w,
484             "{0:1$} //{2} in {3}",
485             indented_decl,
486             ALIGN,
487             local_name,
488             comment(tcx, local_decl.source_info),
489         )?;
490     }
491
492     let children = match scope_tree.get(&parent) {
493         Some(childs) => childs,
494         None => return Ok(()),
495     };
496
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())?;
502     }
503
504     Ok(())
505 }
506
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>(
510     tcx: TyCtxt<'tcx>,
511     src: MirSource<'tcx>,
512     body: &Body<'_>,
513     w: &mut dyn Write,
514 ) -> io::Result<()> {
515     write_mir_sig(tcx, src, body, w)?;
516     writeln!(w, "{{")?;
517
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));
523         } else {
524             // Only the argument scope has no parent, because it's the root.
525             assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
526         }
527     }
528
529     write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
530
531     // Add an empty line before the first block is printed.
532     writeln!(w, "")?;
533
534     Ok(())
535 }
536
537 fn write_mir_sig(
538     tcx: TyCtxt<'_>,
539     src: MirSource<'tcx>,
540     body: &Body<'_>,
541     w: &mut dyn Write,
542 ) -> io::Result<()> {
543     use rustc_hir::def::DefKind;
544
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()),
550     };
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 { "" })?
556         }
557         (_, _) if is_function => write!(w, "fn ")?,
558         (None, _) => {} // things like anon const, not an item
559         _ => bug!("Unexpected def kind {:?}", kind),
560     }
561
562     ty::print::with_forced_impl_filename_line(|| {
563         // see notes on #41697 elsewhere
564         write!(w, " {}", tcx.def_path_str(src.def_id()))
565     })?;
566
567     if src.promoted.is_none() && is_function {
568         write!(w, "(")?;
569
570         // fn argument types.
571         for (i, arg) in body.args_iter().enumerate() {
572             if i != 0 {
573                 write!(w, ", ")?;
574             }
575             write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
576         }
577
578         write!(w, ") -> {}", body.return_ty())?;
579     } else {
580         assert_eq!(body.arg_count, 0);
581         write!(w, ": {} =", body.return_ty())?;
582     }
583
584     if let Some(yield_ty) = body.yield_ty {
585         writeln!(w)?;
586         writeln!(w, "yields {}", yield_ty)?;
587     }
588
589     write!(w, " ")?;
590     // Next thing that gets printed is the opening {
591
592     Ok(())
593 }
594
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")?;
598     }
599     for (index, annotation) in body.user_type_annotations.iter_enumerated() {
600         writeln!(w, "| {:?}: {:?} at {:?}", index.index(), annotation.user_ty, annotation.span)?;
601     }
602     if !body.user_type_annotations.is_empty() {
603         writeln!(w, "|")?;
604     }
605     Ok(())
606 }
607
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() }
610 }