1use std::collections::BTreeSet;
2use std::fmt::{Display, Write as _};
3use std::path::{Path, PathBuf};
4use std::{fs, io};
5
6use rustc_abi::Size;
7use rustc_ast::InlineAsmTemplatePiece;
8use tracing::trace;
9use ty::print::PrettyPrinter;
10
11use super::graphviz::write_mir_fn_graphviz;
12use crate::mir::interpret::{
13 AllocBytes, AllocId, Allocation, ConstAllocation, GlobalAlloc, Pointer, Provenance,
14 alloc_range, read_target_uint,
15};
16use crate::mir::visit::Visitor;
17use crate::mir::*;
18
19const INDENT: &str = " ";
20pub(crate) const ALIGN: usize = 40;
22
23#[derive(Clone, Copy)]
26pub enum PassWhere {
27 BeforeCFG,
29
30 AfterCFG,
32
33 BeforeBlock(BasicBlock),
35
36 BeforeLocation(Location),
38
39 AfterLocation(Location),
41
42 AfterTerminator(BasicBlock),
44}
45
46#[derive(Copy, Clone)]
49pub struct PrettyPrintMirOptions {
50 pub include_extra_comments: bool,
52}
53
54impl PrettyPrintMirOptions {
55 pub fn from_cli(tcx: TyCtxt<'_>) -> Self {
57 Self { include_extra_comments: tcx.sess.opts.unstable_opts.mir_include_spans.is_enabled() }
58 }
59}
60
61pub struct MirDumper<'dis, 'de, 'tcx> {
65 show_pass_num: bool,
66 pass_name: &'static str,
67 disambiguator: &'dis dyn Display,
68 writer: MirWriter<'de, 'tcx>,
69}
70
71impl<'dis, 'de, 'tcx> MirDumper<'dis, 'de, 'tcx> {
72 pub fn new(tcx: TyCtxt<'tcx>, pass_name: &'static str, body: &Body<'tcx>) -> Option<Self> {
79 let dump_enabled = if let Some(ref filters) = tcx.sess.opts.unstable_opts.dump_mir {
80 let node_path = ty::print::with_no_trimmed_paths!(
82 ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()))
83 );
84 filters.split('|').any(|or_filter| {
85 or_filter.split('&').all(|and_filter| {
86 let and_filter_trimmed = and_filter.trim();
87 and_filter_trimmed == "all"
88 || pass_name.contains(and_filter_trimmed)
89 || node_path.contains(and_filter_trimmed)
90 })
91 })
92 } else {
93 false
94 };
95
96 dump_enabled.then_some(MirDumper {
97 show_pass_num: false,
98 pass_name,
99 disambiguator: &0,
100 writer: MirWriter::new(tcx),
101 })
102 }
103
104 pub fn tcx(&self) -> TyCtxt<'tcx> {
105 self.writer.tcx
106 }
107
108 #[must_use]
109 pub fn set_show_pass_num(mut self) -> Self {
110 self.show_pass_num = true;
111 self
112 }
113
114 #[must_use]
115 pub fn set_disambiguator(mut self, disambiguator: &'dis dyn Display) -> Self {
116 self.disambiguator = disambiguator;
117 self
118 }
119
120 #[must_use]
121 pub fn set_extra_data(
122 mut self,
123 extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
124 ) -> Self {
125 self.writer.extra_data = extra_data;
126 self
127 }
128
129 #[must_use]
130 pub fn set_options(mut self, options: PrettyPrintMirOptions) -> Self {
131 self.writer.options = options;
132 self
133 }
134
135 pub fn dump_mir(&self, body: &Body<'tcx>) {
160 let _: io::Result<()> = try {
161 let mut file = self.create_dump_file("mir", body)?;
162 self.dump_mir_to_writer(body, &mut file)?;
163 };
164
165 if self.tcx().sess.opts.unstable_opts.dump_mir_graphviz {
166 let _: io::Result<()> = try {
167 let mut file = self.create_dump_file("dot", body)?;
168 write_mir_fn_graphviz(self.tcx(), body, false, &mut file)?;
169 };
170 }
171 }
172
173 pub fn dump_mir_to_writer(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
176 let def_path =
178 ty::print::with_no_trimmed_paths!(ty::print::with_forced_impl_filename_line!(
179 self.tcx().def_path_str(body.source.def_id())
180 ));
181 write!(w, "// MIR for `{def_path}")?;
183 match body.source.promoted {
184 None => write!(w, "`")?,
185 Some(promoted) => write!(w, "::{promoted:?}`")?,
186 }
187 writeln!(w, " {} {}", self.disambiguator, self.pass_name)?;
188 if let Some(ref layout) = body.coroutine_layout_raw() {
189 writeln!(w, "/* coroutine_layout = {layout:#?} */")?;
190 }
191 writeln!(w)?;
192 (self.writer.extra_data)(PassWhere::BeforeCFG, w)?;
193 write_user_type_annotations(self.tcx(), body, w)?;
194 self.writer.write_mir_fn(body, w)?;
195 (self.writer.extra_data)(PassWhere::AfterCFG, w)
196 }
197
198 fn dump_path(&self, extension: &str, body: &Body<'tcx>) -> PathBuf {
202 let tcx = self.tcx();
203 let source = body.source;
204 let promotion_id = match source.promoted {
205 Some(id) => format!("-{id:?}"),
206 None => String::new(),
207 };
208
209 let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
210 String::new()
211 } else if self.show_pass_num {
212 let (dialect_index, phase_index) = body.phase.index();
213 format!(".{}-{}-{:03}", dialect_index, phase_index, body.pass_count)
214 } else {
215 ".-------".to_string()
216 };
217
218 let crate_name = tcx.crate_name(source.def_id().krate);
219 let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
220 let shim_disambiguator = match source.instance {
223 ty::InstanceKind::DropGlue(_, Some(ty)) => {
224 let mut s = ".".to_owned();
227 s.extend(ty.to_string().chars().filter_map(|c| match c {
228 ' ' => None,
229 ':' | '<' | '>' => Some('_'),
230 c => Some(c),
231 }));
232 s
233 }
234 ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
235 let mut s = ".".to_owned();
236 s.extend(ty.to_string().chars().filter_map(|c| match c {
237 ' ' => None,
238 ':' | '<' | '>' => Some('_'),
239 c => Some(c),
240 }));
241 s
242 }
243 ty::InstanceKind::AsyncDropGlue(_, ty) => {
244 let ty::Coroutine(_, args) = ty.kind() else {
245 bug!();
246 };
247 let ty = args.first().unwrap().expect_ty();
248 let mut s = ".".to_owned();
249 s.extend(ty.to_string().chars().filter_map(|c| match c {
250 ' ' => None,
251 ':' | '<' | '>' => Some('_'),
252 c => Some(c),
253 }));
254 s
255 }
256 ty::InstanceKind::FutureDropPollShim(_, proxy_cor, impl_cor) => {
257 let mut s = ".".to_owned();
258 s.extend(proxy_cor.to_string().chars().filter_map(|c| match c {
259 ' ' => None,
260 ':' | '<' | '>' => Some('_'),
261 c => Some(c),
262 }));
263 s.push('.');
264 s.extend(impl_cor.to_string().chars().filter_map(|c| match c {
265 ' ' => None,
266 ':' | '<' | '>' => Some('_'),
267 c => Some(c),
268 }));
269 s
270 }
271 _ => String::new(),
272 };
273
274 let mut file_path = PathBuf::new();
275 file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir));
276
277 let pass_name = self.pass_name;
278 let disambiguator = self.disambiguator;
279 let file_name = format!(
280 "{crate_name}.{item_name}{shim_disambiguator}{promotion_id}{pass_num}.{pass_name}.{disambiguator}.{extension}",
281 );
282
283 file_path.push(&file_name);
284
285 file_path
286 }
287
288 pub fn create_dump_file(
293 &self,
294 extension: &str,
295 body: &Body<'tcx>,
296 ) -> io::Result<io::BufWriter<fs::File>> {
297 let file_path = self.dump_path(extension, body);
298 if let Some(parent) = file_path.parent() {
299 fs::create_dir_all(parent).map_err(|e| {
300 io::Error::new(
301 e.kind(),
302 format!("IO error creating MIR dump directory: {parent:?}; {e}"),
303 )
304 })?;
305 }
306 fs::File::create_buffered(&file_path).map_err(|e| {
307 io::Error::new(e.kind(), format!("IO error creating MIR dump file: {file_path:?}; {e}"))
308 })
309 }
310}
311
312pub fn write_mir_pretty<'tcx>(
318 tcx: TyCtxt<'tcx>,
319 single: Option<DefId>,
320 w: &mut dyn io::Write,
321) -> io::Result<()> {
322 let writer = MirWriter::new(tcx);
323
324 writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
325 writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
326 writeln!(w, "// HINT: See also -Z dump-mir for MIR at specific points during compilation.")?;
327
328 let mut first = true;
329 for def_id in dump_mir_def_ids(tcx, single) {
330 if first {
331 first = false;
332 } else {
333 writeln!(w)?;
335 }
336
337 let render_body = |w: &mut dyn io::Write, body| -> io::Result<()> {
338 writer.write_mir_fn(body, w)?;
339
340 for body in tcx.promoted_mir(def_id) {
341 writeln!(w)?;
342 writer.write_mir_fn(body, w)?;
343 }
344 Ok(())
345 };
346
347 if tcx.is_const_fn(def_id) {
349 render_body(w, tcx.optimized_mir(def_id))?;
350 writeln!(w)?;
351 writeln!(w, "// MIR FOR CTFE")?;
352 writer.write_mir_fn(tcx.mir_for_ctfe(def_id), w)?;
355 } else {
356 let instance_mir = tcx.instance_mir(ty::InstanceKind::Item(def_id));
357 render_body(w, instance_mir)?;
358 }
359 }
360 Ok(())
361}
362
363pub struct MirWriter<'de, 'tcx> {
365 tcx: TyCtxt<'tcx>,
366 extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
367 options: PrettyPrintMirOptions,
368}
369
370impl<'de, 'tcx> MirWriter<'de, 'tcx> {
371 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
372 MirWriter { tcx, extra_data: &|_, _| Ok(()), options: PrettyPrintMirOptions::from_cli(tcx) }
373 }
374
375 pub fn write_mir_fn(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
377 write_mir_intro(self.tcx, body, w, self.options)?;
378 for block in body.basic_blocks.indices() {
379 (self.extra_data)(PassWhere::BeforeBlock(block), w)?;
380 self.write_basic_block(block, body, w)?;
381 if block.index() + 1 != body.basic_blocks.len() {
382 writeln!(w)?;
383 }
384 }
385
386 writeln!(w, "}}")?;
387
388 write_allocations(self.tcx, body, w)?;
389
390 Ok(())
391 }
392}
393
394fn write_scope_tree(
396 tcx: TyCtxt<'_>,
397 body: &Body<'_>,
398 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
399 w: &mut dyn io::Write,
400 parent: SourceScope,
401 depth: usize,
402 options: PrettyPrintMirOptions,
403) -> io::Result<()> {
404 let indent = depth * INDENT.len();
405
406 for var_debug_info in &body.var_debug_info {
408 if var_debug_info.source_info.scope != parent {
409 continue;
411 }
412
413 let indented_debug_info = format!("{0:1$}debug {2:?};", INDENT, indent, var_debug_info);
414
415 if options.include_extra_comments {
416 writeln!(
417 w,
418 "{0:1$} // in {2}",
419 indented_debug_info,
420 ALIGN,
421 comment(tcx, var_debug_info.source_info),
422 )?;
423 } else {
424 writeln!(w, "{indented_debug_info}")?;
425 }
426 }
427
428 for (local, local_decl) in body.local_decls.iter_enumerated() {
430 if (1..body.arg_count + 1).contains(&local.index()) {
431 continue;
433 }
434
435 if local_decl.source_info.scope != parent {
436 continue;
438 }
439
440 let mut_str = local_decl.mutability.prefix_str();
441
442 let mut indented_decl = ty::print::with_no_trimmed_paths!(format!(
443 "{0:1$}let {2}{3:?}: {4}",
444 INDENT, indent, mut_str, local, local_decl.ty
445 ));
446 if let Some(user_ty) = &local_decl.user_ty {
447 for user_ty in user_ty.projections() {
448 write!(indented_decl, " as {user_ty:?}").unwrap();
449 }
450 }
451 indented_decl.push(';');
452
453 let local_name = if local == RETURN_PLACE { " return place" } else { "" };
454
455 if options.include_extra_comments {
456 writeln!(
457 w,
458 "{0:1$} //{2} in {3}",
459 indented_decl,
460 ALIGN,
461 local_name,
462 comment(tcx, local_decl.source_info),
463 )?;
464 } else {
465 writeln!(w, "{indented_decl}",)?;
466 }
467 }
468
469 let Some(children) = scope_tree.get(&parent) else {
470 return Ok(());
471 };
472
473 for &child in children {
474 let child_data = &body.source_scopes[child];
475 assert_eq!(child_data.parent_scope, Some(parent));
476
477 let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
478 (
479 format!(
480 " (inlined {}{})",
481 if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
482 callee
483 ),
484 Some(callsite_span),
485 )
486 } else {
487 (String::new(), None)
488 };
489
490 let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
491
492 if options.include_extra_comments {
493 if let Some(span) = span {
494 writeln!(
495 w,
496 "{0:1$} // at {2}",
497 indented_header,
498 ALIGN,
499 tcx.sess.source_map().span_to_embeddable_string(span),
500 )?;
501 } else {
502 writeln!(w, "{indented_header}")?;
503 }
504 } else {
505 writeln!(w, "{indented_header}")?;
506 }
507
508 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1, options)?;
509 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
510 }
511
512 Ok(())
513}
514
515impl Debug for VarDebugInfo<'_> {
516 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
517 if let Some(box VarDebugInfoFragment { ty, ref projection }) = self.composite {
518 pre_fmt_projection(&projection[..], fmt)?;
519 write!(fmt, "({}: {})", self.name, ty)?;
520 post_fmt_projection(&projection[..], fmt)?;
521 } else {
522 write!(fmt, "{}", self.name)?;
523 }
524
525 write!(fmt, " => {:?}", self.value)
526 }
527}
528
529fn write_mir_intro<'tcx>(
532 tcx: TyCtxt<'tcx>,
533 body: &Body<'_>,
534 w: &mut dyn io::Write,
535 options: PrettyPrintMirOptions,
536) -> io::Result<()> {
537 write_mir_sig(tcx, body, w)?;
538 writeln!(w, "{{")?;
539
540 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
542 for (index, scope_data) in body.source_scopes.iter_enumerated() {
543 if let Some(parent) = scope_data.parent_scope {
544 scope_tree.entry(parent).or_default().push(index);
545 } else {
546 assert_eq!(index, OUTERMOST_SOURCE_SCOPE);
548 }
549 }
550
551 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1, options)?;
552
553 writeln!(w)?;
555
556 if let Some(coverage_info_hi) = &body.coverage_info_hi {
557 write_coverage_info_hi(coverage_info_hi, w)?;
558 }
559 if let Some(function_coverage_info) = &body.function_coverage_info {
560 write_function_coverage_info(function_coverage_info, w)?;
561 }
562
563 Ok(())
564}
565
566fn write_coverage_info_hi(
567 coverage_info_hi: &coverage::CoverageInfoHi,
568 w: &mut dyn io::Write,
569) -> io::Result<()> {
570 let coverage::CoverageInfoHi { num_block_markers: _, branch_spans } = coverage_info_hi;
571
572 let mut did_print = false;
574
575 for coverage::BranchSpan { span, true_marker, false_marker } in branch_spans {
576 writeln!(
577 w,
578 "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
579 )?;
580 did_print = true;
581 }
582
583 if did_print {
584 writeln!(w)?;
585 }
586
587 Ok(())
588}
589
590fn write_function_coverage_info(
591 function_coverage_info: &coverage::FunctionCoverageInfo,
592 w: &mut dyn io::Write,
593) -> io::Result<()> {
594 let coverage::FunctionCoverageInfo { mappings, .. } = function_coverage_info;
595
596 for coverage::Mapping { kind, span } in mappings {
597 writeln!(w, "{INDENT}coverage {kind:?} => {span:?};")?;
598 }
599 writeln!(w)?;
600
601 Ok(())
602}
603
604fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io::Result<()> {
605 use rustc_hir::def::DefKind;
606
607 trace!("write_mir_sig: {:?}", body.source.instance);
608 let def_id = body.source.def_id();
609 let kind = tcx.def_kind(def_id);
610 let is_function = match kind {
611 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
612 true
613 }
614 _ => tcx.is_closure_like(def_id),
615 };
616 match (kind, body.source.promoted) {
617 (_, Some(_)) => write!(w, "const ")?, (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
619 (DefKind::Static { safety: _, mutability: hir::Mutability::Not, nested: false }, _) => {
620 write!(w, "static ")?
621 }
622 (DefKind::Static { safety: _, mutability: hir::Mutability::Mut, nested: false }, _) => {
623 write!(w, "static mut ")?
624 }
625 (_, _) if is_function => write!(w, "fn ")?,
626 (DefKind::AnonConst | DefKind::InlineConst, _) => {}
628 (DefKind::GlobalAsm, _) => {}
630 _ => bug!("Unexpected def kind {:?}", kind),
631 }
632
633 ty::print::with_forced_impl_filename_line! {
634 write!(w, "{}", tcx.def_path_str(def_id))?
636 }
637 if let Some(p) = body.source.promoted {
638 write!(w, "::{p:?}")?;
639 }
640
641 if body.source.promoted.is_none() && is_function {
642 write!(w, "(")?;
643
644 for (i, arg) in body.args_iter().enumerate() {
646 if i != 0 {
647 write!(w, ", ")?;
648 }
649 write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
650 }
651
652 write!(w, ") -> {}", body.return_ty())?;
653 } else {
654 assert_eq!(body.arg_count, 0);
655 write!(w, ": {} =", body.return_ty())?;
656 }
657
658 if let Some(yield_ty) = body.yield_ty() {
659 writeln!(w)?;
660 writeln!(w, "yields {yield_ty}")?;
661 }
662
663 write!(w, " ")?;
664 Ok(())
667}
668
669fn write_user_type_annotations(
670 tcx: TyCtxt<'_>,
671 body: &Body<'_>,
672 w: &mut dyn io::Write,
673) -> io::Result<()> {
674 if !body.user_type_annotations.is_empty() {
675 writeln!(w, "| User Type Annotations")?;
676 }
677 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
678 writeln!(
679 w,
680 "| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
681 index.index(),
682 annotation.user_ty,
683 tcx.sess.source_map().span_to_embeddable_string(annotation.span),
684 with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
685 )?;
686 }
687 if !body.user_type_annotations.is_empty() {
688 writeln!(w, "|")?;
689 }
690 Ok(())
691}
692
693pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
694 if let Some(i) = single {
695 vec![i]
696 } else {
697 tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
698 }
699}
700
701impl<'de, 'tcx> MirWriter<'de, 'tcx> {
705 fn write_basic_block(
707 &self,
708 block: BasicBlock,
709 body: &Body<'tcx>,
710 w: &mut dyn io::Write,
711 ) -> io::Result<()> {
712 let data = &body[block];
713
714 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
716 writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
717
718 let mut current_location = Location { block, statement_index: 0 };
720 for statement in &data.statements {
721 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
722
723 for debuginfo in statement.debuginfos.iter() {
724 writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
725 }
726
727 let indented_body = format!("{INDENT}{INDENT}{statement:?};");
728 if self.options.include_extra_comments {
729 writeln!(
730 w,
731 "{:A$} // {}{}",
732 indented_body,
733 if self.tcx.sess.verbose_internals() {
734 format!("{current_location:?}: ")
735 } else {
736 String::new()
737 },
738 comment(self.tcx, statement.source_info),
739 A = ALIGN,
740 )?;
741 } else {
742 writeln!(w, "{indented_body}")?;
743 }
744
745 write_extra(
746 self.tcx,
747 w,
748 &|visitor| visitor.visit_statement(statement, current_location),
749 self.options,
750 )?;
751
752 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
753
754 current_location.statement_index += 1;
755 }
756
757 for debuginfo in data.after_last_stmt_debuginfos.iter() {
758 writeln!(w, "{INDENT}{INDENT}// DBG: {debuginfo:?};")?;
759 }
760
761 (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
763 if data.terminator.is_some() {
764 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
765 if self.options.include_extra_comments {
766 writeln!(
767 w,
768 "{:A$} // {}{}",
769 indented_terminator,
770 if self.tcx.sess.verbose_internals() {
771 format!("{current_location:?}: ")
772 } else {
773 String::new()
774 },
775 comment(self.tcx, data.terminator().source_info),
776 A = ALIGN,
777 )?;
778 } else {
779 writeln!(w, "{indented_terminator}")?;
780 }
781
782 write_extra(
783 self.tcx,
784 w,
785 &|visitor| visitor.visit_terminator(data.terminator(), current_location),
786 self.options,
787 )?;
788 }
789
790 (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
791 (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
792
793 writeln!(w, "{INDENT}}}")
794 }
795}
796
797impl Debug for Statement<'_> {
798 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
799 use self::StatementKind::*;
800 match self.kind {
801 Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"),
802 FakeRead(box (ref cause, ref place)) => {
803 write!(fmt, "FakeRead({cause:?}, {place:?})")
804 }
805 Retag(ref kind, ref place) => write!(
806 fmt,
807 "Retag({}{:?})",
808 match kind {
809 RetagKind::FnEntry => "[fn entry] ",
810 RetagKind::TwoPhase => "[2phase] ",
811 RetagKind::Raw => "[raw] ",
812 RetagKind::Default => "",
813 },
814 place,
815 ),
816 StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"),
817 StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"),
818 SetDiscriminant { ref place, variant_index } => {
819 write!(fmt, "discriminant({place:?}) = {variant_index:?}")
820 }
821 PlaceMention(ref place) => {
822 write!(fmt, "PlaceMention({place:?})")
823 }
824 AscribeUserType(box (ref place, ref c_ty), ref variance) => {
825 write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
826 }
827 Coverage(ref kind) => write!(fmt, "Coverage::{kind:?}"),
828 Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
829 ConstEvalCounter => write!(fmt, "ConstEvalCounter"),
830 Nop => write!(fmt, "nop"),
831 BackwardIncompatibleDropHint { ref place, reason: _ } => {
832 write!(fmt, "BackwardIncompatibleDropHint({place:?})")
835 }
836 }
837 }
838}
839
840impl Debug for StmtDebugInfo<'_> {
841 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
842 match self {
843 StmtDebugInfo::AssignRef(local, place) => {
844 write!(fmt, "{local:?} = &{place:?}")
845 }
846 StmtDebugInfo::InvalidAssign(local) => {
847 write!(fmt, "{local:?} = &?")
848 }
849 }
850 }
851}
852
853impl Display for NonDivergingIntrinsic<'_> {
854 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855 match self {
856 Self::Assume(op) => write!(f, "assume({op:?})"),
857 Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
858 write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
859 }
860 }
861 }
862}
863
864impl<'tcx> Debug for TerminatorKind<'tcx> {
865 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
866 self.fmt_head(fmt)?;
867 let successor_count = self.successors().count();
868 let labels = self.fmt_successor_labels();
869 assert_eq!(successor_count, labels.len());
870
871 let show_unwind = !matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
873 let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
874 write!(fmt, "unwind ")?;
875 match self.unwind() {
876 None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
878 Some(UnwindAction::Continue) => write!(fmt, "continue"),
879 Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
880 Some(UnwindAction::Terminate(reason)) => {
881 write!(fmt, "terminate({})", reason.as_short_str())
882 }
883 }
884 };
885
886 match (successor_count, show_unwind) {
887 (0, false) => Ok(()),
888 (0, true) => {
889 write!(fmt, " -> ")?;
890 fmt_unwind(fmt)
891 }
892 (1, false) => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
893 _ => {
894 write!(fmt, " -> [")?;
895 for (i, target) in self.successors().enumerate() {
896 if i > 0 {
897 write!(fmt, ", ")?;
898 }
899 write!(fmt, "{}: {:?}", labels[i], target)?;
900 }
901 if show_unwind {
902 write!(fmt, ", ")?;
903 fmt_unwind(fmt)?;
904 }
905 write!(fmt, "]")
906 }
907 }
908 }
909}
910
911impl<'tcx> TerminatorKind<'tcx> {
912 pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
916 use self::TerminatorKind::*;
917 match self {
918 Goto { .. } => write!(fmt, "goto"),
919 SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"),
920 Return => write!(fmt, "return"),
921 CoroutineDrop => write!(fmt, "coroutine_drop"),
922 UnwindResume => write!(fmt, "resume"),
923 UnwindTerminate(reason) => {
924 write!(fmt, "terminate({})", reason.as_short_str())
925 }
926 Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"),
927 Unreachable => write!(fmt, "unreachable"),
928 Drop { place, async_fut: None, .. } => write!(fmt, "drop({place:?})"),
929 Drop { place, async_fut: Some(async_fut), .. } => {
930 write!(fmt, "async drop({place:?}; poll={async_fut:?})")
931 }
932 Call { func, args, destination, .. } => {
933 write!(fmt, "{destination:?} = ")?;
934 write!(fmt, "{func:?}(")?;
935 for (index, arg) in args.iter().enumerate() {
936 if index > 0 {
937 write!(fmt, ", ")?;
938 }
939 write!(fmt, "{:?}", arg.node)?;
940 }
941 write!(fmt, ")")
942 }
943 TailCall { func, args, .. } => {
944 write!(fmt, "tailcall {func:?}(")?;
945 for (index, arg) in args.iter().enumerate() {
946 if index > 0 {
947 write!(fmt, ", ")?;
948 }
949 write!(fmt, "{:?}", arg.node)?;
950 }
951 write!(fmt, ")")
952 }
953 Assert { cond, expected, msg, .. } => {
954 write!(fmt, "assert(")?;
955 if !expected {
956 write!(fmt, "!")?;
957 }
958 write!(fmt, "{cond:?}, ")?;
959 msg.fmt_assert_args(fmt)?;
960 write!(fmt, ")")
961 }
962 FalseEdge { .. } => write!(fmt, "falseEdge"),
963 FalseUnwind { .. } => write!(fmt, "falseUnwind"),
964 InlineAsm { template, operands, options, .. } => {
965 write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
966 for op in operands {
967 write!(fmt, ", ")?;
968 let print_late = |&late| if late { "late" } else { "" };
969 match op {
970 InlineAsmOperand::In { reg, value } => {
971 write!(fmt, "in({reg}) {value:?}")?;
972 }
973 InlineAsmOperand::Out { reg, late, place: Some(place) } => {
974 write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
975 }
976 InlineAsmOperand::Out { reg, late, place: None } => {
977 write!(fmt, "{}out({}) _", print_late(late), reg)?;
978 }
979 InlineAsmOperand::InOut {
980 reg,
981 late,
982 in_value,
983 out_place: Some(out_place),
984 } => {
985 write!(
986 fmt,
987 "in{}out({}) {:?} => {:?}",
988 print_late(late),
989 reg,
990 in_value,
991 out_place
992 )?;
993 }
994 InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
995 write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
996 }
997 InlineAsmOperand::Const { value } => {
998 write!(fmt, "const {value:?}")?;
999 }
1000 InlineAsmOperand::SymFn { value } => {
1001 write!(fmt, "sym_fn {value:?}")?;
1002 }
1003 InlineAsmOperand::SymStatic { def_id } => {
1004 write!(fmt, "sym_static {def_id:?}")?;
1005 }
1006 InlineAsmOperand::Label { target_index } => {
1007 write!(fmt, "label {target_index}")?;
1008 }
1009 }
1010 }
1011 write!(fmt, ", options({options:?}))")
1012 }
1013 }
1014 }
1015
1016 pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1018 use self::TerminatorKind::*;
1019 match *self {
1020 Return
1021 | TailCall { .. }
1022 | UnwindResume
1023 | UnwindTerminate(_)
1024 | Unreachable
1025 | CoroutineDrop => vec![],
1026 Goto { .. } => vec!["".into()],
1027 SwitchInt { ref targets, .. } => targets
1028 .values
1029 .iter()
1030 .map(|&u| Cow::Owned(u.to_string()))
1031 .chain(iter::once("otherwise".into()))
1032 .collect(),
1033 Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1034 vec!["return".into(), "unwind".into()]
1035 }
1036 Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
1037 Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
1038 Call { target: None, unwind: _, .. } => vec![],
1039 Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1040 Yield { drop: None, .. } => vec!["resume".into()],
1041 Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1042 vec!["return".into(), "unwind".into(), "drop".into()]
1043 }
1044 Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1045 vec!["return".into(), "unwind".into()]
1046 }
1047 Drop { unwind: _, drop: Some(_), .. } => vec!["return".into(), "drop".into()],
1048 Drop { unwind: _, .. } => vec!["return".into()],
1049 Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1050 vec!["success".into(), "unwind".into()]
1051 }
1052 Assert { unwind: _, .. } => vec!["success".into()],
1053 FalseEdge { .. } => vec!["real".into(), "imaginary".into()],
1054 FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1055 vec!["real".into(), "unwind".into()]
1056 }
1057 FalseUnwind { unwind: _, .. } => vec!["real".into()],
1058 InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1059 let mut vec = Vec::with_capacity(targets.len() + 1);
1060 if !asm_macro.diverges(options) {
1061 vec.push("return".into());
1062 }
1063 vec.resize(targets.len(), "label".into());
1064
1065 if let UnwindAction::Cleanup(_) = unwind {
1066 vec.push("unwind".into());
1067 }
1068
1069 vec
1070 }
1071 }
1072 }
1073}
1074
1075impl<'tcx> Debug for Rvalue<'tcx> {
1076 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1077 use self::Rvalue::*;
1078
1079 match *self {
1080 Use(ref place) => write!(fmt, "{place:?}"),
1081 Repeat(ref a, b) => {
1082 write!(fmt, "[{a:?}; ")?;
1083 pretty_print_const(b, fmt, false)?;
1084 write!(fmt, "]")
1085 }
1086 Cast(ref kind, ref place, ref ty) => {
1087 with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1088 }
1089 BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
1090 UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
1091 Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
1092 NullaryOp(ref op, ref t) => {
1093 let t = with_no_trimmed_paths!(format!("{}", t));
1094 match op {
1095 NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
1096 NullOp::UbChecks => write!(fmt, "UbChecks()"),
1097 NullOp::ContractChecks => write!(fmt, "ContractChecks()"),
1098 }
1099 }
1100 ThreadLocalRef(did) => ty::tls::with(|tcx| {
1101 let muta = tcx.static_mutability(did).unwrap().prefix_str();
1102 write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1103 }),
1104 Ref(region, borrow_kind, ref place) => {
1105 let kind_str = match borrow_kind {
1106 BorrowKind::Shared => "",
1107 BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1108 BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1109 BorrowKind::Mut { .. } => "mut ",
1110 };
1111
1112 let print_region = ty::tls::with(|tcx| {
1114 tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1115 });
1116 let region = if print_region {
1117 let mut region = region.to_string();
1118 if !region.is_empty() {
1119 region.push(' ');
1120 }
1121 region
1122 } else {
1123 String::new()
1125 };
1126 write!(fmt, "&{region}{kind_str}{place:?}")
1127 }
1128
1129 CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"),
1130
1131 RawPtr(mutability, ref place) => {
1132 write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1133 }
1134
1135 Aggregate(ref kind, ref places) => {
1136 let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1137 let mut tuple_fmt = fmt.debug_tuple(name);
1138 for place in places {
1139 tuple_fmt.field(place);
1140 }
1141 tuple_fmt.finish()
1142 };
1143
1144 match **kind {
1145 AggregateKind::Array(_) => write!(fmt, "{places:?}"),
1146
1147 AggregateKind::Tuple => {
1148 if places.is_empty() {
1149 write!(fmt, "()")
1150 } else {
1151 fmt_tuple(fmt, "")
1152 }
1153 }
1154
1155 AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1156 ty::tls::with(|tcx| {
1157 let variant_def = &tcx.adt_def(adt_did).variant(variant);
1158 let args = tcx.lift(args).expect("could not lift for printing");
1159 let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1160 p.print_def_path(variant_def.def_id, args)
1161 })?;
1162
1163 match variant_def.ctor_kind() {
1164 Some(CtorKind::Const) => fmt.write_str(&name),
1165 Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1166 None => {
1167 let mut struct_fmt = fmt.debug_struct(&name);
1168 for (field, place) in iter::zip(&variant_def.fields, places) {
1169 struct_fmt.field(field.name.as_str(), place);
1170 }
1171 struct_fmt.finish()
1172 }
1173 }
1174 })
1175 }
1176
1177 AggregateKind::Closure(def_id, args)
1178 | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1179 let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1180 let args = tcx.lift(args).unwrap();
1181 format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1182 } else {
1183 let span = tcx.def_span(def_id);
1184 format!(
1185 "{{closure@{}}}",
1186 tcx.sess.source_map().span_to_diagnostic_string(span)
1187 )
1188 };
1189 let mut struct_fmt = fmt.debug_struct(&name);
1190
1191 if let Some(def_id) = def_id.as_local()
1193 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1194 {
1195 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1196 let var_name = tcx.hir_name(var_id);
1197 struct_fmt.field(var_name.as_str(), place);
1198 }
1199 } else {
1200 for (index, place) in places.iter().enumerate() {
1201 struct_fmt.field(&format!("{index}"), place);
1202 }
1203 }
1204
1205 struct_fmt.finish()
1206 }),
1207
1208 AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1209 let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1210 let mut struct_fmt = fmt.debug_struct(&name);
1211
1212 if let Some(def_id) = def_id.as_local()
1214 && let Some(upvars) = tcx.upvars_mentioned(def_id)
1215 {
1216 for (&var_id, place) in iter::zip(upvars.keys(), places) {
1217 let var_name = tcx.hir_name(var_id);
1218 struct_fmt.field(var_name.as_str(), place);
1219 }
1220 } else {
1221 for (index, place) in places.iter().enumerate() {
1222 struct_fmt.field(&format!("{index}"), place);
1223 }
1224 }
1225
1226 struct_fmt.finish()
1227 }),
1228
1229 AggregateKind::RawPtr(pointee_ty, mutability) => {
1230 let kind_str = match mutability {
1231 Mutability::Mut => "mut",
1232 Mutability::Not => "const",
1233 };
1234 with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1235 fmt_tuple(fmt, "")
1236 }
1237 }
1238 }
1239
1240 ShallowInitBox(ref place, ref ty) => {
1241 with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
1242 }
1243
1244 WrapUnsafeBinder(ref op, ty) => {
1245 with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1246 }
1247 }
1248 }
1249}
1250
1251impl<'tcx> Debug for Operand<'tcx> {
1252 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1253 use self::Operand::*;
1254 match *self {
1255 Constant(ref a) => write!(fmt, "{a:?}"),
1256 Copy(ref place) => write!(fmt, "copy {place:?}"),
1257 Move(ref place) => write!(fmt, "move {place:?}"),
1258 }
1259 }
1260}
1261
1262impl<'tcx> Debug for ConstOperand<'tcx> {
1263 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1264 write!(fmt, "{self}")
1265 }
1266}
1267
1268impl<'tcx> Display for ConstOperand<'tcx> {
1269 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1270 match self.ty().kind() {
1271 ty::FnDef(..) => {}
1272 _ => write!(fmt, "const ")?,
1273 }
1274 Display::fmt(&self.const_, fmt)
1275 }
1276}
1277
1278impl Debug for Place<'_> {
1279 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1280 self.as_ref().fmt(fmt)
1281 }
1282}
1283
1284impl Debug for PlaceRef<'_> {
1285 fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1286 pre_fmt_projection(self.projection, fmt)?;
1287 write!(fmt, "{:?}", self.local)?;
1288 post_fmt_projection(self.projection, fmt)
1289 }
1290}
1291
1292fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1293 for &elem in projection.iter().rev() {
1294 match elem {
1295 ProjectionElem::OpaqueCast(_)
1296 | ProjectionElem::Downcast(_, _)
1297 | ProjectionElem::Field(_, _) => {
1298 write!(fmt, "(")?;
1299 }
1300 ProjectionElem::Deref => {
1301 write!(fmt, "(*")?;
1302 }
1303 ProjectionElem::Index(_)
1304 | ProjectionElem::ConstantIndex { .. }
1305 | ProjectionElem::Subslice { .. } => {}
1306 ProjectionElem::UnwrapUnsafeBinder(_) => {
1307 write!(fmt, "unwrap_binder!(")?;
1308 }
1309 }
1310 }
1311
1312 Ok(())
1313}
1314
1315fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1316 for &elem in projection.iter() {
1317 match elem {
1318 ProjectionElem::OpaqueCast(ty) => {
1319 write!(fmt, " as {ty})")?;
1320 }
1321 ProjectionElem::Downcast(Some(name), _index) => {
1322 write!(fmt, " as {name})")?;
1323 }
1324 ProjectionElem::Downcast(None, index) => {
1325 write!(fmt, " as variant#{index:?})")?;
1326 }
1327 ProjectionElem::Deref => {
1328 write!(fmt, ")")?;
1329 }
1330 ProjectionElem::Field(field, ty) => {
1331 with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1332 }
1333 ProjectionElem::Index(ref index) => {
1334 write!(fmt, "[{index:?}]")?;
1335 }
1336 ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1337 write!(fmt, "[{offset:?} of {min_length:?}]")?;
1338 }
1339 ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1340 write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1341 }
1342 ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1343 write!(fmt, "[{from:?}:]")?;
1344 }
1345 ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1346 write!(fmt, "[:-{to:?}]")?;
1347 }
1348 ProjectionElem::Subslice { from, to, from_end: true } => {
1349 write!(fmt, "[{from:?}:-{to:?}]")?;
1350 }
1351 ProjectionElem::Subslice { from, to, from_end: false } => {
1352 write!(fmt, "[{from:?}..{to:?}]")?;
1353 }
1354 ProjectionElem::UnwrapUnsafeBinder(ty) => {
1355 write!(fmt, "; {ty})")?;
1356 }
1357 }
1358 }
1359
1360 Ok(())
1361}
1362
1363fn write_extra<'tcx>(
1367 tcx: TyCtxt<'tcx>,
1368 write: &mut dyn io::Write,
1369 visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1370 options: PrettyPrintMirOptions,
1371) -> io::Result<()> {
1372 if options.include_extra_comments {
1373 let mut extra_comments = ExtraComments { tcx, comments: vec![] };
1374 visit_op(&mut extra_comments);
1375 for comment in extra_comments.comments {
1376 writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1377 }
1378 }
1379 Ok(())
1380}
1381
1382struct ExtraComments<'tcx> {
1383 tcx: TyCtxt<'tcx>,
1384 comments: Vec<String>,
1385}
1386
1387impl<'tcx> ExtraComments<'tcx> {
1388 fn push(&mut self, lines: &str) {
1389 for line in lines.split('\n') {
1390 self.comments.push(line.to_string());
1391 }
1392 }
1393}
1394
1395fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1396 match *ty.kind() {
1397 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1398 ty::Tuple(g_args) if g_args.is_empty() => false,
1400 ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1401 ty::Array(ty, _) => use_verbose(ty, fn_def),
1402 ty::FnDef(..) => fn_def,
1403 _ => true,
1404 }
1405}
1406
1407impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1408 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1409 let ConstOperand { span, user_ty, const_ } = constant;
1410 if use_verbose(const_.ty(), true) {
1411 self.push("mir::ConstOperand");
1412 self.push(&format!(
1413 "+ span: {}",
1414 self.tcx.sess.source_map().span_to_embeddable_string(*span)
1415 ));
1416 if let Some(user_ty) = user_ty {
1417 self.push(&format!("+ user_ty: {user_ty:?}"));
1418 }
1419
1420 let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1421 let tcx = self.tcx;
1422 rustc_data_structures::make_display(move |fmt| {
1423 pretty_print_const_value_tcx(tcx, val, ty, fmt)
1424 })
1425 };
1426
1427 let fmt_valtree = |cv: &ty::Value<'tcx>| {
1428 let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1429 p.pretty_print_const_valtree(*cv, true).unwrap();
1430 p.into_buffer()
1431 };
1432
1433 let val = match const_ {
1434 Const::Ty(_, ct) => match ct.kind() {
1435 ty::ConstKind::Param(p) => format!("ty::Param({p})"),
1436 ty::ConstKind::Unevaluated(uv) => {
1437 format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1438 }
1439 ty::ConstKind::Value(cv) => {
1440 format!("ty::Valtree({})", fmt_valtree(&cv))
1441 }
1442 ty::ConstKind::Error(_) => "Error".to_string(),
1444 ty::ConstKind::Placeholder(_)
1446 | ty::ConstKind::Infer(_)
1447 | ty::ConstKind::Expr(_)
1448 | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", const_),
1449 },
1450 Const::Unevaluated(uv, _) => {
1451 format!(
1452 "Unevaluated({}, {:?}, {:?})",
1453 self.tcx.def_path_str(uv.def),
1454 uv.args,
1455 uv.promoted,
1456 )
1457 }
1458 Const::Val(val, ty) => format!("Value({})", fmt_val(*val, *ty)),
1459 };
1460
1461 self.push(&format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1465 }
1466 }
1467
1468 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1469 self.super_rvalue(rvalue, location);
1470 if let Rvalue::Aggregate(kind, _) = rvalue {
1471 match **kind {
1472 AggregateKind::Closure(def_id, args) => {
1473 self.push("closure");
1474 self.push(&format!("+ def_id: {def_id:?}"));
1475 self.push(&format!("+ args: {args:#?}"));
1476 }
1477
1478 AggregateKind::Coroutine(def_id, args) => {
1479 self.push("coroutine");
1480 self.push(&format!("+ def_id: {def_id:?}"));
1481 self.push(&format!("+ args: {args:#?}"));
1482 self.push(&format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1483 }
1484
1485 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1486 self.push("adt");
1487 self.push(&format!("+ user_ty: {user_ty:?}"));
1488 }
1489
1490 _ => {}
1491 }
1492 }
1493 }
1494}
1495
1496fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1497 let location = tcx.sess.source_map().span_to_embeddable_string(span);
1498 format!("scope {} at {}", scope.index(), location,)
1499}
1500
1501pub fn write_allocations<'tcx>(
1507 tcx: TyCtxt<'tcx>,
1508 body: &Body<'_>,
1509 w: &mut dyn io::Write,
1510) -> io::Result<()> {
1511 fn alloc_ids_from_alloc(
1512 alloc: ConstAllocation<'_>,
1513 ) -> impl DoubleEndedIterator<Item = AllocId> {
1514 alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1515 }
1516
1517 fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1518 match val {
1519 ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1520 ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1521 ConstValue::ZeroSized => None,
1522 ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1523 Some(alloc_id)
1526 }
1527 }
1528 }
1529 struct CollectAllocIds(BTreeSet<AllocId>);
1530
1531 impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1532 fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1533 match c.const_ {
1534 Const::Ty(_, _) | Const::Unevaluated(..) => {}
1535 Const::Val(val, _) => {
1536 if let Some(id) = alloc_id_from_const_val(val) {
1537 self.0.insert(id);
1538 }
1539 }
1540 }
1541 }
1542 }
1543
1544 let mut visitor = CollectAllocIds(Default::default());
1545 visitor.visit_body(body);
1546
1547 let mut seen = visitor.0;
1551 let mut todo: Vec<_> = seen.iter().copied().collect();
1552 while let Some(id) = todo.pop() {
1553 let mut write_allocation_track_relocs =
1554 |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1555 for id in alloc_ids_from_alloc(alloc).rev() {
1557 if seen.insert(id) {
1558 todo.push(id);
1559 }
1560 }
1561 write!(w, "{}", display_allocation(tcx, alloc.inner()))
1562 };
1563 write!(w, "\n{id:?}")?;
1564 match tcx.try_get_global_alloc(id) {
1565 None => write!(w, " (deallocated)")?,
1568 Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?,
1569 Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1570 write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1571 }
1572 Some(GlobalAlloc::TypeId { ty }) => write!(w, " (typeid for {ty})")?,
1573 Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1574 write!(w, " (static: {}", tcx.def_path_str(did))?;
1575 if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1576 && body
1577 .source
1578 .def_id()
1579 .as_local()
1580 .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1581 {
1582 write!(w, ")")?;
1586 } else {
1587 match tcx.eval_static_initializer(did) {
1588 Ok(alloc) => {
1589 write!(w, ", ")?;
1590 write_allocation_track_relocs(w, alloc)?;
1591 }
1592 Err(_) => write!(w, ", error during initializer evaluation)")?,
1593 }
1594 }
1595 }
1596 Some(GlobalAlloc::Static(did)) => {
1597 write!(w, " (extern static: {})", tcx.def_path_str(did))?
1598 }
1599 Some(GlobalAlloc::Memory(alloc)) => {
1600 write!(w, " (")?;
1601 write_allocation_track_relocs(w, alloc)?
1602 }
1603 }
1604 writeln!(w)?;
1605 }
1606 Ok(())
1607}
1608
1609pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1626 tcx: TyCtxt<'tcx>,
1627 alloc: &'a Allocation<Prov, Extra, Bytes>,
1628) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1629 RenderAllocation { tcx, alloc }
1630}
1631
1632#[doc(hidden)]
1633pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1634 tcx: TyCtxt<'tcx>,
1635 alloc: &'a Allocation<Prov, Extra, Bytes>,
1636}
1637
1638impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1639 for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1640{
1641 fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1642 let RenderAllocation { tcx, alloc } = *self;
1643 write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1644 if alloc.size() == Size::ZERO {
1645 return write!(w, " {{}}");
1647 }
1648 if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1649 return write!(w, " {{ .. }}");
1650 }
1651 writeln!(w, " {{")?;
1653 write_allocation_bytes(tcx, alloc, w, " ")?;
1654 write!(w, "}}")?;
1655 Ok(())
1656 }
1657}
1658
1659fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1660 for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1661 write!(w, " ")?;
1662 }
1663 writeln!(w, " │ {ascii}")
1664}
1665
1666const BYTES_PER_LINE: usize = 16;
1668
1669fn write_allocation_newline(
1671 w: &mut dyn std::fmt::Write,
1672 mut line_start: Size,
1673 ascii: &str,
1674 pos_width: usize,
1675 prefix: &str,
1676) -> Result<Size, std::fmt::Error> {
1677 write_allocation_endline(w, ascii)?;
1678 line_start += Size::from_bytes(BYTES_PER_LINE);
1679 write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1680 Ok(line_start)
1681}
1682
1683pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1687 tcx: TyCtxt<'tcx>,
1688 alloc: &Allocation<Prov, Extra, Bytes>,
1689 w: &mut dyn std::fmt::Write,
1690 prefix: &str,
1691) -> std::fmt::Result {
1692 let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1693 let pos_width = hex_number_length(alloc.size().bytes());
1695
1696 if num_lines > 0 {
1697 write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1698 } else {
1699 write!(w, "{prefix}")?;
1700 }
1701
1702 let mut i = Size::ZERO;
1703 let mut line_start = Size::ZERO;
1704
1705 let ptr_size = tcx.data_layout.pointer_size();
1706
1707 let mut ascii = String::new();
1708
1709 let oversized_ptr = |target: &mut String, width| {
1710 if target.len() > width {
1711 write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1712 }
1713 };
1714
1715 while i < alloc.size() {
1716 if i != line_start {
1720 write!(w, " ")?;
1721 }
1722 if let Some(prov) = alloc.provenance().get_ptr(i) {
1723 assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1725 let j = i.bytes_usize();
1726 let offset = alloc
1727 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1728 let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1729 let offset = Size::from_bytes(offset);
1730 let provenance_width = |bytes| bytes * 3;
1731 let ptr = Pointer::new(prov, offset);
1732 let mut target = format!("{ptr:?}");
1733 if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1734 target = format!("{ptr:#?}");
1736 }
1737 if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1738 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1741 let overflow = ptr_size - remainder;
1742 let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1743 let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1744 ascii.push('╾'); for _ in 1..remainder.bytes() {
1746 ascii.push('─'); }
1748 if overflow_width > remainder_width && overflow_width >= target.len() {
1749 write!(w, "╾{0:─^1$}", "", remainder_width)?;
1751 line_start =
1752 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1753 ascii.clear();
1754 write!(w, "{target:─^overflow_width$}╼")?;
1755 } else {
1756 oversized_ptr(&mut target, remainder_width);
1757 write!(w, "╾{target:─^remainder_width$}")?;
1758 line_start =
1759 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1760 write!(w, "{0:─^1$}╼", "", overflow_width)?;
1761 ascii.clear();
1762 }
1763 for _ in 0..overflow.bytes() - 1 {
1764 ascii.push('─');
1765 }
1766 ascii.push('╼'); i += ptr_size;
1768 continue;
1769 } else {
1770 let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1772 oversized_ptr(&mut target, provenance_width);
1773 ascii.push('╾');
1774 write!(w, "╾{target:─^provenance_width$}╼")?;
1775 for _ in 0..ptr_size.bytes() - 2 {
1776 ascii.push('─');
1777 }
1778 ascii.push('╼');
1779 i += ptr_size;
1780 }
1781 } else if let Some((prov, idx)) = alloc.provenance().get_byte(i, &tcx) {
1782 assert!(
1784 alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1785 );
1786 ascii.push('━'); let j = i.bytes_usize();
1790 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1791 write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼")?;
1792 i += Size::from_bytes(1);
1793 } else if alloc
1794 .init_mask()
1795 .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1796 .is_ok()
1797 {
1798 let j = i.bytes_usize();
1799
1800 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1803 write!(w, "{c:02x}")?;
1804 if c.is_ascii_control() || c >= 0x80 {
1805 ascii.push('.');
1806 } else {
1807 ascii.push(char::from(c));
1808 }
1809 i += Size::from_bytes(1);
1810 } else {
1811 write!(w, "__")?;
1812 ascii.push('░');
1813 i += Size::from_bytes(1);
1814 }
1815 if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1817 line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1818 ascii.clear();
1819 }
1820 }
1821 write_allocation_endline(w, &ascii)?;
1822
1823 Ok(())
1824}
1825
1826fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1830 write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1831}
1832
1833fn comma_sep<'tcx>(
1834 tcx: TyCtxt<'tcx>,
1835 fmt: &mut Formatter<'_>,
1836 elems: Vec<(ConstValue, Ty<'tcx>)>,
1837) -> fmt::Result {
1838 let mut first = true;
1839 for (ct, ty) in elems {
1840 if !first {
1841 fmt.write_str(", ")?;
1842 }
1843 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1844 first = false;
1845 }
1846 Ok(())
1847}
1848
1849fn pretty_print_const_value_tcx<'tcx>(
1850 tcx: TyCtxt<'tcx>,
1851 ct: ConstValue,
1852 ty: Ty<'tcx>,
1853 fmt: &mut Formatter<'_>,
1854) -> fmt::Result {
1855 use crate::ty::print::PrettyPrinter;
1856
1857 if tcx.sess.verbose_internals() {
1858 fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?;
1859 return Ok(());
1860 }
1861
1862 let u8_type = tcx.types.u8;
1863 match (ct, ty.kind()) {
1864 (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1866 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1867 fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?;
1868 return Ok(());
1869 }
1870 }
1871 (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => {
1872 if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1873 pretty_print_byte_str(fmt, data)?;
1874 return Ok(());
1875 }
1876 }
1877 (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1878 let n = n.try_to_target_usize(tcx).unwrap();
1879 let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1880 let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1882 let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1883 fmt.write_str("*")?;
1884 pretty_print_byte_str(fmt, byte_str)?;
1885 return Ok(());
1886 }
1887 (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1895 let ct = tcx.lift(ct).unwrap();
1896 let ty = tcx.lift(ty).unwrap();
1897 if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1898 let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1899 match *ty.kind() {
1900 ty::Array(..) => {
1901 fmt.write_str("[")?;
1902 comma_sep(tcx, fmt, fields)?;
1903 fmt.write_str("]")?;
1904 }
1905 ty::Tuple(..) => {
1906 fmt.write_str("(")?;
1907 comma_sep(tcx, fmt, fields)?;
1908 if contents.fields.len() == 1 {
1909 fmt.write_str(",")?;
1910 }
1911 fmt.write_str(")")?;
1912 }
1913 ty::Adt(def, _) if def.variants().is_empty() => {
1914 fmt.write_str(&format!("{{unreachable(): {ty}}}"))?;
1915 }
1916 ty::Adt(def, args) => {
1917 let variant_idx = contents
1918 .variant
1919 .expect("destructed mir constant of adt without variant idx");
1920 let variant_def = &def.variant(variant_idx);
1921 let args = tcx.lift(args).unwrap();
1922 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1923 p.print_alloc_ids = true;
1924 p.pretty_print_value_path(variant_def.def_id, args)?;
1925 fmt.write_str(&p.into_buffer())?;
1926
1927 match variant_def.ctor_kind() {
1928 Some(CtorKind::Const) => {}
1929 Some(CtorKind::Fn) => {
1930 fmt.write_str("(")?;
1931 comma_sep(tcx, fmt, fields)?;
1932 fmt.write_str(")")?;
1933 }
1934 None => {
1935 fmt.write_str(" {{ ")?;
1936 let mut first = true;
1937 for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
1938 {
1939 if !first {
1940 fmt.write_str(", ")?;
1941 }
1942 write!(fmt, "{}: ", field_def.name)?;
1943 pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1944 first = false;
1945 }
1946 fmt.write_str(" }}")?;
1947 }
1948 }
1949 }
1950 _ => unreachable!(),
1951 }
1952 return Ok(());
1953 }
1954 }
1955 (ConstValue::Scalar(scalar), _) => {
1956 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1957 p.print_alloc_ids = true;
1958 let ty = tcx.lift(ty).unwrap();
1959 p.pretty_print_const_scalar(scalar, ty)?;
1960 fmt.write_str(&p.into_buffer())?;
1961 return Ok(());
1962 }
1963 (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
1964 let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1965 p.print_alloc_ids = true;
1966 p.pretty_print_value_path(*d, s)?;
1967 fmt.write_str(&p.into_buffer())?;
1968 return Ok(());
1969 }
1970 _ => {}
1973 }
1974 write!(fmt, "{ct:?}: {ty}")
1976}
1977
1978pub(crate) fn pretty_print_const_value<'tcx>(
1979 ct: ConstValue,
1980 ty: Ty<'tcx>,
1981 fmt: &mut Formatter<'_>,
1982) -> fmt::Result {
1983 ty::tls::with(|tcx| {
1984 let ct = tcx.lift(ct).unwrap();
1985 let ty = tcx.lift(ty).unwrap();
1986 pretty_print_const_value_tcx(tcx, ct, ty, fmt)
1987 })
1988}
1989
1990fn hex_number_length(x: u64) -> usize {
2001 if x == 0 {
2002 return 1;
2003 }
2004 let mut length = 0;
2005 let mut x_left = x;
2006 while x_left > 0 {
2007 x_left /= 16;
2008 length += 1;
2009 }
2010 length
2011}