1 use std::collections::BTreeSet;
3 use std::fmt::Write as _;
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;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_hir::def_id::DefId;
13 use rustc_index::vec::Idx;
14 use rustc_middle::mir::interpret::{
15 alloc_range, read_target_uint, AllocId, Allocation, ConstAllocation, ConstValue, GlobalAlloc,
18 use rustc_middle::mir::visit::Visitor;
19 use rustc_middle::mir::*;
20 use rustc_middle::ty::{self, TyCtxt};
21 use rustc_target::abi::Size;
23 const INDENT: &str = " ";
24 /// Alignment for lining up comments following MIR statements
25 pub(crate) const ALIGN: usize = 40;
27 /// An indication of where we are in the control flow graph. Used for printing
28 /// extra information in `dump_mir`
30 /// We have not started dumping the control flow graph, but we are about to.
33 /// We just finished dumping the control flow graph. This is right before EOF
36 /// We are about to start dumping the given basic block.
37 BeforeBlock(BasicBlock),
39 /// We are just about to dump the given statement or terminator.
40 BeforeLocation(Location),
42 /// We just dumped the given statement or terminator.
43 AfterLocation(Location),
45 /// We just dumped the terminator for a block but not the closing `}`.
46 AfterTerminator(BasicBlock),
49 /// If the session is properly configured, dumps a human-readable
50 /// representation of the mir into:
53 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
56 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
57 /// where `<filter>` takes the following forms:
59 /// - `all` -- dump MIR for all fns, all passes, all everything
60 /// - a filter defined by a set of substrings combined with `&` and `|`
61 /// (`&` has higher precedence). At least one of the `|`-separated groups
62 /// must match; an `|`-separated group matches if all of its `&`-separated
63 /// substrings are matched.
67 /// - `nll` == match if `nll` appears in the name
68 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
69 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
70 /// or `typeck` appears in the name.
71 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
72 /// or `typeck` and `bar` both appear in the name.
74 pub fn dump_mir<'tcx, F>(
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 Some(ref filters) = tcx.sess.opts.unstable_opts.dump_mir else {
95 // see notes on #41697 below
96 let node_path = ty::print::with_forced_impl_filename_line!(tcx.def_path_str(def_id));
97 filters.split('|').any(|or_filter| {
98 or_filter.split('&').all(|and_filter| {
99 let and_filter_trimmed = and_filter.trim();
100 and_filter_trimmed == "all"
101 || pass_name.contains(and_filter_trimmed)
102 || node_path.contains(and_filter_trimmed)
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>(
115 disambiguator: &dyn Display,
119 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
121 let _: io::Result<()> = try {
122 let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body)?;
123 // see notes on #41697 above
125 ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
126 write!(file, "// MIR for `{}", def_path)?;
127 match body.source.promoted {
128 None => write!(file, "`")?,
129 Some(promoted) => write!(file, "::{:?}`", promoted)?,
131 writeln!(file, " {} {}", disambiguator, pass_name)?;
132 if let Some(ref layout) = body.generator_layout() {
133 writeln!(file, "/* generator_layout = {:#?} */", layout)?;
136 extra_data(PassWhere::BeforeCFG, &mut file)?;
137 write_user_type_annotations(tcx, body, &mut file)?;
138 write_mir_fn(tcx, body, &mut extra_data, &mut file)?;
139 extra_data(PassWhere::AfterCFG, &mut file)?;
142 if tcx.sess.opts.unstable_opts.dump_mir_graphviz {
143 let _: io::Result<()> = try {
144 let mut file = create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, body)?;
145 write_mir_fn_graphviz(tcx, body, false, &mut file)?;
149 if let Some(spanview) = tcx.sess.opts.unstable_opts.dump_mir_spanview {
150 let _: io::Result<()> = try {
151 let file_basename = dump_file_basename(tcx, pass_num, pass_name, disambiguator, body);
152 let mut file = create_dump_file_with_basename(tcx, &file_basename, "html")?;
153 if body.source.def_id().is_local() {
154 write_mir_fn_spanview(tcx, body, spanview, &file_basename, &mut file)?;
160 /// Returns the file basename portion (without extension) of a filename path
161 /// where we should dump a MIR representation output files.
162 fn dump_file_basename<'tcx>(
166 disambiguator: &dyn Display,
169 let source = body.source;
170 let promotion_id = match source.promoted {
171 Some(id) => format!("-{:?}", id),
172 None => String::new(),
175 let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
179 format!(".{:03}-{:03}", body.phase.phase_index(), body.pass_count)
181 ".-------".to_string()
185 let crate_name = tcx.crate_name(source.def_id().krate);
186 let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
187 // All drop shims have the same DefId, so we have to add the type
188 // to get unique file names.
189 let shim_disambiguator = match source.instance {
190 ty::InstanceDef::DropGlue(_, Some(ty)) => {
191 // Unfortunately, pretty-printed typed are not very filename-friendly.
192 // We dome some filtering.
193 let mut s = ".".to_owned();
194 s.extend(ty.to_string().chars().filter_map(|c| match c {
196 ':' | '<' | '>' => Some('_'),
206 crate_name, item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator,
210 /// Returns the path to the filename where we should dump a given MIR.
211 /// Also used by other bits of code (e.g., NLL inference) that dump
212 /// graphviz data or other things.
213 fn dump_path(tcx: TyCtxt<'_>, basename: &str, extension: &str) -> PathBuf {
214 let mut file_path = PathBuf::new();
215 file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir));
217 let file_name = format!("{}.{}", basename, extension,);
219 file_path.push(&file_name);
224 /// Attempts to open the MIR dump file with the given name and extension.
225 fn create_dump_file_with_basename(
229 ) -> io::Result<io::BufWriter<fs::File>> {
230 let file_path = dump_path(tcx, file_basename, extension);
231 if let Some(parent) = file_path.parent() {
232 fs::create_dir_all(parent).map_err(|e| {
235 format!("IO error creating MIR dump directory: {:?}; {}", parent, e),
239 Ok(io::BufWriter::new(fs::File::create(&file_path).map_err(|e| {
240 io::Error::new(e.kind(), format!("IO error creating MIR dump file: {:?}; {}", file_path, e))
244 /// Attempts to open a file where we should dump a given MIR or other
245 /// bit of MIR-related data. Used by `mir-dump`, but also by other
246 /// bits of code (e.g., NLL inference) that dump graphviz data or
247 /// other things, and hence takes the extension as an argument.
248 pub fn create_dump_file<'tcx>(
253 disambiguator: &dyn Display,
255 ) -> io::Result<io::BufWriter<fs::File>> {
256 create_dump_file_with_basename(
258 &dump_file_basename(tcx, pass_num, pass_name, disambiguator, body),
263 /// Write out a human-readable textual representation for the given MIR.
264 pub fn write_mir_pretty<'tcx>(
266 single: Option<DefId>,
268 ) -> io::Result<()> {
269 writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
270 writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
272 let mut first = true;
273 for def_id in dump_mir_def_ids(tcx, single) {
277 // Put empty lines between all items
281 let render_body = |w: &mut dyn Write, body| -> io::Result<()> {
282 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
284 for body in tcx.promoted_mir(def_id) {
286 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
291 // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
292 if tcx.is_const_fn_raw(def_id) {
293 render_body(w, tcx.optimized_mir(def_id))?;
295 writeln!(w, "// MIR FOR CTFE")?;
296 // Do not use `render_body`, as that would render the promoteds again, but these
297 // are shared between mir_for_ctfe and optimized_mir
298 write_mir_fn(tcx, tcx.mir_for_ctfe(def_id), &mut |_, _| Ok(()), w)?;
301 tcx.instance_mir(ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)));
302 render_body(w, instance_mir)?;
308 /// Write out a human-readable textual representation for the given function.
309 pub fn write_mir_fn<'tcx, F>(
316 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
318 write_mir_intro(tcx, body, w)?;
319 for block in body.basic_blocks.indices() {
320 extra_data(PassWhere::BeforeBlock(block), w)?;
321 write_basic_block(tcx, block, body, extra_data, w)?;
322 if block.index() + 1 != body.basic_blocks.len() {
329 write_allocations(tcx, body, w)?;
334 /// Write out a human-readable textual representation for the given basic block.
335 pub fn write_basic_block<'tcx, F>(
343 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
345 let data = &body[block];
347 // Basic block label at the top.
348 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
349 writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
351 // List of statements in the middle.
352 let mut current_location = Location { block, statement_index: 0 };
353 for statement in &data.statements {
354 extra_data(PassWhere::BeforeLocation(current_location), w)?;
355 let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
360 if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
361 comment(tcx, statement.source_info, body.span),
365 write_extra(tcx, w, |visitor| {
366 visitor.visit_statement(statement, current_location);
369 extra_data(PassWhere::AfterLocation(current_location), w)?;
371 current_location.statement_index += 1;
374 // Terminator at the bottom.
375 extra_data(PassWhere::BeforeLocation(current_location), w)?;
376 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
381 if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
382 comment(tcx, data.terminator().source_info, body.span),
386 write_extra(tcx, w, |visitor| {
387 visitor.visit_terminator(data.terminator(), current_location);
390 extra_data(PassWhere::AfterLocation(current_location), w)?;
391 extra_data(PassWhere::AfterTerminator(block), w)?;
393 writeln!(w, "{}}}", INDENT)
396 /// After we print the main statement, we sometimes dump extra
397 /// information. There's often a lot of little things "nuzzled up" in
399 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
401 F: FnMut(&mut ExtraComments<'tcx>),
403 let mut extra_comments = ExtraComments { tcx, comments: vec![] };
404 visit_op(&mut extra_comments);
405 for comment in extra_comments.comments {
406 writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
411 struct ExtraComments<'tcx> {
413 comments: Vec<String>,
416 impl<'tcx> ExtraComments<'tcx> {
417 fn push(&mut self, lines: &str) {
418 for line in lines.split('\n') {
419 self.comments.push(line.to_string());
424 fn use_verbose<'tcx>(ty: Ty<'tcx>, fn_def: bool) -> bool {
426 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
428 ty::Tuple(g_args) if g_args.is_empty() => false,
429 ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
430 ty::Array(ty, _) => use_verbose(ty, fn_def),
431 ty::FnDef(..) => fn_def,
436 impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
437 fn visit_constant(&mut self, constant: &Constant<'tcx>, _location: Location) {
438 let Constant { span, user_ty, literal } = constant;
439 if use_verbose(literal.ty(), true) {
440 self.push("mir::Constant");
443 self.tcx.sess.source_map().span_to_embeddable_string(*span)
445 if let Some(user_ty) = user_ty {
446 self.push(&format!("+ user_ty: {:?}", user_ty));
449 // FIXME: this is a poor version of `pretty_print_const_value`.
450 let fmt_val = |val: &ConstValue<'tcx>| match val {
451 ConstValue::ZeroSized => format!("<ZST>"),
452 ConstValue::Scalar(s) => format!("Scalar({:?})", s),
453 ConstValue::Slice { .. } => format!("Slice(..)"),
454 ConstValue::ByRef { .. } => format!("ByRef(..)"),
457 let fmt_valtree = |valtree: &ty::ValTree<'tcx>| match valtree {
458 ty::ValTree::Leaf(leaf) => format!("ValTree::Leaf({:?})", leaf),
459 ty::ValTree::Branch(_) => format!("ValTree::Branch(..)"),
462 let val = match literal {
463 ConstantKind::Ty(ct) => match ct.kind() {
464 ty::ConstKind::Param(p) => format!("Param({})", p),
465 ty::ConstKind::Unevaluated(uv) => {
467 "Unevaluated({}, {:?})",
468 self.tcx.def_path_str(uv.def.did),
472 ty::ConstKind::Value(val) => format!("Value({})", fmt_valtree(&val)),
473 ty::ConstKind::Error(_) => "Error".to_string(),
474 // These variants shouldn't exist in the MIR.
475 ty::ConstKind::Placeholder(_)
476 | ty::ConstKind::Infer(_)
477 | ty::ConstKind::Expr(_)
478 | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", literal),
480 ConstantKind::Unevaluated(uv, _) => {
482 "Unevaluated({}, {:?}, {:?})",
483 self.tcx.def_path_str(uv.def.did),
488 // To keep the diffs small, we render this like we render `ty::Const::Value`.
490 // This changes once `ty::Const::Value` is represented using valtrees.
491 ConstantKind::Val(val, _) => format!("Value({})", fmt_val(&val)),
494 // This reflects what `Const` looked liked before `val` was renamed
495 // as `kind`. We print it like this to avoid having to update
496 // expected output in a lot of tests.
497 self.push(&format!("+ literal: Const {{ ty: {}, val: {} }}", literal.ty(), val));
501 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
502 self.super_rvalue(rvalue, location);
503 if let Rvalue::Aggregate(kind, _) = rvalue {
505 AggregateKind::Closure(def_id, substs) => {
506 self.push("closure");
507 self.push(&format!("+ def_id: {:?}", def_id));
508 self.push(&format!("+ substs: {:#?}", substs));
511 AggregateKind::Generator(def_id, substs, movability) => {
512 self.push("generator");
513 self.push(&format!("+ def_id: {:?}", def_id));
514 self.push(&format!("+ substs: {:#?}", substs));
515 self.push(&format!("+ movability: {:?}", movability));
518 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
520 self.push(&format!("+ user_ty: {:?}", user_ty));
529 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo, function_span: Span) -> String {
530 let location = if tcx.sess.opts.unstable_opts.mir_pretty_relative_line_numbers {
531 tcx.sess.source_map().span_to_relative_line_string(span, function_span)
533 tcx.sess.source_map().span_to_embeddable_string(span)
536 format!("scope {} at {}", scope.index(), location,)
539 /// Prints local variables in a scope tree.
543 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
547 ) -> io::Result<()> {
548 let indent = depth * INDENT.len();
550 // Local variable debuginfo.
551 for var_debug_info in &body.var_debug_info {
552 if var_debug_info.source_info.scope != parent {
553 // Not declared in this scope.
557 let indented_debug_info = format!(
558 "{0:1$}debug {2} => {3:?};",
559 INDENT, indent, var_debug_info.name, var_debug_info.value,
567 comment(tcx, var_debug_info.source_info, body.span),
571 // Local variable types.
572 for (local, local_decl) in body.local_decls.iter_enumerated() {
573 if (1..body.arg_count + 1).contains(&local.index()) {
574 // Skip over argument locals, they're printed in the signature.
578 if local_decl.source_info.scope != parent {
579 // Not declared in this scope.
583 let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };
585 let mut indented_decl =
586 format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
587 if let Some(user_ty) = &local_decl.user_ty {
588 for user_ty in user_ty.projections() {
589 write!(indented_decl, " as {:?}", user_ty).unwrap();
592 indented_decl.push(';');
594 let local_name = if local == RETURN_PLACE { " return place" } else { "" };
598 "{0:1$} //{2} in {3}",
602 comment(tcx, local_decl.source_info, body.span),
606 let Some(children) = scope_tree.get(&parent) else {
610 for &child in children {
611 let child_data = &body.source_scopes[child];
612 assert_eq!(child_data.parent_scope, Some(parent));
614 let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
618 if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
624 (String::new(), None)
627 let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
629 if let Some(span) = span {
635 tcx.sess.source_map().span_to_embeddable_string(span),
638 writeln!(w, "{}", indented_header)?;
641 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
642 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
648 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
649 /// local variables (both user-defined bindings and compiler temporaries).
650 pub fn write_mir_intro<'tcx>(
654 ) -> io::Result<()> {
655 write_mir_sig(tcx, body, w)?;
658 // construct a scope tree and write it out
659 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
660 for (index, scope_data) in body.source_scopes.iter().enumerate() {
661 if let Some(parent) = scope_data.parent_scope {
662 scope_tree.entry(parent).or_default().push(SourceScope::new(index));
664 // Only the argument scope has no parent, because it's the root.
665 assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
669 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
671 // Add an empty line before the first block is printed.
677 /// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
679 pub fn write_allocations<'tcx>(
683 ) -> io::Result<()> {
684 fn alloc_ids_from_alloc(
685 alloc: ConstAllocation<'_>,
686 ) -> impl DoubleEndedIterator<Item = AllocId> + '_ {
687 alloc.inner().provenance().ptrs().values().map(|id| *id)
690 fn alloc_ids_from_const_val(val: ConstValue<'_>) -> impl Iterator<Item = AllocId> + '_ {
692 ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => {
693 Either::Left(Either::Left(std::iter::once(ptr.provenance)))
695 ConstValue::Scalar(interpret::Scalar::Int { .. }) => {
696 Either::Left(Either::Right(std::iter::empty()))
698 ConstValue::ZeroSized => Either::Left(Either::Right(std::iter::empty())),
699 ConstValue::ByRef { alloc, .. } | ConstValue::Slice { data: alloc, .. } => {
700 Either::Right(alloc_ids_from_alloc(alloc))
704 struct CollectAllocIds(BTreeSet<AllocId>);
706 impl<'tcx> Visitor<'tcx> for CollectAllocIds {
707 fn visit_constant(&mut self, c: &Constant<'tcx>, _: Location) {
709 ConstantKind::Ty(_) | ConstantKind::Unevaluated(..) => {}
710 ConstantKind::Val(val, _) => {
711 self.0.extend(alloc_ids_from_const_val(val));
717 let mut visitor = CollectAllocIds(Default::default());
718 visitor.visit_body(body);
720 // `seen` contains all seen allocations, including the ones we have *not* printed yet.
721 // The protocol is to first `insert` into `seen`, and only if that returns `true`
722 // then push to `todo`.
723 let mut seen = visitor.0;
724 let mut todo: Vec<_> = seen.iter().copied().collect();
725 while let Some(id) = todo.pop() {
726 let mut write_allocation_track_relocs =
727 |w: &mut dyn Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
728 // `.rev()` because we are popping them from the back of the `todo` vector.
729 for id in alloc_ids_from_alloc(alloc).rev() {
734 write!(w, "{}", display_allocation(tcx, alloc.inner()))
736 write!(w, "\n{id:?}")?;
737 match tcx.try_get_global_alloc(id) {
738 // This can't really happen unless there are bugs, but it doesn't cost us anything to
739 // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
740 None => write!(w, " (deallocated)")?,
741 Some(GlobalAlloc::Function(inst)) => write!(w, " (fn: {inst})")?,
742 Some(GlobalAlloc::VTable(ty, Some(trait_ref))) => {
743 write!(w, " (vtable: impl {trait_ref} for {ty})")?
745 Some(GlobalAlloc::VTable(ty, None)) => {
746 write!(w, " (vtable: impl <auto trait> for {ty})")?
748 Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
749 match tcx.eval_static_initializer(did) {
751 write!(w, " (static: {}, ", tcx.def_path_str(did))?;
752 write_allocation_track_relocs(w, alloc)?;
756 " (static: {}, error during initializer evaluation)",
757 tcx.def_path_str(did)
761 Some(GlobalAlloc::Static(did)) => {
762 write!(w, " (extern static: {})", tcx.def_path_str(did))?
764 Some(GlobalAlloc::Memory(alloc)) => {
766 write_allocation_track_relocs(w, alloc)?
774 /// Dumps the size and metadata and content of an allocation to the given writer.
775 /// The expectation is that the caller first prints other relevant metadata, so the exact
776 /// format of this function is (*without* leading or trailing newline):
779 /// size: {}, align: {}) {
784 /// The byte format is similar to how hex editors print bytes. Each line starts with the address of
785 /// the start of the line, followed by all bytes in hex format (space separated).
786 /// If the allocation is small enough to fit into a single line, no start address is given.
787 /// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
788 /// characters or characters whose value is larger than 127) with a `.`
789 /// This also prints provenance adequately.
790 pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra>(
792 alloc: &'a Allocation<Prov, Extra>,
793 ) -> RenderAllocation<'a, 'tcx, Prov, Extra> {
794 RenderAllocation { tcx, alloc }
798 pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra> {
800 alloc: &'a Allocation<Prov, Extra>,
803 impl<'a, 'tcx, Prov: Provenance, Extra> std::fmt::Display
804 for RenderAllocation<'a, 'tcx, Prov, Extra>
806 fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
807 let RenderAllocation { tcx, alloc } = *self;
808 write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
809 if alloc.size() == Size::ZERO {
811 return write!(w, " {{}}");
813 // Write allocation bytes.
815 write_allocation_bytes(tcx, alloc, w, " ")?;
821 fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
822 for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
825 writeln!(w, " │ {}", ascii)
828 /// Number of bytes to print per allocation hex dump line.
829 const BYTES_PER_LINE: usize = 16;
831 /// Prints the line start address and returns the new line start address.
832 fn write_allocation_newline(
833 w: &mut dyn std::fmt::Write,
834 mut line_start: Size,
838 ) -> Result<Size, std::fmt::Error> {
839 write_allocation_endline(w, ascii)?;
840 line_start += Size::from_bytes(BYTES_PER_LINE);
841 write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
845 /// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
846 /// is only one line). Note that your prefix should contain a trailing space as the lines are
847 /// printed directly after it.
848 fn write_allocation_bytes<'tcx, Prov: Provenance, Extra>(
850 alloc: &Allocation<Prov, Extra>,
851 w: &mut dyn std::fmt::Write,
853 ) -> std::fmt::Result {
854 let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
855 // Number of chars needed to represent all line numbers.
856 let pos_width = hex_number_length(alloc.size().bytes());
859 write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
861 write!(w, "{}", prefix)?;
864 let mut i = Size::ZERO;
865 let mut line_start = Size::ZERO;
867 let ptr_size = tcx.data_layout.pointer_size;
869 let mut ascii = String::new();
871 let oversized_ptr = |target: &mut String, width| {
872 if target.len() > width {
873 write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
877 while i < alloc.size() {
878 // The line start already has a space. While we could remove that space from the line start
879 // printing and unconditionally print a space here, that would cause the single-line case
880 // to have a single space before it, which looks weird.
884 if let Some(prov) = alloc.provenance().get_ptr(i) {
885 // Memory with provenance must be defined
886 assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
887 let j = i.bytes_usize();
889 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
890 let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
891 let offset = Size::from_bytes(offset);
892 let provenance_width = |bytes| bytes * 3;
893 let ptr = Pointer::new(prov, offset);
894 let mut target = format!("{:?}", ptr);
895 if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
896 // This is too long, try to save some space.
897 target = format!("{:#?}", ptr);
899 if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
900 // This branch handles the situation where a provenance starts in the current line
901 // but ends in the next one.
902 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
903 let overflow = ptr_size - remainder;
904 let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
905 let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
906 ascii.push('╾'); // HEAVY LEFT AND LIGHT RIGHT
907 for _ in 1..remainder.bytes() {
908 ascii.push('─'); // LIGHT HORIZONTAL
910 if overflow_width > remainder_width && overflow_width >= target.len() {
911 // The case where the provenance fits into the part in the next line
912 write!(w, "╾{0:─^1$}", "", remainder_width)?;
914 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
916 write!(w, "{0:─^1$}╼", target, overflow_width)?;
918 oversized_ptr(&mut target, remainder_width);
919 write!(w, "╾{0:─^1$}", target, remainder_width)?;
921 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
922 write!(w, "{0:─^1$}╼", "", overflow_width)?;
925 for _ in 0..overflow.bytes() - 1 {
928 ascii.push('╼'); // LIGHT LEFT AND HEAVY RIGHT
932 // This branch handles a provenance that starts and ends in the current line.
933 let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
934 oversized_ptr(&mut target, provenance_width);
936 write!(w, "╾{0:─^1$}╼", target, provenance_width)?;
937 for _ in 0..ptr_size.bytes() - 2 {
943 } else if let Some(prov) = alloc.provenance().get(i, &tcx) {
944 // Memory with provenance must be defined
946 alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
948 ascii.push('━'); // HEAVY HORIZONTAL
949 // We have two characters to display this, which is obviously not enough.
950 // Format is similar to "oversized" above.
951 let j = i.bytes_usize();
952 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
953 write!(w, "╾{:02x}{:#?} (1 ptr byte)╼", c, prov)?;
954 i += Size::from_bytes(1);
957 .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
960 let j = i.bytes_usize();
962 // Checked definedness (and thus range) and provenance. This access also doesn't
963 // influence interpreter execution but is only for debugging.
964 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
965 write!(w, "{:02x}", c)?;
966 if c.is_ascii_control() || c >= 0x80 {
969 ascii.push(char::from(c));
971 i += Size::from_bytes(1);
975 i += Size::from_bytes(1);
977 // Print a new line header if the next line still has some bytes to print.
978 if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
979 line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
983 write_allocation_endline(w, &ascii)?;
988 fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
989 use rustc_hir::def::DefKind;
991 trace!("write_mir_sig: {:?}", body.source.instance);
992 let def_id = body.source.def_id();
993 let kind = tcx.def_kind(def_id);
994 let is_function = match kind {
995 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) => true,
996 _ => tcx.is_closure(def_id),
998 match (kind, body.source.promoted) {
999 (_, Some(i)) => write!(w, "{:?} in ", i)?,
1000 (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
1001 (DefKind::Static(hir::Mutability::Not), _) => write!(w, "static ")?,
1002 (DefKind::Static(hir::Mutability::Mut), _) => write!(w, "static mut ")?,
1003 (_, _) if is_function => write!(w, "fn ")?,
1004 (DefKind::AnonConst | DefKind::InlineConst, _) => {} // things like anon const, not an item
1005 _ => bug!("Unexpected def kind {:?}", kind),
1008 ty::print::with_forced_impl_filename_line! {
1009 // see notes on #41697 elsewhere
1010 write!(w, "{}", tcx.def_path_str(def_id))?
1013 if body.source.promoted.is_none() && is_function {
1016 // fn argument types.
1017 for (i, arg) in body.args_iter().enumerate() {
1021 write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
1024 write!(w, ") -> {}", body.return_ty())?;
1026 assert_eq!(body.arg_count, 0);
1027 write!(w, ": {} =", body.return_ty())?;
1030 if let Some(yield_ty) = body.yield_ty() {
1032 writeln!(w, "yields {}", yield_ty)?;
1036 // Next thing that gets printed is the opening {
1041 fn write_user_type_annotations(
1045 ) -> io::Result<()> {
1046 if !body.user_type_annotations.is_empty() {
1047 writeln!(w, "| User Type Annotations")?;
1049 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
1052 "| {:?}: user_ty: {:?}, span: {}, inferred_ty: {:?}",
1055 tcx.sess.source_map().span_to_embeddable_string(annotation.span),
1056 annotation.inferred_ty,
1059 if !body.user_type_annotations.is_empty() {
1065 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
1066 if let Some(i) = single {
1069 tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
1073 /// Calc converted u64 decimal into hex and return it's length in chars
1075 /// ```ignore (cannot-test-private-function)
1076 /// assert_eq!(1, hex_number_length(0));
1077 /// assert_eq!(1, hex_number_length(1));
1078 /// assert_eq!(2, hex_number_length(16));
1080 fn hex_number_length(x: u64) -> usize {