]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/util/pretty.rs
Rollup merge of #82119 - m-ou-se:typo, r=dtolnay
[rust.git] / compiler / rustc_mir / src / util / pretty.rs
1 use std::collections::BTreeSet;
2 use std::fmt::Write as _;
3 use std::fmt::{Debug, Display};
4 use std::fs;
5 use std::io::{self, Write};
6 use std::path::{Path, PathBuf};
7
8 use super::graphviz::write_mir_fn_graphviz;
9 use super::spanview::write_mir_fn_spanview;
10 use crate::transform::MirSource;
11 use either::Either;
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc_index::vec::Idx;
15 use rustc_middle::mir::interpret::{
16     read_target_uint, AllocId, Allocation, ConstValue, GlobalAlloc, Pointer,
17 };
18 use rustc_middle::mir::visit::Visitor;
19 use rustc_middle::mir::*;
20 use rustc_middle::ty::{self, TyCtxt, TyS, TypeFoldable, TypeVisitor};
21 use rustc_target::abi::Size;
22 use std::ops::ControlFlow;
23
24 const INDENT: &str = "    ";
25 /// Alignment for lining up comments following MIR statements
26 pub(crate) const ALIGN: usize = 40;
27
28 /// An indication of where we are in the control flow graph. Used for printing
29 /// extra information in `dump_mir`
30 pub enum PassWhere {
31     /// We have not started dumping the control flow graph, but we are about to.
32     BeforeCFG,
33
34     /// We just finished dumping the control flow graph. This is right before EOF
35     AfterCFG,
36
37     /// We are about to start dumping the given basic block.
38     BeforeBlock(BasicBlock),
39
40     /// We are just about to dump the given statement or terminator.
41     BeforeLocation(Location),
42
43     /// We just dumped the given statement or terminator.
44     AfterLocation(Location),
45
46     /// We just dumped the terminator for a block but not the closing `}`.
47     AfterTerminator(BasicBlock),
48 }
49
50 /// If the session is properly configured, dumps a human-readable
51 /// representation of the mir into:
52 ///
53 /// ```text
54 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
55 /// ```
56 ///
57 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
58 /// where `<filter>` takes the following forms:
59 ///
60 /// - `all` -- dump MIR for all fns, all passes, all everything
61 /// - a filter defined by a set of substrings combined with `&` and `|`
62 ///   (`&` has higher precedence). At least one of the `|`-separated groups
63 ///   must match; an `|`-separated group matches if all of its `&`-separated
64 ///   substrings are matched.
65 ///
66 /// Example:
67 ///
68 /// - `nll` == match if `nll` appears in the name
69 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
70 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
71 ///   or `typeck` appears in the name.
72 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
73 ///   or `typeck` and `bar` both appear in the name.
74 pub fn dump_mir<'tcx, F>(
75     tcx: TyCtxt<'tcx>,
76     pass_num: Option<&dyn Display>,
77     pass_name: &str,
78     disambiguator: &dyn Display,
79     body: &Body<'tcx>,
80     extra_data: F,
81 ) where
82     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
83 {
84     if !dump_enabled(tcx, pass_name, body.source.def_id()) {
85         return;
86     }
87
88     dump_matched_mir_node(tcx, pass_num, pass_name, disambiguator, body, extra_data);
89 }
90
91 pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, def_id: DefId) -> bool {
92     let filters = match tcx.sess.opts.debugging_opts.dump_mir {
93         None => return false,
94         Some(ref filters) => filters,
95     };
96     let node_path = ty::print::with_forced_impl_filename_line(|| {
97         // see notes on #41697 below
98         tcx.def_path_str(def_id)
99     });
100     filters.split('|').any(|or_filter| {
101         or_filter.split('&').all(|and_filter| {
102             and_filter == "all" || pass_name.contains(and_filter) || node_path.contains(and_filter)
103         })
104     })
105 }
106
107 // #41697 -- we use `with_forced_impl_filename_line()` because
108 // `def_path_str()` would otherwise trigger `type_of`, and this can
109 // run while we are already attempting to evaluate `type_of`.
110
111 fn dump_matched_mir_node<'tcx, F>(
112     tcx: TyCtxt<'tcx>,
113     pass_num: Option<&dyn Display>,
114     pass_name: &str,
115     disambiguator: &dyn Display,
116     body: &Body<'tcx>,
117     mut extra_data: F,
118 ) where
119     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
120 {
121     let _: io::Result<()> = try {
122         let mut file =
123             create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body.source)?;
124         let def_path = ty::print::with_forced_impl_filename_line(|| {
125             // see notes on #41697 above
126             tcx.def_path_str(body.source.def_id())
127         });
128         write!(file, "// MIR for `{}", def_path)?;
129         match body.source.promoted {
130             None => write!(file, "`")?,
131             Some(promoted) => write!(file, "::{:?}`", promoted)?,
132         }
133         writeln!(file, " {} {}", disambiguator, pass_name)?;
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(tcx, body, &mut file)?;
140         write_mir_fn(tcx, 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, body.source)?;
148             write_mir_fn_graphviz(tcx, body, false, &mut file)?;
149         };
150     }
151
152     if let Some(spanview) = tcx.sess.opts.debugging_opts.dump_mir_spanview {
153         let _: io::Result<()> = try {
154             let file_basename =
155                 dump_file_basename(tcx, pass_num, pass_name, disambiguator, body.source);
156             let mut file = create_dump_file_with_basename(tcx, &file_basename, "html")?;
157             if body.source.def_id().is_local() {
158                 write_mir_fn_spanview(tcx, body, spanview, &file_basename, &mut file)?;
159             }
160         };
161     }
162 }
163
164 /// Returns the file basename portion (without extension) of a filename path
165 /// where we should dump a MIR representation output files.
166 fn dump_file_basename(
167     tcx: TyCtxt<'_>,
168     pass_num: Option<&dyn Display>,
169     pass_name: &str,
170     disambiguator: &dyn Display,
171     source: MirSource<'tcx>,
172 ) -> String {
173     let promotion_id = match source.promoted {
174         Some(id) => format!("-{:?}", id),
175         None => String::new(),
176     };
177
178     let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
179         String::new()
180     } else {
181         match pass_num {
182             None => ".-------".to_string(),
183             Some(pass_num) => format!(".{}", pass_num),
184         }
185     };
186
187     let crate_name = tcx.crate_name(source.def_id().krate);
188     let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
189     // All drop shims have the same DefId, so we have to add the type
190     // to get unique file names.
191     let shim_disambiguator = match source.instance {
192         ty::InstanceDef::DropGlue(_, Some(ty)) => {
193             // Unfortunately, pretty-printed typed are not very filename-friendly.
194             // We dome some filtering.
195             let mut s = ".".to_owned();
196             s.extend(ty.to_string().chars().filter_map(|c| match c {
197                 ' ' => None,
198                 ':' | '<' | '>' => Some('_'),
199                 c => Some(c),
200             }));
201             s
202         }
203         _ => String::new(),
204     };
205
206     format!(
207         "{}.{}{}{}{}.{}.{}",
208         crate_name, item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator,
209     )
210 }
211
212 /// Returns the path to the filename where we should dump a given MIR.
213 /// Also used by other bits of code (e.g., NLL inference) that dump
214 /// graphviz data or other things.
215 fn dump_path(tcx: TyCtxt<'_>, basename: &str, extension: &str) -> PathBuf {
216     let mut file_path = PathBuf::new();
217     file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
218
219     let file_name = format!("{}.{}", basename, extension,);
220
221     file_path.push(&file_name);
222
223     file_path
224 }
225
226 /// Attempts to open the MIR dump file with the given name and extension.
227 fn create_dump_file_with_basename(
228     tcx: TyCtxt<'_>,
229     file_basename: &str,
230     extension: &str,
231 ) -> io::Result<io::BufWriter<fs::File>> {
232     let file_path = dump_path(tcx, file_basename, extension);
233     if let Some(parent) = file_path.parent() {
234         fs::create_dir_all(parent).map_err(|e| {
235             io::Error::new(
236                 e.kind(),
237                 format!("IO error creating MIR dump directory: {:?}; {}", parent, e),
238             )
239         })?;
240     }
241     Ok(io::BufWriter::new(fs::File::create(&file_path).map_err(|e| {
242         io::Error::new(e.kind(), format!("IO error creating MIR dump file: {:?}; {}", file_path, e))
243     })?))
244 }
245
246 /// Attempts to open a file where we should dump a given MIR or other
247 /// bit of MIR-related data. Used by `mir-dump`, but also by other
248 /// bits of code (e.g., NLL inference) that dump graphviz data or
249 /// other things, and hence takes the extension as an argument.
250 pub(crate) fn create_dump_file(
251     tcx: TyCtxt<'_>,
252     extension: &str,
253     pass_num: Option<&dyn Display>,
254     pass_name: &str,
255     disambiguator: &dyn Display,
256     source: MirSource<'tcx>,
257 ) -> io::Result<io::BufWriter<fs::File>> {
258     create_dump_file_with_basename(
259         tcx,
260         &dump_file_basename(tcx, pass_num, pass_name, disambiguator, source),
261         extension,
262     )
263 }
264
265 /// Write out a human-readable textual representation for the given MIR.
266 pub fn write_mir_pretty<'tcx>(
267     tcx: TyCtxt<'tcx>,
268     single: Option<DefId>,
269     w: &mut dyn Write,
270 ) -> io::Result<()> {
271     writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
272     writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
273
274     let mut first = true;
275     for def_id in dump_mir_def_ids(tcx, single) {
276         if first {
277             first = false;
278         } else {
279             // Put empty lines between all items
280             writeln!(w)?;
281         }
282
283         let render_body = |w: &mut dyn Write, body| -> io::Result<()> {
284             write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
285
286             for body in tcx.promoted_mir(def_id) {
287                 writeln!(w)?;
288                 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
289             }
290             Ok(())
291         };
292
293         // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
294         if tcx.is_const_fn_raw(def_id) {
295             render_body(w, tcx.optimized_mir(def_id))?;
296             writeln!(w)?;
297             writeln!(w, "// MIR FOR CTFE")?;
298             // Do not use `render_body`, as that would render the promoteds again, but these
299             // are shared between mir_for_ctfe and optimized_mir
300             write_mir_fn(tcx, tcx.mir_for_ctfe(def_id), &mut |_, _| Ok(()), w)?;
301         } else {
302             let instance_mir =
303                 tcx.instance_mir(ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)));
304             render_body(w, instance_mir)?;
305         }
306     }
307     Ok(())
308 }
309
310 /// Write out a human-readable textual representation for the given function.
311 pub fn write_mir_fn<'tcx, F>(
312     tcx: TyCtxt<'tcx>,
313     body: &Body<'tcx>,
314     extra_data: &mut F,
315     w: &mut dyn Write,
316 ) -> io::Result<()>
317 where
318     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
319 {
320     write_mir_intro(tcx, body, w)?;
321     for block in body.basic_blocks().indices() {
322         extra_data(PassWhere::BeforeBlock(block), w)?;
323         write_basic_block(tcx, block, body, extra_data, w)?;
324         if block.index() + 1 != body.basic_blocks().len() {
325             writeln!(w)?;
326         }
327     }
328
329     writeln!(w, "}}")?;
330
331     write_allocations(tcx, body, w)?;
332
333     Ok(())
334 }
335
336 /// Write out a human-readable textual representation for the given basic block.
337 pub fn write_basic_block<'tcx, F>(
338     tcx: TyCtxt<'tcx>,
339     block: BasicBlock,
340     body: &Body<'tcx>,
341     extra_data: &mut F,
342     w: &mut dyn Write,
343 ) -> io::Result<()>
344 where
345     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
346 {
347     let data = &body[block];
348
349     // Basic block label at the top.
350     let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
351     writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
352
353     // List of statements in the middle.
354     let mut current_location = Location { block, statement_index: 0 };
355     for statement in &data.statements {
356         extra_data(PassWhere::BeforeLocation(current_location), w)?;
357         let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
358         writeln!(
359             w,
360             "{:A$} // {}{}",
361             indented_body,
362             if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
363             comment(tcx, statement.source_info),
364             A = ALIGN,
365         )?;
366
367         write_extra(tcx, w, |visitor| {
368             visitor.visit_statement(statement, current_location);
369         })?;
370
371         extra_data(PassWhere::AfterLocation(current_location), w)?;
372
373         current_location.statement_index += 1;
374     }
375
376     // Terminator at the bottom.
377     extra_data(PassWhere::BeforeLocation(current_location), w)?;
378     let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
379     writeln!(
380         w,
381         "{:A$} // {}{}",
382         indented_terminator,
383         if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
384         comment(tcx, data.terminator().source_info),
385         A = ALIGN,
386     )?;
387
388     write_extra(tcx, w, |visitor| {
389         visitor.visit_terminator(data.terminator(), current_location);
390     })?;
391
392     extra_data(PassWhere::AfterLocation(current_location), w)?;
393     extra_data(PassWhere::AfterTerminator(block), w)?;
394
395     writeln!(w, "{}}}", INDENT)
396 }
397
398 /// After we print the main statement, we sometimes dump extra
399 /// information. There's often a lot of little things "nuzzled up" in
400 /// a statement.
401 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
402 where
403     F: FnMut(&mut ExtraComments<'tcx>),
404 {
405     let mut extra_comments = ExtraComments { tcx, comments: vec![] };
406     visit_op(&mut extra_comments);
407     for comment in extra_comments.comments {
408         writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
409     }
410     Ok(())
411 }
412
413 struct ExtraComments<'tcx> {
414     tcx: TyCtxt<'tcx>,
415     comments: Vec<String>,
416 }
417
418 impl ExtraComments<'tcx> {
419     fn push(&mut self, lines: &str) {
420         for line in lines.split('\n') {
421             self.comments.push(line.to_string());
422         }
423     }
424 }
425
426 fn use_verbose(ty: &&TyS<'tcx>) -> bool {
427     match ty.kind() {
428         ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
429         // Unit type
430         ty::Tuple(g_args) if g_args.is_empty() => false,
431         ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(&g_arg.expect_ty())),
432         ty::Array(ty, _) => use_verbose(ty),
433         ty::FnDef(..) => false,
434         _ => true,
435     }
436 }
437
438 impl Visitor<'tcx> for ExtraComments<'tcx> {
439     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
440         self.super_constant(constant, location);
441         let Constant { span, user_ty, literal } = constant;
442         match literal.ty.kind() {
443             ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char => {}
444             // Unit type
445             ty::Tuple(tys) if tys.is_empty() => {}
446             _ => {
447                 self.push("mir::Constant");
448                 self.push(&format!("+ span: {}", self.tcx.sess.source_map().span_to_string(*span)));
449                 if let Some(user_ty) = user_ty {
450                     self.push(&format!("+ user_ty: {:?}", user_ty));
451                 }
452                 self.push(&format!("+ literal: {:?}", literal));
453             }
454         }
455     }
456
457     fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
458         self.super_const(constant);
459         let ty::Const { ty, val, .. } = constant;
460         if use_verbose(ty) {
461             self.push("ty::Const");
462             self.push(&format!("+ ty: {:?}", ty));
463             self.push(&format!("+ val: {:?}", val));
464         }
465     }
466
467     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
468         self.super_rvalue(rvalue, location);
469         if let Rvalue::Aggregate(kind, _) = rvalue {
470             match **kind {
471                 AggregateKind::Closure(def_id, substs) => {
472                     self.push("closure");
473                     self.push(&format!("+ def_id: {:?}", def_id));
474                     self.push(&format!("+ substs: {:#?}", substs));
475                 }
476
477                 AggregateKind::Generator(def_id, substs, movability) => {
478                     self.push("generator");
479                     self.push(&format!("+ def_id: {:?}", def_id));
480                     self.push(&format!("+ substs: {:#?}", substs));
481                     self.push(&format!("+ movability: {:?}", movability));
482                 }
483
484                 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
485                     self.push("adt");
486                     self.push(&format!("+ user_ty: {:?}", user_ty));
487                 }
488
489                 _ => {}
490             }
491         }
492     }
493 }
494
495 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
496     format!("scope {} at {}", scope.index(), tcx.sess.source_map().span_to_string(span))
497 }
498
499 /// Prints local variables in a scope tree.
500 fn write_scope_tree(
501     tcx: TyCtxt<'_>,
502     body: &Body<'_>,
503     scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
504     w: &mut dyn Write,
505     parent: SourceScope,
506     depth: usize,
507 ) -> io::Result<()> {
508     let indent = depth * INDENT.len();
509
510     // Local variable debuginfo.
511     for var_debug_info in &body.var_debug_info {
512         if var_debug_info.source_info.scope != parent {
513             // Not declared in this scope.
514             continue;
515         }
516
517         let indented_debug_info = format!(
518             "{0:1$}debug {2} => {3:?};",
519             INDENT, indent, var_debug_info.name, var_debug_info.value,
520         );
521
522         writeln!(
523             w,
524             "{0:1$} // in {2}",
525             indented_debug_info,
526             ALIGN,
527             comment(tcx, var_debug_info.source_info),
528         )?;
529     }
530
531     // Local variable types.
532     for (local, local_decl) in body.local_decls.iter_enumerated() {
533         if (1..body.arg_count + 1).contains(&local.index()) {
534             // Skip over argument locals, they're printed in the signature.
535             continue;
536         }
537
538         if local_decl.source_info.scope != parent {
539             // Not declared in this scope.
540             continue;
541         }
542
543         let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };
544
545         let mut indented_decl =
546             format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
547         if let Some(user_ty) = &local_decl.user_ty {
548             for user_ty in user_ty.projections() {
549                 write!(indented_decl, " as {:?}", user_ty).unwrap();
550             }
551         }
552         indented_decl.push(';');
553
554         let local_name =
555             if local == RETURN_PLACE { " return place".to_string() } else { String::new() };
556
557         writeln!(
558             w,
559             "{0:1$} //{2} in {3}",
560             indented_decl,
561             ALIGN,
562             local_name,
563             comment(tcx, local_decl.source_info),
564         )?;
565     }
566
567     let children = match scope_tree.get(&parent) {
568         Some(children) => children,
569         None => return Ok(()),
570     };
571
572     for &child in children {
573         let child_data = &body.source_scopes[child];
574         assert_eq!(child_data.parent_scope, Some(parent));
575
576         let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
577             (
578                 format!(
579                     " (inlined {}{})",
580                     if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
581                     callee
582                 ),
583                 Some(callsite_span),
584             )
585         } else {
586             (String::new(), None)
587         };
588
589         let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
590
591         if let Some(span) = span {
592             writeln!(
593                 w,
594                 "{0:1$} // at {2}",
595                 indented_header,
596                 ALIGN,
597                 tcx.sess.source_map().span_to_string(span),
598             )?;
599         } else {
600             writeln!(w, "{}", indented_header)?;
601         }
602
603         write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
604         writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
605     }
606
607     Ok(())
608 }
609
610 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
611 /// local variables (both user-defined bindings and compiler temporaries).
612 pub fn write_mir_intro<'tcx>(
613     tcx: TyCtxt<'tcx>,
614     body: &Body<'_>,
615     w: &mut dyn Write,
616 ) -> io::Result<()> {
617     write_mir_sig(tcx, body, w)?;
618     writeln!(w, "{{")?;
619
620     // construct a scope tree and write it out
621     let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
622     for (index, scope_data) in body.source_scopes.iter().enumerate() {
623         if let Some(parent) = scope_data.parent_scope {
624             scope_tree.entry(parent).or_default().push(SourceScope::new(index));
625         } else {
626             // Only the argument scope has no parent, because it's the root.
627             assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
628         }
629     }
630
631     write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
632
633     // Add an empty line before the first block is printed.
634     writeln!(w)?;
635
636     Ok(())
637 }
638
639 /// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
640 /// allocations.
641 pub fn write_allocations<'tcx>(
642     tcx: TyCtxt<'tcx>,
643     body: &Body<'_>,
644     w: &mut dyn Write,
645 ) -> io::Result<()> {
646     fn alloc_ids_from_alloc(alloc: &Allocation) -> impl DoubleEndedIterator<Item = AllocId> + '_ {
647         alloc.relocations().values().map(|(_, id)| *id)
648     }
649     fn alloc_ids_from_const(val: ConstValue<'_>) -> impl Iterator<Item = AllocId> + '_ {
650         match val {
651             ConstValue::Scalar(interpret::Scalar::Ptr(ptr)) => {
652                 Either::Left(Either::Left(std::iter::once(ptr.alloc_id)))
653             }
654             ConstValue::Scalar(interpret::Scalar::Int { .. }) => {
655                 Either::Left(Either::Right(std::iter::empty()))
656             }
657             ConstValue::ByRef { alloc, .. } | ConstValue::Slice { data: alloc, .. } => {
658                 Either::Right(alloc_ids_from_alloc(alloc))
659             }
660         }
661     }
662     struct CollectAllocIds(BTreeSet<AllocId>);
663     impl<'tcx> TypeVisitor<'tcx> for CollectAllocIds {
664         fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
665             if let ty::ConstKind::Value(val) = c.val {
666                 self.0.extend(alloc_ids_from_const(val));
667             }
668             c.super_visit_with(self)
669         }
670     }
671     let mut visitor = CollectAllocIds(Default::default());
672     body.visit_with(&mut visitor);
673     // `seen` contains all seen allocations, including the ones we have *not* printed yet.
674     // The protocol is to first `insert` into `seen`, and only if that returns `true`
675     // then push to `todo`.
676     let mut seen = visitor.0;
677     let mut todo: Vec<_> = seen.iter().copied().collect();
678     while let Some(id) = todo.pop() {
679         let mut write_allocation_track_relocs =
680             |w: &mut dyn Write, alloc: &Allocation| -> io::Result<()> {
681                 // `.rev()` because we are popping them from the back of the `todo` vector.
682                 for id in alloc_ids_from_alloc(alloc).rev() {
683                     if seen.insert(id) {
684                         todo.push(id);
685                     }
686                 }
687                 write!(w, "{}", display_allocation(tcx, alloc))
688             };
689         write!(w, "\n{}", id)?;
690         match tcx.get_global_alloc(id) {
691             // This can't really happen unless there are bugs, but it doesn't cost us anything to
692             // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
693             None => write!(w, " (deallocated)")?,
694             Some(GlobalAlloc::Function(inst)) => write!(w, " (fn: {})", inst)?,
695             Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
696                 match tcx.eval_static_initializer(did) {
697                     Ok(alloc) => {
698                         write!(w, " (static: {}, ", tcx.def_path_str(did))?;
699                         write_allocation_track_relocs(w, alloc)?;
700                     }
701                     Err(_) => write!(
702                         w,
703                         " (static: {}, error during initializer evaluation)",
704                         tcx.def_path_str(did)
705                     )?,
706                 }
707             }
708             Some(GlobalAlloc::Static(did)) => {
709                 write!(w, " (extern static: {})", tcx.def_path_str(did))?
710             }
711             Some(GlobalAlloc::Memory(alloc)) => {
712                 write!(w, " (")?;
713                 write_allocation_track_relocs(w, alloc)?
714             }
715         }
716         writeln!(w)?;
717     }
718     Ok(())
719 }
720
721 /// Dumps the size and metadata and content of an allocation to the given writer.
722 /// The expectation is that the caller first prints other relevant metadata, so the exact
723 /// format of this function is (*without* leading or trailing newline):
724 ///
725 /// ```text
726 /// size: {}, align: {}) {
727 ///     <bytes>
728 /// }
729 /// ```
730 ///
731 /// The byte format is similar to how hex editors print bytes. Each line starts with the address of
732 /// the start of the line, followed by all bytes in hex format (space separated).
733 /// If the allocation is small enough to fit into a single line, no start address is given.
734 /// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
735 /// characters or characters whose value is larger than 127) with a `.`
736 /// This also prints relocations adequately.
737 pub fn display_allocation<Tag: Copy + Debug, Extra>(
738     tcx: TyCtxt<'tcx>,
739     alloc: &'a Allocation<Tag, Extra>,
740 ) -> RenderAllocation<'a, 'tcx, Tag, Extra> {
741     RenderAllocation { tcx, alloc }
742 }
743
744 #[doc(hidden)]
745 pub struct RenderAllocation<'a, 'tcx, Tag, Extra> {
746     tcx: TyCtxt<'tcx>,
747     alloc: &'a Allocation<Tag, Extra>,
748 }
749
750 impl<Tag: Copy + Debug, Extra> std::fmt::Display for RenderAllocation<'a, 'tcx, Tag, Extra> {
751     fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
752         let RenderAllocation { tcx, alloc } = *self;
753         write!(w, "size: {}, align: {})", alloc.size.bytes(), alloc.align.bytes())?;
754         if alloc.size == Size::ZERO {
755             // We are done.
756             return write!(w, " {{}}");
757         }
758         // Write allocation bytes.
759         writeln!(w, " {{")?;
760         write_allocation_bytes(tcx, alloc, w, "    ")?;
761         write!(w, "}}")?;
762         Ok(())
763     }
764 }
765
766 fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
767     for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
768         write!(w, "   ")?;
769     }
770     writeln!(w, " │ {}", ascii)
771 }
772
773 /// Number of bytes to print per allocation hex dump line.
774 const BYTES_PER_LINE: usize = 16;
775
776 /// Prints the line start address and returns the new line start address.
777 fn write_allocation_newline(
778     w: &mut dyn std::fmt::Write,
779     mut line_start: Size,
780     ascii: &str,
781     pos_width: usize,
782     prefix: &str,
783 ) -> Result<Size, std::fmt::Error> {
784     write_allocation_endline(w, ascii)?;
785     line_start += Size::from_bytes(BYTES_PER_LINE);
786     write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
787     Ok(line_start)
788 }
789
790 /// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
791 /// is only one line). Note that your prefix should contain a trailing space as the lines are
792 /// printed directly after it.
793 fn write_allocation_bytes<Tag: Copy + Debug, Extra>(
794     tcx: TyCtxt<'tcx>,
795     alloc: &Allocation<Tag, Extra>,
796     w: &mut dyn std::fmt::Write,
797     prefix: &str,
798 ) -> std::fmt::Result {
799     let num_lines = alloc.size.bytes_usize().saturating_sub(BYTES_PER_LINE);
800     // Number of chars needed to represent all line numbers.
801     let pos_width = format!("{:x}", alloc.size.bytes()).len();
802
803     if num_lines > 0 {
804         write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
805     } else {
806         write!(w, "{}", prefix)?;
807     }
808
809     let mut i = Size::ZERO;
810     let mut line_start = Size::ZERO;
811
812     let ptr_size = tcx.data_layout.pointer_size;
813
814     let mut ascii = String::new();
815
816     let oversized_ptr = |target: &mut String, width| {
817         if target.len() > width {
818             write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
819         }
820     };
821
822     while i < alloc.size {
823         // The line start already has a space. While we could remove that space from the line start
824         // printing and unconditionally print a space here, that would cause the single-line case
825         // to have a single space before it, which looks weird.
826         if i != line_start {
827             write!(w, " ")?;
828         }
829         if let Some(&(tag, target_id)) = alloc.relocations().get(&i) {
830             // Memory with a relocation must be defined
831             let j = i.bytes_usize();
832             let offset = alloc
833                 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
834             let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
835             let offset = Size::from_bytes(offset);
836             let relocation_width = |bytes| bytes * 3;
837             let ptr = Pointer::new_with_tag(target_id, offset, tag);
838             let mut target = format!("{:?}", ptr);
839             if target.len() > relocation_width(ptr_size.bytes_usize() - 1) {
840                 // This is too long, try to save some space.
841                 target = format!("{:#?}", ptr);
842             }
843             if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
844                 // This branch handles the situation where a relocation starts in the current line
845                 // but ends in the next one.
846                 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
847                 let overflow = ptr_size - remainder;
848                 let remainder_width = relocation_width(remainder.bytes_usize()) - 2;
849                 let overflow_width = relocation_width(overflow.bytes_usize() - 1) + 1;
850                 ascii.push('╾');
851                 for _ in 0..remainder.bytes() - 1 {
852                     ascii.push('─');
853                 }
854                 if overflow_width > remainder_width && overflow_width >= target.len() {
855                     // The case where the relocation fits into the part in the next line
856                     write!(w, "╾{0:─^1$}", "", remainder_width)?;
857                     line_start =
858                         write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
859                     ascii.clear();
860                     write!(w, "{0:─^1$}╼", target, overflow_width)?;
861                 } else {
862                     oversized_ptr(&mut target, remainder_width);
863                     write!(w, "╾{0:─^1$}", target, remainder_width)?;
864                     line_start =
865                         write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
866                     write!(w, "{0:─^1$}╼", "", overflow_width)?;
867                     ascii.clear();
868                 }
869                 for _ in 0..overflow.bytes() - 1 {
870                     ascii.push('─');
871                 }
872                 ascii.push('╼');
873                 i += ptr_size;
874                 continue;
875             } else {
876                 // This branch handles a relocation that starts and ends in the current line.
877                 let relocation_width = relocation_width(ptr_size.bytes_usize() - 1);
878                 oversized_ptr(&mut target, relocation_width);
879                 ascii.push('╾');
880                 write!(w, "╾{0:─^1$}╼", target, relocation_width)?;
881                 for _ in 0..ptr_size.bytes() - 2 {
882                     ascii.push('─');
883                 }
884                 ascii.push('╼');
885                 i += ptr_size;
886             }
887         } else if alloc.init_mask().is_range_initialized(i, i + Size::from_bytes(1)).is_ok() {
888             let j = i.bytes_usize();
889
890             // Checked definedness (and thus range) and relocations. This access also doesn't
891             // influence interpreter execution but is only for debugging.
892             let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
893             write!(w, "{:02x}", c)?;
894             if c.is_ascii_control() || c >= 0x80 {
895                 ascii.push('.');
896             } else {
897                 ascii.push(char::from(c));
898             }
899             i += Size::from_bytes(1);
900         } else {
901             write!(w, "__")?;
902             ascii.push('░');
903             i += Size::from_bytes(1);
904         }
905         // Print a new line header if the next line still has some bytes to print.
906         if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size {
907             line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
908             ascii.clear();
909         }
910     }
911     write_allocation_endline(w, &ascii)?;
912
913     Ok(())
914 }
915
916 fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
917     use rustc_hir::def::DefKind;
918
919     trace!("write_mir_sig: {:?}", body.source.instance);
920     let def_id = body.source.def_id();
921     let kind = tcx.def_kind(def_id);
922     let is_function = match kind {
923         DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) => true,
924         _ => tcx.is_closure(def_id),
925     };
926     match (kind, body.source.promoted) {
927         (_, Some(i)) => write!(w, "{:?} in ", i)?,
928         (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
929         (DefKind::Static, _) => {
930             write!(w, "static {}", if tcx.is_mutable_static(def_id) { "mut " } else { "" })?
931         }
932         (_, _) if is_function => write!(w, "fn ")?,
933         (DefKind::AnonConst, _) => {} // things like anon const, not an item
934         _ => bug!("Unexpected def kind {:?}", kind),
935     }
936
937     ty::print::with_forced_impl_filename_line(|| {
938         // see notes on #41697 elsewhere
939         write!(w, "{}", tcx.def_path_str(def_id))
940     })?;
941
942     if body.source.promoted.is_none() && is_function {
943         write!(w, "(")?;
944
945         // fn argument types.
946         for (i, arg) in body.args_iter().enumerate() {
947             if i != 0 {
948                 write!(w, ", ")?;
949             }
950             write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
951         }
952
953         write!(w, ") -> {}", body.return_ty())?;
954     } else {
955         assert_eq!(body.arg_count, 0);
956         write!(w, ": {} =", body.return_ty())?;
957     }
958
959     if let Some(yield_ty) = body.yield_ty {
960         writeln!(w)?;
961         writeln!(w, "yields {}", yield_ty)?;
962     }
963
964     write!(w, " ")?;
965     // Next thing that gets printed is the opening {
966
967     Ok(())
968 }
969
970 fn write_user_type_annotations(
971     tcx: TyCtxt<'_>,
972     body: &Body<'_>,
973     w: &mut dyn Write,
974 ) -> io::Result<()> {
975     if !body.user_type_annotations.is_empty() {
976         writeln!(w, "| User Type Annotations")?;
977     }
978     for (index, annotation) in body.user_type_annotations.iter_enumerated() {
979         writeln!(
980             w,
981             "| {:?}: {:?} at {}",
982             index.index(),
983             annotation.user_ty,
984             tcx.sess.source_map().span_to_string(annotation.span)
985         )?;
986     }
987     if !body.user_type_annotations.is_empty() {
988         writeln!(w, "|")?;
989     }
990     Ok(())
991 }
992
993 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
994     if let Some(i) = single {
995         vec![i]
996     } else {
997         tcx.mir_keys(LOCAL_CRATE).iter().map(|def_id| def_id.to_def_id()).collect()
998     }
999 }