rustc_middle/mir/
pretty.rs

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 = "    ";
20/// Alignment for lining up comments following MIR statements
21pub(crate) const ALIGN: usize = 40;
22
23/// An indication of where we are in the control flow graph. Used for printing
24/// extra information in `dump_mir`
25#[derive(Clone, Copy)]
26pub enum PassWhere {
27    /// We have not started dumping the control flow graph, but we are about to.
28    BeforeCFG,
29
30    /// We just finished dumping the control flow graph. This is right before EOF
31    AfterCFG,
32
33    /// We are about to start dumping the given basic block.
34    BeforeBlock(BasicBlock),
35
36    /// We are just about to dump the given statement or terminator.
37    BeforeLocation(Location),
38
39    /// We just dumped the given statement or terminator.
40    AfterLocation(Location),
41
42    /// We just dumped the terminator for a block but not the closing `}`.
43    AfterTerminator(BasicBlock),
44}
45
46/// Cosmetic options for pretty-printing the MIR contents, gathered from the CLI. Each pass can
47/// override these when dumping its own specific MIR information with `dump_mir`.
48#[derive(Copy, Clone)]
49pub struct PrettyPrintMirOptions {
50    /// Whether to include extra comments, like span info. From `-Z mir-include-spans`.
51    pub include_extra_comments: bool,
52}
53
54impl PrettyPrintMirOptions {
55    /// Create the default set of MIR pretty-printing options from the CLI flags.
56    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
61/// Manages MIR dumping, which is MIR writing done to a file with a specific name. In particular,
62/// it makes it impossible to dump MIR to one of these files when it hasn't been requested from the
63/// command line. Layered on top of `MirWriter`, which does the actual writing.
64pub 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    // If dumping should be performed (e.g. because it was requested on the
73    // CLI), returns a `MirDumper` with default values for the following fields:
74    // - `show_pass_num`: `false`
75    // - `disambiguator`: `&0`
76    // - `writer.extra_data`: a no-op
77    // - `writer.options`: default options derived from CLI flags
78    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            // see notes on #41697 below
81            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    /// If the session is properly configured, dumps a human-readable representation of the MIR
136    /// (with default pretty-printing options) into:
137    ///
138    /// ```text
139    /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
140    /// ```
141    ///
142    /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
143    /// where `<filter>` takes the following forms:
144    ///
145    /// - `all` -- dump MIR for all fns, all passes, all everything
146    /// - a filter defined by a set of substrings combined with `&` and `|`
147    ///   (`&` has higher precedence). At least one of the `|`-separated groups
148    ///   must match; an `|`-separated group matches if all of its `&`-separated
149    ///   substrings are matched.
150    ///
151    /// Example:
152    ///
153    /// - `nll` == match if `nll` appears in the name
154    /// - `foo & nll` == match if `foo` and `nll` both appear in the name
155    /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
156    ///   or `typeck` appears in the name.
157    /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
158    ///   or `typeck` and `bar` both appear in the name.
159    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    // #41697 -- we use `with_forced_impl_filename_line()` because `def_path_str()` would otherwise
174    // trigger `type_of`, and this can run while we are already attempting to evaluate `type_of`.
175    pub fn dump_mir_to_writer(&self, body: &Body<'tcx>, w: &mut dyn io::Write) -> io::Result<()> {
176        // see notes on #41697 above
177        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        // ignore-tidy-odd-backticks the literal below is fine
182        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    /// Returns the path to the filename where we should dump a given MIR.
199    /// Also used by other bits of code (e.g., NLL inference) that dump
200    /// graphviz data or other things.
201    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        // All drop shims have the same DefId, so we have to add the type
221        // to get unique file names.
222        let shim_disambiguator = match source.instance {
223            ty::InstanceKind::DropGlue(_, Some(ty)) => {
224                // Unfortunately, pretty-printed types are not very filename-friendly.
225                // We do some filtering.
226                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    /// Attempts to open a file where we should dump a given MIR or other
289    /// bit of MIR-related data. Used by `mir-dump`, but also by other
290    /// bits of code (e.g., NLL inference) that dump graphviz data or
291    /// other things, and hence takes the extension as an argument.
292    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
312///////////////////////////////////////////////////////////////////////////
313// Whole MIR bodies
314
315/// Write out a human-readable textual representation for the given MIR, with the default
316/// [PrettyPrintMirOptions].
317pub 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            // Put empty lines between all items
334            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        // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
348        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            // Do not use `render_body`, as that would render the promoteds again, but these
353            // are shared between mir_for_ctfe and optimized_mir
354            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
363/// Does the writing of MIR to output, e.g. a file.
364pub 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    /// Write out a human-readable textual representation for the given function.
376    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
394/// Prints local variables in a scope tree.
395fn 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    // Local variable debuginfo.
407    for var_debug_info in &body.var_debug_info {
408        if var_debug_info.source_info.scope != parent {
409            // Not declared in this scope.
410            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    // Local variable types.
429    for (local, local_decl) in body.local_decls.iter_enumerated() {
430        if (1..body.arg_count + 1).contains(&local.index()) {
431            // Skip over argument locals, they're printed in the signature.
432            continue;
433        }
434
435        if local_decl.source_info.scope != parent {
436            // Not declared in this scope.
437            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
529/// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
530/// local variables (both user-defined bindings and compiler temporaries).
531fn 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    // construct a scope tree and write it out
541    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            // Only the argument scope has no parent, because it's the root.
547            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    // Add an empty line before the first block is printed.
554    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    // Only add an extra trailing newline if we printed at least one thing.
573    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 ")?, // promoteds are the closest to consts
618        (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        // things like anon const, not an item
627        (DefKind::AnonConst | DefKind::InlineConst, _) => {}
628        // `global_asm!` have fake bodies, which we may dump after mir-build
629        (DefKind::GlobalAsm, _) => {}
630        _ => bug!("Unexpected def kind {:?}", kind),
631    }
632
633    ty::print::with_forced_impl_filename_line! {
634        // see notes on #41697 elsewhere
635        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        // fn argument types.
645        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    // Next thing that gets printed is the opening {
665
666    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
701///////////////////////////////////////////////////////////////////////////
702// Basic blocks and their parts (statements, terminators, ...)
703
704impl<'de, 'tcx> MirWriter<'de, 'tcx> {
705    /// Write out a human-readable textual representation for the given basic block.
706    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        // Basic block label at the top.
715        let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
716        writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
717
718        // List of statements in the middle.
719        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            let indented_body = format!("{INDENT}{INDENT}{statement:?};");
723            if self.options.include_extra_comments {
724                writeln!(
725                    w,
726                    "{:A$} // {}{}",
727                    indented_body,
728                    if self.tcx.sess.verbose_internals() {
729                        format!("{current_location:?}: ")
730                    } else {
731                        String::new()
732                    },
733                    comment(self.tcx, statement.source_info),
734                    A = ALIGN,
735                )?;
736            } else {
737                writeln!(w, "{indented_body}")?;
738            }
739
740            write_extra(
741                self.tcx,
742                w,
743                &|visitor| visitor.visit_statement(statement, current_location),
744                self.options,
745            )?;
746
747            (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
748
749            current_location.statement_index += 1;
750        }
751
752        // Terminator at the bottom.
753        (self.extra_data)(PassWhere::BeforeLocation(current_location), w)?;
754        if data.terminator.is_some() {
755            let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
756            if self.options.include_extra_comments {
757                writeln!(
758                    w,
759                    "{:A$} // {}{}",
760                    indented_terminator,
761                    if self.tcx.sess.verbose_internals() {
762                        format!("{current_location:?}: ")
763                    } else {
764                        String::new()
765                    },
766                    comment(self.tcx, data.terminator().source_info),
767                    A = ALIGN,
768                )?;
769            } else {
770                writeln!(w, "{indented_terminator}")?;
771            }
772
773            write_extra(
774                self.tcx,
775                w,
776                &|visitor| visitor.visit_terminator(data.terminator(), current_location),
777                self.options,
778            )?;
779        }
780
781        (self.extra_data)(PassWhere::AfterLocation(current_location), w)?;
782        (self.extra_data)(PassWhere::AfterTerminator(block), w)?;
783
784        writeln!(w, "{INDENT}}}")
785    }
786}
787
788impl Debug for Statement<'_> {
789    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
790        use self::StatementKind::*;
791        match self.kind {
792            Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"),
793            FakeRead(box (ref cause, ref place)) => {
794                write!(fmt, "FakeRead({cause:?}, {place:?})")
795            }
796            Retag(ref kind, ref place) => write!(
797                fmt,
798                "Retag({}{:?})",
799                match kind {
800                    RetagKind::FnEntry => "[fn entry] ",
801                    RetagKind::TwoPhase => "[2phase] ",
802                    RetagKind::Raw => "[raw] ",
803                    RetagKind::Default => "",
804                },
805                place,
806            ),
807            StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"),
808            StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"),
809            SetDiscriminant { ref place, variant_index } => {
810                write!(fmt, "discriminant({place:?}) = {variant_index:?}")
811            }
812            Deinit(ref place) => write!(fmt, "Deinit({place:?})"),
813            PlaceMention(ref place) => {
814                write!(fmt, "PlaceMention({place:?})")
815            }
816            AscribeUserType(box (ref place, ref c_ty), ref variance) => {
817                write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
818            }
819            Coverage(ref kind) => write!(fmt, "Coverage::{kind:?}"),
820            Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
821            ConstEvalCounter => write!(fmt, "ConstEvalCounter"),
822            Nop => write!(fmt, "nop"),
823            BackwardIncompatibleDropHint { ref place, reason: _ } => {
824                // For now, we don't record the reason because there is only one use case,
825                // which is to report breaking change in drop order by Edition 2024
826                write!(fmt, "BackwardIncompatibleDropHint({place:?})")
827            }
828        }
829    }
830}
831
832impl Display for NonDivergingIntrinsic<'_> {
833    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
834        match self {
835            Self::Assume(op) => write!(f, "assume({op:?})"),
836            Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
837                write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
838            }
839        }
840    }
841}
842
843impl<'tcx> Debug for TerminatorKind<'tcx> {
844    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
845        self.fmt_head(fmt)?;
846        let successor_count = self.successors().count();
847        let labels = self.fmt_successor_labels();
848        assert_eq!(successor_count, labels.len());
849
850        // `Cleanup` is already included in successors
851        let show_unwind = !matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
852        let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
853            write!(fmt, "unwind ")?;
854            match self.unwind() {
855                // Not needed or included in successors
856                None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
857                Some(UnwindAction::Continue) => write!(fmt, "continue"),
858                Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
859                Some(UnwindAction::Terminate(reason)) => {
860                    write!(fmt, "terminate({})", reason.as_short_str())
861                }
862            }
863        };
864
865        match (successor_count, show_unwind) {
866            (0, false) => Ok(()),
867            (0, true) => {
868                write!(fmt, " -> ")?;
869                fmt_unwind(fmt)
870            }
871            (1, false) => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
872            _ => {
873                write!(fmt, " -> [")?;
874                for (i, target) in self.successors().enumerate() {
875                    if i > 0 {
876                        write!(fmt, ", ")?;
877                    }
878                    write!(fmt, "{}: {:?}", labels[i], target)?;
879                }
880                if show_unwind {
881                    write!(fmt, ", ")?;
882                    fmt_unwind(fmt)?;
883                }
884                write!(fmt, "]")
885            }
886        }
887    }
888}
889
890impl<'tcx> TerminatorKind<'tcx> {
891    /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
892    /// successor basic block, if any. The only information not included is the list of possible
893    /// successors, which may be rendered differently between the text and the graphviz format.
894    pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
895        use self::TerminatorKind::*;
896        match self {
897            Goto { .. } => write!(fmt, "goto"),
898            SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"),
899            Return => write!(fmt, "return"),
900            CoroutineDrop => write!(fmt, "coroutine_drop"),
901            UnwindResume => write!(fmt, "resume"),
902            UnwindTerminate(reason) => {
903                write!(fmt, "terminate({})", reason.as_short_str())
904            }
905            Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"),
906            Unreachable => write!(fmt, "unreachable"),
907            Drop { place, async_fut: None, .. } => write!(fmt, "drop({place:?})"),
908            Drop { place, async_fut: Some(async_fut), .. } => {
909                write!(fmt, "async drop({place:?}; poll={async_fut:?})")
910            }
911            Call { func, args, destination, .. } => {
912                write!(fmt, "{destination:?} = ")?;
913                write!(fmt, "{func:?}(")?;
914                for (index, arg) in args.iter().enumerate() {
915                    if index > 0 {
916                        write!(fmt, ", ")?;
917                    }
918                    write!(fmt, "{:?}", arg.node)?;
919                }
920                write!(fmt, ")")
921            }
922            TailCall { func, args, .. } => {
923                write!(fmt, "tailcall {func:?}(")?;
924                for (index, arg) in args.iter().enumerate() {
925                    if index > 0 {
926                        write!(fmt, ", ")?;
927                    }
928                    write!(fmt, "{:?}", arg.node)?;
929                }
930                write!(fmt, ")")
931            }
932            Assert { cond, expected, msg, .. } => {
933                write!(fmt, "assert(")?;
934                if !expected {
935                    write!(fmt, "!")?;
936                }
937                write!(fmt, "{cond:?}, ")?;
938                msg.fmt_assert_args(fmt)?;
939                write!(fmt, ")")
940            }
941            FalseEdge { .. } => write!(fmt, "falseEdge"),
942            FalseUnwind { .. } => write!(fmt, "falseUnwind"),
943            InlineAsm { template, operands, options, .. } => {
944                write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
945                for op in operands {
946                    write!(fmt, ", ")?;
947                    let print_late = |&late| if late { "late" } else { "" };
948                    match op {
949                        InlineAsmOperand::In { reg, value } => {
950                            write!(fmt, "in({reg}) {value:?}")?;
951                        }
952                        InlineAsmOperand::Out { reg, late, place: Some(place) } => {
953                            write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
954                        }
955                        InlineAsmOperand::Out { reg, late, place: None } => {
956                            write!(fmt, "{}out({}) _", print_late(late), reg)?;
957                        }
958                        InlineAsmOperand::InOut {
959                            reg,
960                            late,
961                            in_value,
962                            out_place: Some(out_place),
963                        } => {
964                            write!(
965                                fmt,
966                                "in{}out({}) {:?} => {:?}",
967                                print_late(late),
968                                reg,
969                                in_value,
970                                out_place
971                            )?;
972                        }
973                        InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
974                            write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
975                        }
976                        InlineAsmOperand::Const { value } => {
977                            write!(fmt, "const {value:?}")?;
978                        }
979                        InlineAsmOperand::SymFn { value } => {
980                            write!(fmt, "sym_fn {value:?}")?;
981                        }
982                        InlineAsmOperand::SymStatic { def_id } => {
983                            write!(fmt, "sym_static {def_id:?}")?;
984                        }
985                        InlineAsmOperand::Label { target_index } => {
986                            write!(fmt, "label {target_index}")?;
987                        }
988                    }
989                }
990                write!(fmt, ", options({options:?}))")
991            }
992        }
993    }
994
995    /// Returns the list of labels for the edges to the successor basic blocks.
996    pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
997        use self::TerminatorKind::*;
998        match *self {
999            Return
1000            | TailCall { .. }
1001            | UnwindResume
1002            | UnwindTerminate(_)
1003            | Unreachable
1004            | CoroutineDrop => vec![],
1005            Goto { .. } => vec!["".into()],
1006            SwitchInt { ref targets, .. } => targets
1007                .values
1008                .iter()
1009                .map(|&u| Cow::Owned(u.to_string()))
1010                .chain(iter::once("otherwise".into()))
1011                .collect(),
1012            Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1013                vec!["return".into(), "unwind".into()]
1014            }
1015            Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
1016            Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
1017            Call { target: None, unwind: _, .. } => vec![],
1018            Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1019            Yield { drop: None, .. } => vec!["resume".into()],
1020            Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1021                vec!["return".into(), "unwind".into(), "drop".into()]
1022            }
1023            Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1024                vec!["return".into(), "unwind".into()]
1025            }
1026            Drop { unwind: _, drop: Some(_), .. } => vec!["return".into(), "drop".into()],
1027            Drop { unwind: _, .. } => vec!["return".into()],
1028            Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1029                vec!["success".into(), "unwind".into()]
1030            }
1031            Assert { unwind: _, .. } => vec!["success".into()],
1032            FalseEdge { .. } => vec!["real".into(), "imaginary".into()],
1033            FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1034                vec!["real".into(), "unwind".into()]
1035            }
1036            FalseUnwind { unwind: _, .. } => vec!["real".into()],
1037            InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1038                let mut vec = Vec::with_capacity(targets.len() + 1);
1039                if !asm_macro.diverges(options) {
1040                    vec.push("return".into());
1041                }
1042                vec.resize(targets.len(), "label".into());
1043
1044                if let UnwindAction::Cleanup(_) = unwind {
1045                    vec.push("unwind".into());
1046                }
1047
1048                vec
1049            }
1050        }
1051    }
1052}
1053
1054impl<'tcx> Debug for Rvalue<'tcx> {
1055    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1056        use self::Rvalue::*;
1057
1058        match *self {
1059            Use(ref place) => write!(fmt, "{place:?}"),
1060            Repeat(ref a, b) => {
1061                write!(fmt, "[{a:?}; ")?;
1062                pretty_print_const(b, fmt, false)?;
1063                write!(fmt, "]")
1064            }
1065            Cast(ref kind, ref place, ref ty) => {
1066                with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1067            }
1068            BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
1069            UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
1070            Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
1071            NullaryOp(ref op, ref t) => {
1072                let t = with_no_trimmed_paths!(format!("{}", t));
1073                match op {
1074                    NullOp::SizeOf => write!(fmt, "SizeOf({t})"),
1075                    NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
1076                    NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
1077                    NullOp::UbChecks => write!(fmt, "UbChecks()"),
1078                    NullOp::ContractChecks => write!(fmt, "ContractChecks()"),
1079                }
1080            }
1081            ThreadLocalRef(did) => ty::tls::with(|tcx| {
1082                let muta = tcx.static_mutability(did).unwrap().prefix_str();
1083                write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1084            }),
1085            Ref(region, borrow_kind, ref place) => {
1086                let kind_str = match borrow_kind {
1087                    BorrowKind::Shared => "",
1088                    BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1089                    BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1090                    BorrowKind::Mut { .. } => "mut ",
1091                };
1092
1093                // When printing regions, add trailing space if necessary.
1094                let print_region = ty::tls::with(|tcx| {
1095                    tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1096                });
1097                let region = if print_region {
1098                    let mut region = region.to_string();
1099                    if !region.is_empty() {
1100                        region.push(' ');
1101                    }
1102                    region
1103                } else {
1104                    // Do not even print 'static
1105                    String::new()
1106                };
1107                write!(fmt, "&{region}{kind_str}{place:?}")
1108            }
1109
1110            CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"),
1111
1112            RawPtr(mutability, ref place) => {
1113                write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1114            }
1115
1116            Aggregate(ref kind, ref places) => {
1117                let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1118                    let mut tuple_fmt = fmt.debug_tuple(name);
1119                    for place in places {
1120                        tuple_fmt.field(place);
1121                    }
1122                    tuple_fmt.finish()
1123                };
1124
1125                match **kind {
1126                    AggregateKind::Array(_) => write!(fmt, "{places:?}"),
1127
1128                    AggregateKind::Tuple => {
1129                        if places.is_empty() {
1130                            write!(fmt, "()")
1131                        } else {
1132                            fmt_tuple(fmt, "")
1133                        }
1134                    }
1135
1136                    AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1137                        ty::tls::with(|tcx| {
1138                            let variant_def = &tcx.adt_def(adt_did).variant(variant);
1139                            let args = tcx.lift(args).expect("could not lift for printing");
1140                            let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |p| {
1141                                p.print_def_path(variant_def.def_id, args)
1142                            })?;
1143
1144                            match variant_def.ctor_kind() {
1145                                Some(CtorKind::Const) => fmt.write_str(&name),
1146                                Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1147                                None => {
1148                                    let mut struct_fmt = fmt.debug_struct(&name);
1149                                    for (field, place) in iter::zip(&variant_def.fields, places) {
1150                                        struct_fmt.field(field.name.as_str(), place);
1151                                    }
1152                                    struct_fmt.finish()
1153                                }
1154                            }
1155                        })
1156                    }
1157
1158                    AggregateKind::Closure(def_id, args)
1159                    | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1160                        let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1161                            let args = tcx.lift(args).unwrap();
1162                            format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1163                        } else {
1164                            let span = tcx.def_span(def_id);
1165                            format!(
1166                                "{{closure@{}}}",
1167                                tcx.sess.source_map().span_to_diagnostic_string(span)
1168                            )
1169                        };
1170                        let mut struct_fmt = fmt.debug_struct(&name);
1171
1172                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1173                        if let Some(def_id) = def_id.as_local()
1174                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1175                        {
1176                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1177                                let var_name = tcx.hir_name(var_id);
1178                                struct_fmt.field(var_name.as_str(), place);
1179                            }
1180                        } else {
1181                            for (index, place) in places.iter().enumerate() {
1182                                struct_fmt.field(&format!("{index}"), place);
1183                            }
1184                        }
1185
1186                        struct_fmt.finish()
1187                    }),
1188
1189                    AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1190                        let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1191                        let mut struct_fmt = fmt.debug_struct(&name);
1192
1193                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1194                        if let Some(def_id) = def_id.as_local()
1195                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1196                        {
1197                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1198                                let var_name = tcx.hir_name(var_id);
1199                                struct_fmt.field(var_name.as_str(), place);
1200                            }
1201                        } else {
1202                            for (index, place) in places.iter().enumerate() {
1203                                struct_fmt.field(&format!("{index}"), place);
1204                            }
1205                        }
1206
1207                        struct_fmt.finish()
1208                    }),
1209
1210                    AggregateKind::RawPtr(pointee_ty, mutability) => {
1211                        let kind_str = match mutability {
1212                            Mutability::Mut => "mut",
1213                            Mutability::Not => "const",
1214                        };
1215                        with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1216                        fmt_tuple(fmt, "")
1217                    }
1218                }
1219            }
1220
1221            ShallowInitBox(ref place, ref ty) => {
1222                with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
1223            }
1224
1225            WrapUnsafeBinder(ref op, ty) => {
1226                with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1227            }
1228        }
1229    }
1230}
1231
1232impl<'tcx> Debug for Operand<'tcx> {
1233    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1234        use self::Operand::*;
1235        match *self {
1236            Constant(ref a) => write!(fmt, "{a:?}"),
1237            Copy(ref place) => write!(fmt, "copy {place:?}"),
1238            Move(ref place) => write!(fmt, "move {place:?}"),
1239        }
1240    }
1241}
1242
1243impl<'tcx> Debug for ConstOperand<'tcx> {
1244    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1245        write!(fmt, "{self}")
1246    }
1247}
1248
1249impl<'tcx> Display for ConstOperand<'tcx> {
1250    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1251        match self.ty().kind() {
1252            ty::FnDef(..) => {}
1253            _ => write!(fmt, "const ")?,
1254        }
1255        Display::fmt(&self.const_, fmt)
1256    }
1257}
1258
1259impl Debug for Place<'_> {
1260    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1261        self.as_ref().fmt(fmt)
1262    }
1263}
1264
1265impl Debug for PlaceRef<'_> {
1266    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1267        pre_fmt_projection(self.projection, fmt)?;
1268        write!(fmt, "{:?}", self.local)?;
1269        post_fmt_projection(self.projection, fmt)
1270    }
1271}
1272
1273fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1274    for &elem in projection.iter().rev() {
1275        match elem {
1276            ProjectionElem::OpaqueCast(_)
1277            | ProjectionElem::Subtype(_)
1278            | ProjectionElem::Downcast(_, _)
1279            | ProjectionElem::Field(_, _) => {
1280                write!(fmt, "(")?;
1281            }
1282            ProjectionElem::Deref => {
1283                write!(fmt, "(*")?;
1284            }
1285            ProjectionElem::Index(_)
1286            | ProjectionElem::ConstantIndex { .. }
1287            | ProjectionElem::Subslice { .. } => {}
1288            ProjectionElem::UnwrapUnsafeBinder(_) => {
1289                write!(fmt, "unwrap_binder!(")?;
1290            }
1291        }
1292    }
1293
1294    Ok(())
1295}
1296
1297fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1298    for &elem in projection.iter() {
1299        match elem {
1300            ProjectionElem::OpaqueCast(ty) => {
1301                write!(fmt, " as {ty})")?;
1302            }
1303            ProjectionElem::Subtype(ty) => {
1304                write!(fmt, " as subtype {ty})")?;
1305            }
1306            ProjectionElem::Downcast(Some(name), _index) => {
1307                write!(fmt, " as {name})")?;
1308            }
1309            ProjectionElem::Downcast(None, index) => {
1310                write!(fmt, " as variant#{index:?})")?;
1311            }
1312            ProjectionElem::Deref => {
1313                write!(fmt, ")")?;
1314            }
1315            ProjectionElem::Field(field, ty) => {
1316                with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1317            }
1318            ProjectionElem::Index(ref index) => {
1319                write!(fmt, "[{index:?}]")?;
1320            }
1321            ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1322                write!(fmt, "[{offset:?} of {min_length:?}]")?;
1323            }
1324            ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1325                write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1326            }
1327            ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1328                write!(fmt, "[{from:?}:]")?;
1329            }
1330            ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1331                write!(fmt, "[:-{to:?}]")?;
1332            }
1333            ProjectionElem::Subslice { from, to, from_end: true } => {
1334                write!(fmt, "[{from:?}:-{to:?}]")?;
1335            }
1336            ProjectionElem::Subslice { from, to, from_end: false } => {
1337                write!(fmt, "[{from:?}..{to:?}]")?;
1338            }
1339            ProjectionElem::UnwrapUnsafeBinder(ty) => {
1340                write!(fmt, "; {ty})")?;
1341            }
1342        }
1343    }
1344
1345    Ok(())
1346}
1347
1348/// After we print the main statement, we sometimes dump extra
1349/// information. There's often a lot of little things "nuzzled up" in
1350/// a statement.
1351fn write_extra<'tcx>(
1352    tcx: TyCtxt<'tcx>,
1353    write: &mut dyn io::Write,
1354    visit_op: &dyn Fn(&mut ExtraComments<'tcx>),
1355    options: PrettyPrintMirOptions,
1356) -> io::Result<()> {
1357    if options.include_extra_comments {
1358        let mut extra_comments = ExtraComments { tcx, comments: vec![] };
1359        visit_op(&mut extra_comments);
1360        for comment in extra_comments.comments {
1361            writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1362        }
1363    }
1364    Ok(())
1365}
1366
1367struct ExtraComments<'tcx> {
1368    tcx: TyCtxt<'tcx>,
1369    comments: Vec<String>,
1370}
1371
1372impl<'tcx> ExtraComments<'tcx> {
1373    fn push(&mut self, lines: &str) {
1374        for line in lines.split('\n') {
1375            self.comments.push(line.to_string());
1376        }
1377    }
1378}
1379
1380fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1381    match *ty.kind() {
1382        ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1383        // Unit type
1384        ty::Tuple(g_args) if g_args.is_empty() => false,
1385        ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1386        ty::Array(ty, _) => use_verbose(ty, fn_def),
1387        ty::FnDef(..) => fn_def,
1388        _ => true,
1389    }
1390}
1391
1392impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1393    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1394        let ConstOperand { span, user_ty, const_ } = constant;
1395        if use_verbose(const_.ty(), true) {
1396            self.push("mir::ConstOperand");
1397            self.push(&format!(
1398                "+ span: {}",
1399                self.tcx.sess.source_map().span_to_embeddable_string(*span)
1400            ));
1401            if let Some(user_ty) = user_ty {
1402                self.push(&format!("+ user_ty: {user_ty:?}"));
1403            }
1404
1405            let fmt_val = |val: ConstValue, ty: Ty<'tcx>| {
1406                let tcx = self.tcx;
1407                rustc_data_structures::make_display(move |fmt| {
1408                    pretty_print_const_value_tcx(tcx, val, ty, fmt)
1409                })
1410            };
1411
1412            let fmt_valtree = |cv: &ty::Value<'tcx>| {
1413                let mut p = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1414                p.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1415                p.into_buffer()
1416            };
1417
1418            let val = match const_ {
1419                Const::Ty(_, ct) => match ct.kind() {
1420                    ty::ConstKind::Param(p) => format!("ty::Param({p})"),
1421                    ty::ConstKind::Unevaluated(uv) => {
1422                        format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1423                    }
1424                    ty::ConstKind::Value(cv) => {
1425                        format!("ty::Valtree({})", fmt_valtree(&cv))
1426                    }
1427                    // No `ty::` prefix since we also use this to represent errors from `mir::Unevaluated`.
1428                    ty::ConstKind::Error(_) => "Error".to_string(),
1429                    // These variants shouldn't exist in the MIR.
1430                    ty::ConstKind::Placeholder(_)
1431                    | ty::ConstKind::Infer(_)
1432                    | ty::ConstKind::Expr(_)
1433                    | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", const_),
1434                },
1435                Const::Unevaluated(uv, _) => {
1436                    format!(
1437                        "Unevaluated({}, {:?}, {:?})",
1438                        self.tcx.def_path_str(uv.def),
1439                        uv.args,
1440                        uv.promoted,
1441                    )
1442                }
1443                Const::Val(val, ty) => format!("Value({})", fmt_val(*val, *ty)),
1444            };
1445
1446            // This reflects what `Const` looked liked before `val` was renamed
1447            // as `kind`. We print it like this to avoid having to update
1448            // expected output in a lot of tests.
1449            self.push(&format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1450        }
1451    }
1452
1453    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1454        self.super_rvalue(rvalue, location);
1455        if let Rvalue::Aggregate(kind, _) = rvalue {
1456            match **kind {
1457                AggregateKind::Closure(def_id, args) => {
1458                    self.push("closure");
1459                    self.push(&format!("+ def_id: {def_id:?}"));
1460                    self.push(&format!("+ args: {args:#?}"));
1461                }
1462
1463                AggregateKind::Coroutine(def_id, args) => {
1464                    self.push("coroutine");
1465                    self.push(&format!("+ def_id: {def_id:?}"));
1466                    self.push(&format!("+ args: {args:#?}"));
1467                    self.push(&format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1468                }
1469
1470                AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1471                    self.push("adt");
1472                    self.push(&format!("+ user_ty: {user_ty:?}"));
1473                }
1474
1475                _ => {}
1476            }
1477        }
1478    }
1479}
1480
1481fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1482    let location = tcx.sess.source_map().span_to_embeddable_string(span);
1483    format!("scope {} at {}", scope.index(), location,)
1484}
1485
1486///////////////////////////////////////////////////////////////////////////
1487// Allocations
1488
1489/// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
1490/// allocations.
1491pub fn write_allocations<'tcx>(
1492    tcx: TyCtxt<'tcx>,
1493    body: &Body<'_>,
1494    w: &mut dyn io::Write,
1495) -> io::Result<()> {
1496    fn alloc_ids_from_alloc(
1497        alloc: ConstAllocation<'_>,
1498    ) -> impl DoubleEndedIterator<Item = AllocId> {
1499        alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1500    }
1501
1502    fn alloc_id_from_const_val(val: ConstValue) -> Option<AllocId> {
1503        match val {
1504            ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1505            ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1506            ConstValue::ZeroSized => None,
1507            ConstValue::Slice { alloc_id, .. } | ConstValue::Indirect { alloc_id, .. } => {
1508                // FIXME: we don't actually want to print all of these, since some are printed nicely directly as values inline in MIR.
1509                // Really we'd want `pretty_print_const_value` to decide which allocations to print, instead of having a separate visitor.
1510                Some(alloc_id)
1511            }
1512        }
1513    }
1514    struct CollectAllocIds(BTreeSet<AllocId>);
1515
1516    impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1517        fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1518            match c.const_ {
1519                Const::Ty(_, _) | Const::Unevaluated(..) => {}
1520                Const::Val(val, _) => {
1521                    if let Some(id) = alloc_id_from_const_val(val) {
1522                        self.0.insert(id);
1523                    }
1524                }
1525            }
1526        }
1527    }
1528
1529    let mut visitor = CollectAllocIds(Default::default());
1530    visitor.visit_body(body);
1531
1532    // `seen` contains all seen allocations, including the ones we have *not* printed yet.
1533    // The protocol is to first `insert` into `seen`, and only if that returns `true`
1534    // then push to `todo`.
1535    let mut seen = visitor.0;
1536    let mut todo: Vec<_> = seen.iter().copied().collect();
1537    while let Some(id) = todo.pop() {
1538        let mut write_allocation_track_relocs =
1539            |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1540                // `.rev()` because we are popping them from the back of the `todo` vector.
1541                for id in alloc_ids_from_alloc(alloc).rev() {
1542                    if seen.insert(id) {
1543                        todo.push(id);
1544                    }
1545                }
1546                write!(w, "{}", display_allocation(tcx, alloc.inner()))
1547            };
1548        write!(w, "\n{id:?}")?;
1549        match tcx.try_get_global_alloc(id) {
1550            // This can't really happen unless there are bugs, but it doesn't cost us anything to
1551            // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
1552            None => write!(w, " (deallocated)")?,
1553            Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?,
1554            Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1555                write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1556            }
1557            Some(GlobalAlloc::TypeId { ty }) => write!(w, " (typeid for {ty})")?,
1558            Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1559                write!(w, " (static: {}", tcx.def_path_str(did))?;
1560                if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1561                    && body
1562                        .source
1563                        .def_id()
1564                        .as_local()
1565                        .is_some_and(|def_id| tcx.hir_body_const_context(def_id).is_some())
1566                {
1567                    // Statics may be cyclic and evaluating them too early
1568                    // in the MIR pipeline may cause cycle errors even though
1569                    // normal compilation is fine.
1570                    write!(w, ")")?;
1571                } else {
1572                    match tcx.eval_static_initializer(did) {
1573                        Ok(alloc) => {
1574                            write!(w, ", ")?;
1575                            write_allocation_track_relocs(w, alloc)?;
1576                        }
1577                        Err(_) => write!(w, ", error during initializer evaluation)")?,
1578                    }
1579                }
1580            }
1581            Some(GlobalAlloc::Static(did)) => {
1582                write!(w, " (extern static: {})", tcx.def_path_str(did))?
1583            }
1584            Some(GlobalAlloc::Memory(alloc)) => {
1585                write!(w, " (")?;
1586                write_allocation_track_relocs(w, alloc)?
1587            }
1588        }
1589        writeln!(w)?;
1590    }
1591    Ok(())
1592}
1593
1594/// Dumps the size and metadata and content of an allocation to the given writer.
1595/// The expectation is that the caller first prints other relevant metadata, so the exact
1596/// format of this function is (*without* leading or trailing newline):
1597///
1598/// ```text
1599/// size: {}, align: {}) {
1600///     <bytes>
1601/// }
1602/// ```
1603///
1604/// The byte format is similar to how hex editors print bytes. Each line starts with the address of
1605/// the start of the line, followed by all bytes in hex format (space separated).
1606/// If the allocation is small enough to fit into a single line, no start address is given.
1607/// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
1608/// characters or characters whose value is larger than 127) with a `.`
1609/// This also prints provenance adequately.
1610pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1611    tcx: TyCtxt<'tcx>,
1612    alloc: &'a Allocation<Prov, Extra, Bytes>,
1613) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1614    RenderAllocation { tcx, alloc }
1615}
1616
1617#[doc(hidden)]
1618pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1619    tcx: TyCtxt<'tcx>,
1620    alloc: &'a Allocation<Prov, Extra, Bytes>,
1621}
1622
1623impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1624    for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1625{
1626    fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1627        let RenderAllocation { tcx, alloc } = *self;
1628        write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1629        if alloc.size() == Size::ZERO {
1630            // We are done.
1631            return write!(w, " {{}}");
1632        }
1633        if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1634            return write!(w, " {{ .. }}");
1635        }
1636        // Write allocation bytes.
1637        writeln!(w, " {{")?;
1638        write_allocation_bytes(tcx, alloc, w, "    ")?;
1639        write!(w, "}}")?;
1640        Ok(())
1641    }
1642}
1643
1644fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1645    for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1646        write!(w, "   ")?;
1647    }
1648    writeln!(w, " │ {ascii}")
1649}
1650
1651/// Number of bytes to print per allocation hex dump line.
1652const BYTES_PER_LINE: usize = 16;
1653
1654/// Prints the line start address and returns the new line start address.
1655fn write_allocation_newline(
1656    w: &mut dyn std::fmt::Write,
1657    mut line_start: Size,
1658    ascii: &str,
1659    pos_width: usize,
1660    prefix: &str,
1661) -> Result<Size, std::fmt::Error> {
1662    write_allocation_endline(w, ascii)?;
1663    line_start += Size::from_bytes(BYTES_PER_LINE);
1664    write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1665    Ok(line_start)
1666}
1667
1668/// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
1669/// is only one line). Note that your prefix should contain a trailing space as the lines are
1670/// printed directly after it.
1671pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1672    tcx: TyCtxt<'tcx>,
1673    alloc: &Allocation<Prov, Extra, Bytes>,
1674    w: &mut dyn std::fmt::Write,
1675    prefix: &str,
1676) -> std::fmt::Result {
1677    let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1678    // Number of chars needed to represent all line numbers.
1679    let pos_width = hex_number_length(alloc.size().bytes());
1680
1681    if num_lines > 0 {
1682        write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1683    } else {
1684        write!(w, "{prefix}")?;
1685    }
1686
1687    let mut i = Size::ZERO;
1688    let mut line_start = Size::ZERO;
1689
1690    let ptr_size = tcx.data_layout.pointer_size();
1691
1692    let mut ascii = String::new();
1693
1694    let oversized_ptr = |target: &mut String, width| {
1695        if target.len() > width {
1696            write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1697        }
1698    };
1699
1700    while i < alloc.size() {
1701        // The line start already has a space. While we could remove that space from the line start
1702        // printing and unconditionally print a space here, that would cause the single-line case
1703        // to have a single space before it, which looks weird.
1704        if i != line_start {
1705            write!(w, " ")?;
1706        }
1707        if let Some(prov) = alloc.provenance().get_ptr(i) {
1708            // Memory with provenance must be defined
1709            assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1710            let j = i.bytes_usize();
1711            let offset = alloc
1712                .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1713            let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1714            let offset = Size::from_bytes(offset);
1715            let provenance_width = |bytes| bytes * 3;
1716            let ptr = Pointer::new(prov, offset);
1717            let mut target = format!("{ptr:?}");
1718            if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1719                // This is too long, try to save some space.
1720                target = format!("{ptr:#?}");
1721            }
1722            if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1723                // This branch handles the situation where a provenance starts in the current line
1724                // but ends in the next one.
1725                let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1726                let overflow = ptr_size - remainder;
1727                let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1728                let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1729                ascii.push('╾'); // HEAVY LEFT AND LIGHT RIGHT
1730                for _ in 1..remainder.bytes() {
1731                    ascii.push('─'); // LIGHT HORIZONTAL
1732                }
1733                if overflow_width > remainder_width && overflow_width >= target.len() {
1734                    // The case where the provenance fits into the part in the next line
1735                    write!(w, "╾{0:─^1$}", "", remainder_width)?;
1736                    line_start =
1737                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1738                    ascii.clear();
1739                    write!(w, "{target:─^overflow_width$}╼")?;
1740                } else {
1741                    oversized_ptr(&mut target, remainder_width);
1742                    write!(w, "╾{target:─^remainder_width$}")?;
1743                    line_start =
1744                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1745                    write!(w, "{0:─^1$}╼", "", overflow_width)?;
1746                    ascii.clear();
1747                }
1748                for _ in 0..overflow.bytes() - 1 {
1749                    ascii.push('─');
1750                }
1751                ascii.push('╼'); // LIGHT LEFT AND HEAVY RIGHT
1752                i += ptr_size;
1753                continue;
1754            } else {
1755                // This branch handles a provenance that starts and ends in the current line.
1756                let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1757                oversized_ptr(&mut target, provenance_width);
1758                ascii.push('╾');
1759                write!(w, "╾{target:─^provenance_width$}╼")?;
1760                for _ in 0..ptr_size.bytes() - 2 {
1761                    ascii.push('─');
1762                }
1763                ascii.push('╼');
1764                i += ptr_size;
1765            }
1766        } else if let Some((prov, idx)) = alloc.provenance().get_byte(i, &tcx) {
1767            // Memory with provenance must be defined
1768            assert!(
1769                alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1770            );
1771            ascii.push('━'); // HEAVY HORIZONTAL
1772            // We have two characters to display this, which is obviously not enough.
1773            // Format is similar to "oversized" above.
1774            let j = i.bytes_usize();
1775            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1776            write!(w, "╾{c:02x}{prov:#?} (ptr fragment {idx})╼")?;
1777            i += Size::from_bytes(1);
1778        } else if alloc
1779            .init_mask()
1780            .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1781            .is_ok()
1782        {
1783            let j = i.bytes_usize();
1784
1785            // Checked definedness (and thus range) and provenance. This access also doesn't
1786            // influence interpreter execution but is only for debugging.
1787            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1788            write!(w, "{c:02x}")?;
1789            if c.is_ascii_control() || c >= 0x80 {
1790                ascii.push('.');
1791            } else {
1792                ascii.push(char::from(c));
1793            }
1794            i += Size::from_bytes(1);
1795        } else {
1796            write!(w, "__")?;
1797            ascii.push('░');
1798            i += Size::from_bytes(1);
1799        }
1800        // Print a new line header if the next line still has some bytes to print.
1801        if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1802            line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1803            ascii.clear();
1804        }
1805    }
1806    write_allocation_endline(w, &ascii)?;
1807
1808    Ok(())
1809}
1810
1811///////////////////////////////////////////////////////////////////////////
1812// Constants
1813
1814fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1815    write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1816}
1817
1818fn comma_sep<'tcx>(
1819    tcx: TyCtxt<'tcx>,
1820    fmt: &mut Formatter<'_>,
1821    elems: Vec<(ConstValue, Ty<'tcx>)>,
1822) -> fmt::Result {
1823    let mut first = true;
1824    for (ct, ty) in elems {
1825        if !first {
1826            fmt.write_str(", ")?;
1827        }
1828        pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1829        first = false;
1830    }
1831    Ok(())
1832}
1833
1834fn pretty_print_const_value_tcx<'tcx>(
1835    tcx: TyCtxt<'tcx>,
1836    ct: ConstValue,
1837    ty: Ty<'tcx>,
1838    fmt: &mut Formatter<'_>,
1839) -> fmt::Result {
1840    use crate::ty::print::PrettyPrinter;
1841
1842    if tcx.sess.verbose_internals() {
1843        fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?;
1844        return Ok(());
1845    }
1846
1847    let u8_type = tcx.types.u8;
1848    match (ct, ty.kind()) {
1849        // Byte/string slices, printed as (byte) string literals.
1850        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1851            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1852                fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?;
1853                return Ok(());
1854            }
1855        }
1856        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => {
1857            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1858                pretty_print_byte_str(fmt, data)?;
1859                return Ok(());
1860            }
1861        }
1862        (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1863            let n = n.try_to_target_usize(tcx).unwrap();
1864            let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1865            // cast is ok because we already checked for pointer size (32 or 64 bit) above
1866            let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1867            let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1868            fmt.write_str("*")?;
1869            pretty_print_byte_str(fmt, byte_str)?;
1870            return Ok(());
1871        }
1872        // Aggregates, printed as array/tuple/struct/variant construction syntax.
1873        //
1874        // NB: the `has_non_region_param` check ensures that we can use
1875        // the `destructure_const` query with an empty `ty::ParamEnv` without
1876        // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1877        // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1878        // to be able to destructure the tuple into `(0u8, *mut T)`
1879        (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1880            let ct = tcx.lift(ct).unwrap();
1881            let ty = tcx.lift(ty).unwrap();
1882            if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1883                let fields: Vec<(ConstValue, Ty<'_>)> = contents.fields.to_vec();
1884                match *ty.kind() {
1885                    ty::Array(..) => {
1886                        fmt.write_str("[")?;
1887                        comma_sep(tcx, fmt, fields)?;
1888                        fmt.write_str("]")?;
1889                    }
1890                    ty::Tuple(..) => {
1891                        fmt.write_str("(")?;
1892                        comma_sep(tcx, fmt, fields)?;
1893                        if contents.fields.len() == 1 {
1894                            fmt.write_str(",")?;
1895                        }
1896                        fmt.write_str(")")?;
1897                    }
1898                    ty::Adt(def, _) if def.variants().is_empty() => {
1899                        fmt.write_str(&format!("{{unreachable(): {ty}}}"))?;
1900                    }
1901                    ty::Adt(def, args) => {
1902                        let variant_idx = contents
1903                            .variant
1904                            .expect("destructed mir constant of adt without variant idx");
1905                        let variant_def = &def.variant(variant_idx);
1906                        let args = tcx.lift(args).unwrap();
1907                        let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1908                        p.print_alloc_ids = true;
1909                        p.pretty_print_value_path(variant_def.def_id, args)?;
1910                        fmt.write_str(&p.into_buffer())?;
1911
1912                        match variant_def.ctor_kind() {
1913                            Some(CtorKind::Const) => {}
1914                            Some(CtorKind::Fn) => {
1915                                fmt.write_str("(")?;
1916                                comma_sep(tcx, fmt, fields)?;
1917                                fmt.write_str(")")?;
1918                            }
1919                            None => {
1920                                fmt.write_str(" {{ ")?;
1921                                let mut first = true;
1922                                for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
1923                                {
1924                                    if !first {
1925                                        fmt.write_str(", ")?;
1926                                    }
1927                                    write!(fmt, "{}: ", field_def.name)?;
1928                                    pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1929                                    first = false;
1930                                }
1931                                fmt.write_str(" }}")?;
1932                            }
1933                        }
1934                    }
1935                    _ => unreachable!(),
1936                }
1937                return Ok(());
1938            }
1939        }
1940        (ConstValue::Scalar(scalar), _) => {
1941            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1942            p.print_alloc_ids = true;
1943            let ty = tcx.lift(ty).unwrap();
1944            p.pretty_print_const_scalar(scalar, ty)?;
1945            fmt.write_str(&p.into_buffer())?;
1946            return Ok(());
1947        }
1948        (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
1949            let mut p = FmtPrinter::new(tcx, Namespace::ValueNS);
1950            p.print_alloc_ids = true;
1951            p.pretty_print_value_path(*d, s)?;
1952            fmt.write_str(&p.into_buffer())?;
1953            return Ok(());
1954        }
1955        // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1956        // their fields instead of just dumping the memory.
1957        _ => {}
1958    }
1959    // Fall back to debug pretty printing for invalid constants.
1960    write!(fmt, "{ct:?}: {ty}")
1961}
1962
1963pub(crate) fn pretty_print_const_value<'tcx>(
1964    ct: ConstValue,
1965    ty: Ty<'tcx>,
1966    fmt: &mut Formatter<'_>,
1967) -> fmt::Result {
1968    ty::tls::with(|tcx| {
1969        let ct = tcx.lift(ct).unwrap();
1970        let ty = tcx.lift(ty).unwrap();
1971        pretty_print_const_value_tcx(tcx, ct, ty, fmt)
1972    })
1973}
1974
1975///////////////////////////////////////////////////////////////////////////
1976// Miscellaneous
1977
1978/// Calc converted u64 decimal into hex and return its length in chars.
1979///
1980/// ```ignore (cannot-test-private-function)
1981/// assert_eq!(1, hex_number_length(0));
1982/// assert_eq!(1, hex_number_length(1));
1983/// assert_eq!(2, hex_number_length(16));
1984/// ```
1985fn hex_number_length(x: u64) -> usize {
1986    if x == 0 {
1987        return 1;
1988    }
1989    let mut length = 0;
1990    let mut x_left = x;
1991    while x_left > 0 {
1992        x_left /= 16;
1993        length += 1;
1994    }
1995    length
1996}