1 use std::collections::BTreeSet;
2 use std::fmt::Write as _;
3 use std::fmt::{Debug, Display};
5 use std::io::{self, Write};
6 use std::path::{Path, PathBuf};
8 use super::graphviz::write_mir_fn_graphviz;
9 use super::spanview::write_mir_fn_spanview;
10 use crate::transform::MirSource;
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,
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;
24 const INDENT: &str = " ";
25 /// Alignment for lining up comments following MIR statements
26 pub(crate) const ALIGN: usize = 40;
28 /// An indication of where we are in the control flow graph. Used for printing
29 /// extra information in `dump_mir`
31 /// We have not started dumping the control flow graph, but we are about to.
34 /// We just finished dumping the control flow graph. This is right before EOF
37 /// We are about to start dumping the given basic block.
38 BeforeBlock(BasicBlock),
40 /// We are just about to dump the given statement or terminator.
41 BeforeLocation(Location),
43 /// We just dumped the given statement or terminator.
44 AfterLocation(Location),
46 /// We just dumped the terminator for a block but not the closing `}`.
47 AfterTerminator(BasicBlock),
50 /// If the session is properly configured, dumps a human-readable
51 /// representation of the mir into:
54 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
57 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
58 /// where `<filter>` takes the following forms:
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.
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>(
76 pass_num: Option<&dyn Display>,
78 disambiguator: &dyn Display,
82 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
84 if !dump_enabled(tcx, pass_name, body.source.def_id()) {
88 dump_matched_mir_node(tcx, pass_num, pass_name, disambiguator, body, extra_data);
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 {
94 Some(ref filters) => filters,
96 let node_path = ty::print::with_forced_impl_filename_line(|| {
97 // see notes on #41697 below
98 tcx.def_path_str(def_id)
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)
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`.
111 fn dump_matched_mir_node<'tcx, F>(
113 pass_num: Option<&dyn Display>,
115 disambiguator: &dyn Display,
119 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
121 let _: io::Result<()> = try {
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())
128 write!(file, "// MIR for `{}", def_path)?;
129 match body.source.promoted {
130 None => write!(file, "`")?,
131 Some(promoted) => write!(file, "::{:?}`", promoted)?,
133 writeln!(file, " {} {}", disambiguator, pass_name)?;
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(tcx, body, &mut file)?;
140 write_mir_fn(tcx, 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, body.source)?;
148 write_mir_fn_graphviz(tcx, body, false, &mut file)?;
152 if let Some(spanview) = tcx.sess.opts.debugging_opts.dump_mir_spanview {
153 let _: io::Result<()> = try {
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)?;
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(
168 pass_num: Option<&dyn Display>,
170 disambiguator: &dyn Display,
171 source: MirSource<'tcx>,
173 let promotion_id = match source.promoted {
174 Some(id) => format!("-{:?}", id),
175 None => String::new(),
178 let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
182 None => ".-------".to_string(),
183 Some(pass_num) => format!(".{}", pass_num),
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 {
198 ':' | '<' | '>' => Some('_'),
208 crate_name, item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator,
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));
219 let file_name = format!("{}.{}", basename, extension,);
221 file_path.push(&file_name);
226 /// Attempts to open the MIR dump file with the given name and extension.
227 fn create_dump_file_with_basename(
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| {
237 format!("IO error creating MIR dump directory: {:?}; {}", parent, e),
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))
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(
253 pass_num: Option<&dyn Display>,
255 disambiguator: &dyn Display,
256 source: MirSource<'tcx>,
257 ) -> io::Result<io::BufWriter<fs::File>> {
258 create_dump_file_with_basename(
260 &dump_file_basename(tcx, pass_num, pass_name, disambiguator, source),
265 /// Write out a human-readable textual representation for the given MIR.
266 pub fn write_mir_pretty<'tcx>(
268 single: Option<DefId>,
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.")?;
274 let mut first = true;
275 for def_id in dump_mir_def_ids(tcx, single) {
279 // Put empty lines between all items
283 let render_body = |w: &mut dyn Write, body| -> io::Result<()> {
284 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
286 for body in tcx.promoted_mir(def_id) {
288 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
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))?;
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)?;
303 tcx.instance_mir(ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)));
304 render_body(w, instance_mir)?;
310 /// Write out a human-readable textual representation for the given function.
311 pub fn write_mir_fn<'tcx, F>(
318 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
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() {
331 write_allocations(tcx, body, w)?;
336 /// Write out a human-readable textual representation for the given basic block.
337 pub fn write_basic_block<'tcx, F>(
345 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
347 let data = &body[block];
349 // Basic block label at the top.
350 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
351 writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
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);
362 if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
363 comment(tcx, statement.source_info),
367 write_extra(tcx, w, |visitor| {
368 visitor.visit_statement(statement, current_location);
371 extra_data(PassWhere::AfterLocation(current_location), w)?;
373 current_location.statement_index += 1;
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);
383 if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
384 comment(tcx, data.terminator().source_info),
388 write_extra(tcx, w, |visitor| {
389 visitor.visit_terminator(data.terminator(), current_location);
392 extra_data(PassWhere::AfterLocation(current_location), w)?;
393 extra_data(PassWhere::AfterTerminator(block), w)?;
395 writeln!(w, "{}}}", INDENT)
398 /// After we print the main statement, we sometimes dump extra
399 /// information. There's often a lot of little things "nuzzled up" in
401 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
403 F: FnMut(&mut ExtraComments<'tcx>),
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)?;
413 struct ExtraComments<'tcx> {
415 comments: Vec<String>,
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());
426 fn use_verbose(ty: &&TyS<'tcx>) -> bool {
428 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
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,
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 => {}
445 ty::Tuple(tys) if tys.is_empty() => {}
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));
452 self.push(&format!("+ literal: {:?}", literal));
457 fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
458 self.super_const(constant);
459 let ty::Const { ty, val, .. } = constant;
461 self.push("ty::Const");
462 self.push(&format!("+ ty: {:?}", ty));
463 self.push(&format!("+ val: {:?}", val));
467 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
468 self.super_rvalue(rvalue, location);
469 if let Rvalue::Aggregate(kind, _) = rvalue {
471 AggregateKind::Closure(def_id, substs) => {
472 self.push("closure");
473 self.push(&format!("+ def_id: {:?}", def_id));
474 self.push(&format!("+ substs: {:#?}", substs));
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));
484 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
486 self.push(&format!("+ user_ty: {:?}", user_ty));
495 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
496 format!("scope {} at {}", scope.index(), tcx.sess.source_map().span_to_string(span))
499 /// Prints local variables in a scope tree.
503 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
507 ) -> io::Result<()> {
508 let indent = depth * INDENT.len();
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.
517 let indented_debug_info = format!(
518 "{0:1$}debug {2} => {3:?};",
519 INDENT, indent, var_debug_info.name, var_debug_info.value,
527 comment(tcx, var_debug_info.source_info),
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.
538 if local_decl.source_info.scope != parent {
539 // Not declared in this scope.
543 let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };
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();
552 indented_decl.push(';');
555 if local == RETURN_PLACE { " return place".to_string() } else { String::new() };
559 "{0:1$} //{2} in {3}",
563 comment(tcx, local_decl.source_info),
567 let children = match scope_tree.get(&parent) {
568 Some(children) => children,
569 None => return Ok(()),
572 for &child in children {
573 let child_data = &body.source_scopes[child];
574 assert_eq!(child_data.parent_scope, Some(parent));
576 let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
580 if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
586 (String::new(), None)
589 let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
591 if let Some(span) = span {
597 tcx.sess.source_map().span_to_string(span),
600 writeln!(w, "{}", indented_header)?;
603 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
604 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
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>(
616 ) -> io::Result<()> {
617 write_mir_sig(tcx, body, w)?;
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));
626 // Only the argument scope has no parent, because it's the root.
627 assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
631 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
633 // Add an empty line before the first block is printed.
639 /// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
641 pub fn write_allocations<'tcx>(
645 ) -> io::Result<()> {
646 fn alloc_ids_from_alloc(alloc: &Allocation) -> impl DoubleEndedIterator<Item = AllocId> + '_ {
647 alloc.relocations().values().map(|(_, id)| *id)
649 fn alloc_ids_from_const(val: ConstValue<'_>) -> impl Iterator<Item = AllocId> + '_ {
651 ConstValue::Scalar(interpret::Scalar::Ptr(ptr)) => {
652 Either::Left(Either::Left(std::iter::once(ptr.alloc_id)))
654 ConstValue::Scalar(interpret::Scalar::Int { .. }) => {
655 Either::Left(Either::Right(std::iter::empty()))
657 ConstValue::ByRef { alloc, .. } | ConstValue::Slice { data: alloc, .. } => {
658 Either::Right(alloc_ids_from_alloc(alloc))
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));
668 c.super_visit_with(self)
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() {
687 write!(w, "{}", display_allocation(tcx, alloc))
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) {
698 write!(w, " (static: {}, ", tcx.def_path_str(did))?;
699 write_allocation_track_relocs(w, alloc)?;
703 " (static: {}, error during initializer evaluation)",
704 tcx.def_path_str(did)
708 Some(GlobalAlloc::Static(did)) => {
709 write!(w, " (extern static: {})", tcx.def_path_str(did))?
711 Some(GlobalAlloc::Memory(alloc)) => {
713 write_allocation_track_relocs(w, alloc)?
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):
726 /// size: {}, align: {}) {
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>(
739 alloc: &'a Allocation<Tag, Extra>,
740 ) -> RenderAllocation<'a, 'tcx, Tag, Extra> {
741 RenderAllocation { tcx, alloc }
745 pub struct RenderAllocation<'a, 'tcx, Tag, Extra> {
747 alloc: &'a Allocation<Tag, Extra>,
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 {
756 return write!(w, " {{}}");
758 // Write allocation bytes.
760 write_allocation_bytes(tcx, alloc, w, " ")?;
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()) {
770 writeln!(w, " │ {}", ascii)
773 /// Number of bytes to print per allocation hex dump line.
774 const BYTES_PER_LINE: usize = 16;
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,
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)?;
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>(
795 alloc: &Allocation<Tag, Extra>,
796 w: &mut dyn std::fmt::Write,
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();
804 write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
806 write!(w, "{}", prefix)?;
809 let mut i = Size::ZERO;
810 let mut line_start = Size::ZERO;
812 let ptr_size = tcx.data_layout.pointer_size;
814 let mut ascii = String::new();
816 let oversized_ptr = |target: &mut String, width| {
817 if target.len() > width {
818 write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
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.
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();
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);
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;
851 for _ in 0..remainder.bytes() - 1 {
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)?;
858 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
860 write!(w, "{0:─^1$}╼", target, overflow_width)?;
862 oversized_ptr(&mut target, remainder_width);
863 write!(w, "╾{0:─^1$}", target, remainder_width)?;
865 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
866 write!(w, "{0:─^1$}╼", "", overflow_width)?;
869 for _ in 0..overflow.bytes() - 1 {
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);
880 write!(w, "╾{0:─^1$}╼", target, relocation_width)?;
881 for _ in 0..ptr_size.bytes() - 2 {
887 } else if alloc.init_mask().is_range_initialized(i, i + Size::from_bytes(1)).is_ok() {
888 let j = i.bytes_usize();
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 {
897 ascii.push(char::from(c));
899 i += Size::from_bytes(1);
903 i += Size::from_bytes(1);
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)?;
911 write_allocation_endline(w, &ascii)?;
916 fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
917 use rustc_hir::def::DefKind;
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),
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 { "" })?
932 (_, _) if is_function => write!(w, "fn ")?,
933 (DefKind::AnonConst, _) => {} // things like anon const, not an item
934 _ => bug!("Unexpected def kind {:?}", kind),
937 ty::print::with_forced_impl_filename_line(|| {
938 // see notes on #41697 elsewhere
939 write!(w, "{}", tcx.def_path_str(def_id))
942 if body.source.promoted.is_none() && is_function {
945 // fn argument types.
946 for (i, arg) in body.args_iter().enumerate() {
950 write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
953 write!(w, ") -> {}", body.return_ty())?;
955 assert_eq!(body.arg_count, 0);
956 write!(w, ": {} =", body.return_ty())?;
959 if let Some(yield_ty) = body.yield_ty() {
961 writeln!(w, "yields {}", yield_ty)?;
965 // Next thing that gets printed is the opening {
970 fn write_user_type_annotations(
974 ) -> io::Result<()> {
975 if !body.user_type_annotations.is_empty() {
976 writeln!(w, "| User Type Annotations")?;
978 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
981 "| {:?}: {:?} at {}",
984 tcx.sess.source_map().span_to_string(annotation.span)
987 if !body.user_type_annotations.is_empty() {
993 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
994 if let Some(i) = single {
997 tcx.mir_keys(LOCAL_CRATE).iter().map(|def_id| def_id.to_def_id()).collect()