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_with_options`].
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/// If the session is properly configured, dumps a human-readable representation of the MIR (with
62/// default pretty-printing options) into:
63///
64/// ```text
65/// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
66/// ```
67///
68/// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
69/// where `<filter>` takes the following forms:
70///
71/// - `all` -- dump MIR for all fns, all passes, all everything
72/// - a filter defined by a set of substrings combined with `&` and `|`
73///   (`&` has higher precedence). At least one of the `|`-separated groups
74///   must match; an `|`-separated group matches if all of its `&`-separated
75///   substrings are matched.
76///
77/// Example:
78///
79/// - `nll` == match if `nll` appears in the name
80/// - `foo & nll` == match if `foo` and `nll` both appear in the name
81/// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
82///   or `typeck` appears in the name.
83/// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
84///   or `typeck` and `bar` both appear in the name.
85#[inline]
86pub fn dump_mir<'tcx, F>(
87    tcx: TyCtxt<'tcx>,
88    pass_num: bool,
89    pass_name: &str,
90    disambiguator: &dyn Display,
91    body: &Body<'tcx>,
92    extra_data: F,
93) where
94    F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
95{
96    dump_mir_with_options(
97        tcx,
98        pass_num,
99        pass_name,
100        disambiguator,
101        body,
102        extra_data,
103        PrettyPrintMirOptions::from_cli(tcx),
104    );
105}
106
107/// If the session is properly configured, dumps a human-readable representation of the MIR, with
108/// the given [pretty-printing options][PrettyPrintMirOptions].
109///
110/// See [`dump_mir`] for more details.
111///
112#[inline]
113pub fn dump_mir_with_options<'tcx, F>(
114    tcx: TyCtxt<'tcx>,
115    pass_num: bool,
116    pass_name: &str,
117    disambiguator: &dyn Display,
118    body: &Body<'tcx>,
119    extra_data: F,
120    options: PrettyPrintMirOptions,
121) where
122    F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
123{
124    if !dump_enabled(tcx, pass_name, body.source.def_id()) {
125        return;
126    }
127
128    dump_matched_mir_node(tcx, pass_num, pass_name, disambiguator, body, extra_data, options);
129}
130
131pub fn dump_enabled(tcx: TyCtxt<'_>, pass_name: &str, def_id: DefId) -> bool {
132    let Some(ref filters) = tcx.sess.opts.unstable_opts.dump_mir else {
133        return false;
134    };
135    // see notes on #41697 below
136    let node_path = ty::print::with_forced_impl_filename_line!(tcx.def_path_str(def_id));
137    filters.split('|').any(|or_filter| {
138        or_filter.split('&').all(|and_filter| {
139            let and_filter_trimmed = and_filter.trim();
140            and_filter_trimmed == "all"
141                || pass_name.contains(and_filter_trimmed)
142                || node_path.contains(and_filter_trimmed)
143        })
144    })
145}
146
147// #41697 -- we use `with_forced_impl_filename_line()` because
148// `def_path_str()` would otherwise trigger `type_of`, and this can
149// run while we are already attempting to evaluate `type_of`.
150
151/// Most use-cases of dumping MIR should use the [dump_mir] entrypoint instead, which will also
152/// check if dumping MIR is enabled, and if this body matches the filters passed on the CLI.
153///
154/// That being said, if the above requirements have been validated already, this function is where
155/// most of the MIR dumping occurs, if one needs to export it to a file they have created with
156/// [create_dump_file], rather than to a new file created as part of [dump_mir], or to stdout/stderr
157/// for debugging purposes.
158pub fn dump_mir_to_writer<'tcx, F>(
159    tcx: TyCtxt<'tcx>,
160    pass_name: &str,
161    disambiguator: &dyn Display,
162    body: &Body<'tcx>,
163    w: &mut dyn io::Write,
164    mut extra_data: F,
165    options: PrettyPrintMirOptions,
166) -> io::Result<()>
167where
168    F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
169{
170    // see notes on #41697 above
171    let def_path =
172        ty::print::with_forced_impl_filename_line!(tcx.def_path_str(body.source.def_id()));
173    // ignore-tidy-odd-backticks the literal below is fine
174    write!(w, "// MIR for `{def_path}")?;
175    match body.source.promoted {
176        None => write!(w, "`")?,
177        Some(promoted) => write!(w, "::{promoted:?}`")?,
178    }
179    writeln!(w, " {disambiguator} {pass_name}")?;
180    if let Some(ref layout) = body.coroutine_layout_raw() {
181        writeln!(w, "/* coroutine_layout = {layout:#?} */")?;
182    }
183    writeln!(w)?;
184    extra_data(PassWhere::BeforeCFG, w)?;
185    write_user_type_annotations(tcx, body, w)?;
186    write_mir_fn(tcx, body, &mut extra_data, w, options)?;
187    extra_data(PassWhere::AfterCFG, w)
188}
189
190fn dump_matched_mir_node<'tcx, F>(
191    tcx: TyCtxt<'tcx>,
192    pass_num: bool,
193    pass_name: &str,
194    disambiguator: &dyn Display,
195    body: &Body<'tcx>,
196    extra_data: F,
197    options: PrettyPrintMirOptions,
198) where
199    F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
200{
201    let _: io::Result<()> = try {
202        let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body)?;
203        dump_mir_to_writer(tcx, pass_name, disambiguator, body, &mut file, extra_data, options)?;
204    };
205
206    if tcx.sess.opts.unstable_opts.dump_mir_graphviz {
207        let _: io::Result<()> = try {
208            let mut file = create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, body)?;
209            write_mir_fn_graphviz(tcx, body, false, &mut file)?;
210        };
211    }
212}
213
214/// Returns the path to the filename where we should dump a given MIR.
215/// Also used by other bits of code (e.g., NLL inference) that dump
216/// graphviz data or other things.
217fn dump_path<'tcx>(
218    tcx: TyCtxt<'tcx>,
219    extension: &str,
220    pass_num: bool,
221    pass_name: &str,
222    disambiguator: &dyn Display,
223    body: &Body<'tcx>,
224) -> PathBuf {
225    let source = body.source;
226    let promotion_id = match source.promoted {
227        Some(id) => format!("-{id:?}"),
228        None => String::new(),
229    };
230
231    let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
232        String::new()
233    } else if pass_num {
234        let (dialect_index, phase_index) = body.phase.index();
235        format!(".{}-{}-{:03}", dialect_index, phase_index, body.pass_count)
236    } else {
237        ".-------".to_string()
238    };
239
240    let crate_name = tcx.crate_name(source.def_id().krate);
241    let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
242    // All drop shims have the same DefId, so we have to add the type
243    // to get unique file names.
244    let shim_disambiguator = match source.instance {
245        ty::InstanceKind::DropGlue(_, Some(ty)) => {
246            // Unfortunately, pretty-printed typed are not very filename-friendly.
247            // We dome some filtering.
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::AsyncDropGlueCtorShim(_, ty) => {
257            let mut s = ".".to_owned();
258            s.extend(ty.to_string().chars().filter_map(|c| match c {
259                ' ' => None,
260                ':' | '<' | '>' => Some('_'),
261                c => Some(c),
262            }));
263            s
264        }
265        ty::InstanceKind::AsyncDropGlue(_, ty) => {
266            let ty::Coroutine(_, args) = ty.kind() else {
267                bug!();
268            };
269            let ty = args.first().unwrap().expect_ty();
270            let mut s = ".".to_owned();
271            s.extend(ty.to_string().chars().filter_map(|c| match c {
272                ' ' => None,
273                ':' | '<' | '>' => Some('_'),
274                c => Some(c),
275            }));
276            s
277        }
278        ty::InstanceKind::FutureDropPollShim(_, proxy_cor, impl_cor) => {
279            let mut s = ".".to_owned();
280            s.extend(proxy_cor.to_string().chars().filter_map(|c| match c {
281                ' ' => None,
282                ':' | '<' | '>' => Some('_'),
283                c => Some(c),
284            }));
285            s.push('.');
286            s.extend(impl_cor.to_string().chars().filter_map(|c| match c {
287                ' ' => None,
288                ':' | '<' | '>' => Some('_'),
289                c => Some(c),
290            }));
291            s
292        }
293        _ => String::new(),
294    };
295
296    let mut file_path = PathBuf::new();
297    file_path.push(Path::new(&tcx.sess.opts.unstable_opts.dump_mir_dir));
298
299    let file_name = format!(
300        "{crate_name}.{item_name}{shim_disambiguator}{promotion_id}{pass_num}.{pass_name}.{disambiguator}.{extension}",
301    );
302
303    file_path.push(&file_name);
304
305    file_path
306}
307
308/// Attempts to open a file where we should dump a given MIR or other
309/// bit of MIR-related data. Used by `mir-dump`, but also by other
310/// bits of code (e.g., NLL inference) that dump graphviz data or
311/// other things, and hence takes the extension as an argument.
312pub fn create_dump_file<'tcx>(
313    tcx: TyCtxt<'tcx>,
314    extension: &str,
315    pass_num: bool,
316    pass_name: &str,
317    disambiguator: &dyn Display,
318    body: &Body<'tcx>,
319) -> io::Result<io::BufWriter<fs::File>> {
320    let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, body);
321    if let Some(parent) = file_path.parent() {
322        fs::create_dir_all(parent).map_err(|e| {
323            io::Error::new(
324                e.kind(),
325                format!("IO error creating MIR dump directory: {parent:?}; {e}"),
326            )
327        })?;
328    }
329    fs::File::create_buffered(&file_path).map_err(|e| {
330        io::Error::new(e.kind(), format!("IO error creating MIR dump file: {file_path:?}; {e}"))
331    })
332}
333
334///////////////////////////////////////////////////////////////////////////
335// Whole MIR bodies
336
337/// Write out a human-readable textual representation for the given MIR, with the default
338/// [PrettyPrintMirOptions].
339pub fn write_mir_pretty<'tcx>(
340    tcx: TyCtxt<'tcx>,
341    single: Option<DefId>,
342    w: &mut dyn io::Write,
343) -> io::Result<()> {
344    let options = PrettyPrintMirOptions::from_cli(tcx);
345
346    writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
347    writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
348    writeln!(w, "// HINT: See also -Z dump-mir for MIR at specific points during compilation.")?;
349
350    let mut first = true;
351    for def_id in dump_mir_def_ids(tcx, single) {
352        if first {
353            first = false;
354        } else {
355            // Put empty lines between all items
356            writeln!(w)?;
357        }
358
359        let render_body = |w: &mut dyn io::Write, body| -> io::Result<()> {
360            write_mir_fn(tcx, body, &mut |_, _| Ok(()), w, options)?;
361
362            for body in tcx.promoted_mir(def_id) {
363                writeln!(w)?;
364                write_mir_fn(tcx, body, &mut |_, _| Ok(()), w, options)?;
365            }
366            Ok(())
367        };
368
369        // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
370        if tcx.is_const_fn(def_id) {
371            render_body(w, tcx.optimized_mir(def_id))?;
372            writeln!(w)?;
373            writeln!(w, "// MIR FOR CTFE")?;
374            // Do not use `render_body`, as that would render the promoteds again, but these
375            // are shared between mir_for_ctfe and optimized_mir
376            write_mir_fn(tcx, tcx.mir_for_ctfe(def_id), &mut |_, _| Ok(()), w, options)?;
377        } else {
378            let instance_mir = tcx.instance_mir(ty::InstanceKind::Item(def_id));
379            render_body(w, instance_mir)?;
380        }
381    }
382    Ok(())
383}
384
385/// Write out a human-readable textual representation for the given function.
386pub fn write_mir_fn<'tcx, F>(
387    tcx: TyCtxt<'tcx>,
388    body: &Body<'tcx>,
389    extra_data: &mut F,
390    w: &mut dyn io::Write,
391    options: PrettyPrintMirOptions,
392) -> io::Result<()>
393where
394    F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
395{
396    write_mir_intro(tcx, body, w, options)?;
397    for block in body.basic_blocks.indices() {
398        extra_data(PassWhere::BeforeBlock(block), w)?;
399        write_basic_block(tcx, block, body, extra_data, w, options)?;
400        if block.index() + 1 != body.basic_blocks.len() {
401            writeln!(w)?;
402        }
403    }
404
405    writeln!(w, "}}")?;
406
407    write_allocations(tcx, body, w)?;
408
409    Ok(())
410}
411
412/// Prints local variables in a scope tree.
413fn write_scope_tree(
414    tcx: TyCtxt<'_>,
415    body: &Body<'_>,
416    scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
417    w: &mut dyn io::Write,
418    parent: SourceScope,
419    depth: usize,
420    options: PrettyPrintMirOptions,
421) -> io::Result<()> {
422    let indent = depth * INDENT.len();
423
424    // Local variable debuginfo.
425    for var_debug_info in &body.var_debug_info {
426        if var_debug_info.source_info.scope != parent {
427            // Not declared in this scope.
428            continue;
429        }
430
431        let indented_debug_info = format!("{0:1$}debug {2:?};", INDENT, indent, var_debug_info);
432
433        if options.include_extra_comments {
434            writeln!(
435                w,
436                "{0:1$} // in {2}",
437                indented_debug_info,
438                ALIGN,
439                comment(tcx, var_debug_info.source_info),
440            )?;
441        } else {
442            writeln!(w, "{indented_debug_info}")?;
443        }
444    }
445
446    // Local variable types.
447    for (local, local_decl) in body.local_decls.iter_enumerated() {
448        if (1..body.arg_count + 1).contains(&local.index()) {
449            // Skip over argument locals, they're printed in the signature.
450            continue;
451        }
452
453        if local_decl.source_info.scope != parent {
454            // Not declared in this scope.
455            continue;
456        }
457
458        let mut_str = local_decl.mutability.prefix_str();
459
460        let mut indented_decl = ty::print::with_no_trimmed_paths!(format!(
461            "{0:1$}let {2}{3:?}: {4}",
462            INDENT, indent, mut_str, local, local_decl.ty
463        ));
464        if let Some(user_ty) = &local_decl.user_ty {
465            for user_ty in user_ty.projections() {
466                write!(indented_decl, " as {user_ty:?}").unwrap();
467            }
468        }
469        indented_decl.push(';');
470
471        let local_name = if local == RETURN_PLACE { " return place" } else { "" };
472
473        if options.include_extra_comments {
474            writeln!(
475                w,
476                "{0:1$} //{2} in {3}",
477                indented_decl,
478                ALIGN,
479                local_name,
480                comment(tcx, local_decl.source_info),
481            )?;
482        } else {
483            writeln!(w, "{indented_decl}",)?;
484        }
485    }
486
487    let Some(children) = scope_tree.get(&parent) else {
488        return Ok(());
489    };
490
491    for &child in children {
492        let child_data = &body.source_scopes[child];
493        assert_eq!(child_data.parent_scope, Some(parent));
494
495        let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
496            (
497                format!(
498                    " (inlined {}{})",
499                    if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
500                    callee
501                ),
502                Some(callsite_span),
503            )
504        } else {
505            (String::new(), None)
506        };
507
508        let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
509
510        if options.include_extra_comments {
511            if let Some(span) = span {
512                writeln!(
513                    w,
514                    "{0:1$} // at {2}",
515                    indented_header,
516                    ALIGN,
517                    tcx.sess.source_map().span_to_embeddable_string(span),
518                )?;
519            } else {
520                writeln!(w, "{indented_header}")?;
521            }
522        } else {
523            writeln!(w, "{indented_header}")?;
524        }
525
526        write_scope_tree(tcx, body, scope_tree, w, child, depth + 1, options)?;
527        writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
528    }
529
530    Ok(())
531}
532
533impl Debug for VarDebugInfo<'_> {
534    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
535        if let Some(box VarDebugInfoFragment { ty, ref projection }) = self.composite {
536            pre_fmt_projection(&projection[..], fmt)?;
537            write!(fmt, "({}: {})", self.name, ty)?;
538            post_fmt_projection(&projection[..], fmt)?;
539        } else {
540            write!(fmt, "{}", self.name)?;
541        }
542
543        write!(fmt, " => {:?}", self.value)
544    }
545}
546
547/// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
548/// local variables (both user-defined bindings and compiler temporaries).
549fn write_mir_intro<'tcx>(
550    tcx: TyCtxt<'tcx>,
551    body: &Body<'_>,
552    w: &mut dyn io::Write,
553    options: PrettyPrintMirOptions,
554) -> io::Result<()> {
555    write_mir_sig(tcx, body, w)?;
556    writeln!(w, "{{")?;
557
558    // construct a scope tree and write it out
559    let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
560    for (index, scope_data) in body.source_scopes.iter_enumerated() {
561        if let Some(parent) = scope_data.parent_scope {
562            scope_tree.entry(parent).or_default().push(index);
563        } else {
564            // Only the argument scope has no parent, because it's the root.
565            assert_eq!(index, OUTERMOST_SOURCE_SCOPE);
566        }
567    }
568
569    write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1, options)?;
570
571    // Add an empty line before the first block is printed.
572    writeln!(w)?;
573
574    if let Some(coverage_info_hi) = &body.coverage_info_hi {
575        write_coverage_info_hi(coverage_info_hi, w)?;
576    }
577    if let Some(function_coverage_info) = &body.function_coverage_info {
578        write_function_coverage_info(function_coverage_info, w)?;
579    }
580
581    Ok(())
582}
583
584fn write_coverage_info_hi(
585    coverage_info_hi: &coverage::CoverageInfoHi,
586    w: &mut dyn io::Write,
587) -> io::Result<()> {
588    let coverage::CoverageInfoHi {
589        num_block_markers: _,
590        branch_spans,
591        mcdc_degraded_branch_spans,
592        mcdc_spans,
593    } = coverage_info_hi;
594
595    // Only add an extra trailing newline if we printed at least one thing.
596    let mut did_print = false;
597
598    for coverage::BranchSpan { span, true_marker, false_marker } in branch_spans {
599        writeln!(
600            w,
601            "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
602        )?;
603        did_print = true;
604    }
605
606    for coverage::MCDCBranchSpan { span, true_marker, false_marker, .. } in
607        mcdc_degraded_branch_spans
608    {
609        writeln!(
610            w,
611            "{INDENT}coverage branch {{ true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
612        )?;
613        did_print = true;
614    }
615
616    for (
617        coverage::MCDCDecisionSpan { span, end_markers, decision_depth, num_conditions: _ },
618        conditions,
619    ) in mcdc_spans
620    {
621        let num_conditions = conditions.len();
622        writeln!(
623            w,
624            "{INDENT}coverage mcdc decision {{ num_conditions: {num_conditions:?}, end: {end_markers:?}, depth: {decision_depth:?} }} => {span:?}"
625        )?;
626        for coverage::MCDCBranchSpan { span, condition_info, true_marker, false_marker } in
627            conditions
628        {
629            writeln!(
630                w,
631                "{INDENT}coverage mcdc branch {{ condition_id: {:?}, true: {true_marker:?}, false: {false_marker:?} }} => {span:?}",
632                condition_info.condition_id
633            )?;
634        }
635        did_print = true;
636    }
637
638    if did_print {
639        writeln!(w)?;
640    }
641
642    Ok(())
643}
644
645fn write_function_coverage_info(
646    function_coverage_info: &coverage::FunctionCoverageInfo,
647    w: &mut dyn io::Write,
648) -> io::Result<()> {
649    let coverage::FunctionCoverageInfo { mappings, .. } = function_coverage_info;
650
651    for coverage::Mapping { kind, span } in mappings {
652        writeln!(w, "{INDENT}coverage {kind:?} => {span:?};")?;
653    }
654    writeln!(w)?;
655
656    Ok(())
657}
658
659fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io::Result<()> {
660    use rustc_hir::def::DefKind;
661
662    trace!("write_mir_sig: {:?}", body.source.instance);
663    let def_id = body.source.def_id();
664    let kind = tcx.def_kind(def_id);
665    let is_function = match kind {
666        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::SyntheticCoroutineBody => {
667            true
668        }
669        _ => tcx.is_closure_like(def_id),
670    };
671    match (kind, body.source.promoted) {
672        (_, Some(_)) => write!(w, "const ")?, // promoteds are the closest to consts
673        (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
674        (DefKind::Static { safety: _, mutability: hir::Mutability::Not, nested: false }, _) => {
675            write!(w, "static ")?
676        }
677        (DefKind::Static { safety: _, mutability: hir::Mutability::Mut, nested: false }, _) => {
678            write!(w, "static mut ")?
679        }
680        (_, _) if is_function => write!(w, "fn ")?,
681        // things like anon const, not an item
682        (DefKind::AnonConst | DefKind::InlineConst, _) => {}
683        // `global_asm!` have fake bodies, which we may dump after mir-build
684        (DefKind::GlobalAsm, _) => {}
685        _ => bug!("Unexpected def kind {:?}", kind),
686    }
687
688    ty::print::with_forced_impl_filename_line! {
689        // see notes on #41697 elsewhere
690        write!(w, "{}", tcx.def_path_str(def_id))?
691    }
692    if let Some(p) = body.source.promoted {
693        write!(w, "::{p:?}")?;
694    }
695
696    if body.source.promoted.is_none() && is_function {
697        write!(w, "(")?;
698
699        // fn argument types.
700        for (i, arg) in body.args_iter().enumerate() {
701            if i != 0 {
702                write!(w, ", ")?;
703            }
704            write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
705        }
706
707        write!(w, ") -> {}", body.return_ty())?;
708    } else {
709        assert_eq!(body.arg_count, 0);
710        write!(w, ": {} =", body.return_ty())?;
711    }
712
713    if let Some(yield_ty) = body.yield_ty() {
714        writeln!(w)?;
715        writeln!(w, "yields {yield_ty}")?;
716    }
717
718    write!(w, " ")?;
719    // Next thing that gets printed is the opening {
720
721    Ok(())
722}
723
724fn write_user_type_annotations(
725    tcx: TyCtxt<'_>,
726    body: &Body<'_>,
727    w: &mut dyn io::Write,
728) -> io::Result<()> {
729    if !body.user_type_annotations.is_empty() {
730        writeln!(w, "| User Type Annotations")?;
731    }
732    for (index, annotation) in body.user_type_annotations.iter_enumerated() {
733        writeln!(
734            w,
735            "| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
736            index.index(),
737            annotation.user_ty,
738            tcx.sess.source_map().span_to_embeddable_string(annotation.span),
739            with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
740        )?;
741    }
742    if !body.user_type_annotations.is_empty() {
743        writeln!(w, "|")?;
744    }
745    Ok(())
746}
747
748pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
749    if let Some(i) = single {
750        vec![i]
751    } else {
752        tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
753    }
754}
755
756///////////////////////////////////////////////////////////////////////////
757// Basic blocks and their parts (statements, terminators, ...)
758
759/// Write out a human-readable textual representation for the given basic block.
760fn write_basic_block<'tcx, F>(
761    tcx: TyCtxt<'tcx>,
762    block: BasicBlock,
763    body: &Body<'tcx>,
764    extra_data: &mut F,
765    w: &mut dyn io::Write,
766    options: PrettyPrintMirOptions,
767) -> io::Result<()>
768where
769    F: FnMut(PassWhere, &mut dyn io::Write) -> io::Result<()>,
770{
771    let data = &body[block];
772
773    // Basic block label at the top.
774    let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
775    writeln!(w, "{INDENT}{block:?}{cleanup_text}: {{")?;
776
777    // List of statements in the middle.
778    let mut current_location = Location { block, statement_index: 0 };
779    for statement in &data.statements {
780        extra_data(PassWhere::BeforeLocation(current_location), w)?;
781        let indented_body = format!("{INDENT}{INDENT}{statement:?};");
782        if options.include_extra_comments {
783            writeln!(
784                w,
785                "{:A$} // {}{}",
786                indented_body,
787                if tcx.sess.verbose_internals() {
788                    format!("{current_location:?}: ")
789                } else {
790                    String::new()
791                },
792                comment(tcx, statement.source_info),
793                A = ALIGN,
794            )?;
795        } else {
796            writeln!(w, "{indented_body}")?;
797        }
798
799        write_extra(
800            tcx,
801            w,
802            |visitor| {
803                visitor.visit_statement(statement, current_location);
804            },
805            options,
806        )?;
807
808        extra_data(PassWhere::AfterLocation(current_location), w)?;
809
810        current_location.statement_index += 1;
811    }
812
813    // Terminator at the bottom.
814    extra_data(PassWhere::BeforeLocation(current_location), w)?;
815    if data.terminator.is_some() {
816        let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
817        if options.include_extra_comments {
818            writeln!(
819                w,
820                "{:A$} // {}{}",
821                indented_terminator,
822                if tcx.sess.verbose_internals() {
823                    format!("{current_location:?}: ")
824                } else {
825                    String::new()
826                },
827                comment(tcx, data.terminator().source_info),
828                A = ALIGN,
829            )?;
830        } else {
831            writeln!(w, "{indented_terminator}")?;
832        }
833
834        write_extra(
835            tcx,
836            w,
837            |visitor| {
838                visitor.visit_terminator(data.terminator(), current_location);
839            },
840            options,
841        )?;
842    }
843
844    extra_data(PassWhere::AfterLocation(current_location), w)?;
845    extra_data(PassWhere::AfterTerminator(block), w)?;
846
847    writeln!(w, "{INDENT}}}")
848}
849
850impl Debug for Statement<'_> {
851    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
852        use self::StatementKind::*;
853        match self.kind {
854            Assign(box (ref place, ref rv)) => write!(fmt, "{place:?} = {rv:?}"),
855            FakeRead(box (ref cause, ref place)) => {
856                write!(fmt, "FakeRead({cause:?}, {place:?})")
857            }
858            Retag(ref kind, ref place) => write!(
859                fmt,
860                "Retag({}{:?})",
861                match kind {
862                    RetagKind::FnEntry => "[fn entry] ",
863                    RetagKind::TwoPhase => "[2phase] ",
864                    RetagKind::Raw => "[raw] ",
865                    RetagKind::Default => "",
866                },
867                place,
868            ),
869            StorageLive(ref place) => write!(fmt, "StorageLive({place:?})"),
870            StorageDead(ref place) => write!(fmt, "StorageDead({place:?})"),
871            SetDiscriminant { ref place, variant_index } => {
872                write!(fmt, "discriminant({place:?}) = {variant_index:?}")
873            }
874            Deinit(ref place) => write!(fmt, "Deinit({place:?})"),
875            PlaceMention(ref place) => {
876                write!(fmt, "PlaceMention({place:?})")
877            }
878            AscribeUserType(box (ref place, ref c_ty), ref variance) => {
879                write!(fmt, "AscribeUserType({place:?}, {variance:?}, {c_ty:?})")
880            }
881            Coverage(ref kind) => write!(fmt, "Coverage::{kind:?}"),
882            Intrinsic(box ref intrinsic) => write!(fmt, "{intrinsic}"),
883            ConstEvalCounter => write!(fmt, "ConstEvalCounter"),
884            Nop => write!(fmt, "nop"),
885            BackwardIncompatibleDropHint { ref place, reason: _ } => {
886                // For now, we don't record the reason because there is only one use case,
887                // which is to report breaking change in drop order by Edition 2024
888                write!(fmt, "BackwardIncompatibleDropHint({place:?})")
889            }
890        }
891    }
892}
893
894impl Display for NonDivergingIntrinsic<'_> {
895    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
896        match self {
897            Self::Assume(op) => write!(f, "assume({op:?})"),
898            Self::CopyNonOverlapping(CopyNonOverlapping { src, dst, count }) => {
899                write!(f, "copy_nonoverlapping(dst = {dst:?}, src = {src:?}, count = {count:?})")
900            }
901        }
902    }
903}
904
905impl<'tcx> Debug for TerminatorKind<'tcx> {
906    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
907        self.fmt_head(fmt)?;
908        let successor_count = self.successors().count();
909        let labels = self.fmt_successor_labels();
910        assert_eq!(successor_count, labels.len());
911
912        // `Cleanup` is already included in successors
913        let show_unwind = !matches!(self.unwind(), None | Some(UnwindAction::Cleanup(_)));
914        let fmt_unwind = |fmt: &mut Formatter<'_>| -> fmt::Result {
915            write!(fmt, "unwind ")?;
916            match self.unwind() {
917                // Not needed or included in successors
918                None | Some(UnwindAction::Cleanup(_)) => unreachable!(),
919                Some(UnwindAction::Continue) => write!(fmt, "continue"),
920                Some(UnwindAction::Unreachable) => write!(fmt, "unreachable"),
921                Some(UnwindAction::Terminate(reason)) => {
922                    write!(fmt, "terminate({})", reason.as_short_str())
923                }
924            }
925        };
926
927        match (successor_count, show_unwind) {
928            (0, false) => Ok(()),
929            (0, true) => {
930                write!(fmt, " -> ")?;
931                fmt_unwind(fmt)
932            }
933            (1, false) => write!(fmt, " -> {:?}", self.successors().next().unwrap()),
934            _ => {
935                write!(fmt, " -> [")?;
936                for (i, target) in self.successors().enumerate() {
937                    if i > 0 {
938                        write!(fmt, ", ")?;
939                    }
940                    write!(fmt, "{}: {:?}", labels[i], target)?;
941                }
942                if show_unwind {
943                    write!(fmt, ", ")?;
944                    fmt_unwind(fmt)?;
945                }
946                write!(fmt, "]")
947            }
948        }
949    }
950}
951
952impl<'tcx> TerminatorKind<'tcx> {
953    /// Writes the "head" part of the terminator; that is, its name and the data it uses to pick the
954    /// successor basic block, if any. The only information not included is the list of possible
955    /// successors, which may be rendered differently between the text and the graphviz format.
956    pub fn fmt_head<W: fmt::Write>(&self, fmt: &mut W) -> fmt::Result {
957        use self::TerminatorKind::*;
958        match self {
959            Goto { .. } => write!(fmt, "goto"),
960            SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"),
961            Return => write!(fmt, "return"),
962            CoroutineDrop => write!(fmt, "coroutine_drop"),
963            UnwindResume => write!(fmt, "resume"),
964            UnwindTerminate(reason) => {
965                write!(fmt, "terminate({})", reason.as_short_str())
966            }
967            Yield { value, resume_arg, .. } => write!(fmt, "{resume_arg:?} = yield({value:?})"),
968            Unreachable => write!(fmt, "unreachable"),
969            Drop { place, .. } => write!(fmt, "drop({place:?})"),
970            Call { func, args, destination, .. } => {
971                write!(fmt, "{destination:?} = ")?;
972                write!(fmt, "{func:?}(")?;
973                for (index, arg) in args.iter().map(|a| &a.node).enumerate() {
974                    if index > 0 {
975                        write!(fmt, ", ")?;
976                    }
977                    write!(fmt, "{arg:?}")?;
978                }
979                write!(fmt, ")")
980            }
981            TailCall { func, args, .. } => {
982                write!(fmt, "tailcall {func:?}(")?;
983                for (index, arg) in args.iter().enumerate() {
984                    if index > 0 {
985                        write!(fmt, ", ")?;
986                    }
987                    write!(fmt, "{:?}", arg)?;
988                }
989                write!(fmt, ")")
990            }
991            Assert { cond, expected, msg, .. } => {
992                write!(fmt, "assert(")?;
993                if !expected {
994                    write!(fmt, "!")?;
995                }
996                write!(fmt, "{cond:?}, ")?;
997                msg.fmt_assert_args(fmt)?;
998                write!(fmt, ")")
999            }
1000            FalseEdge { .. } => write!(fmt, "falseEdge"),
1001            FalseUnwind { .. } => write!(fmt, "falseUnwind"),
1002            InlineAsm { template, operands, options, .. } => {
1003                write!(fmt, "asm!(\"{}\"", InlineAsmTemplatePiece::to_string(template))?;
1004                for op in operands {
1005                    write!(fmt, ", ")?;
1006                    let print_late = |&late| if late { "late" } else { "" };
1007                    match op {
1008                        InlineAsmOperand::In { reg, value } => {
1009                            write!(fmt, "in({reg}) {value:?}")?;
1010                        }
1011                        InlineAsmOperand::Out { reg, late, place: Some(place) } => {
1012                            write!(fmt, "{}out({}) {:?}", print_late(late), reg, place)?;
1013                        }
1014                        InlineAsmOperand::Out { reg, late, place: None } => {
1015                            write!(fmt, "{}out({}) _", print_late(late), reg)?;
1016                        }
1017                        InlineAsmOperand::InOut {
1018                            reg,
1019                            late,
1020                            in_value,
1021                            out_place: Some(out_place),
1022                        } => {
1023                            write!(
1024                                fmt,
1025                                "in{}out({}) {:?} => {:?}",
1026                                print_late(late),
1027                                reg,
1028                                in_value,
1029                                out_place
1030                            )?;
1031                        }
1032                        InlineAsmOperand::InOut { reg, late, in_value, out_place: None } => {
1033                            write!(fmt, "in{}out({}) {:?} => _", print_late(late), reg, in_value)?;
1034                        }
1035                        InlineAsmOperand::Const { value } => {
1036                            write!(fmt, "const {value:?}")?;
1037                        }
1038                        InlineAsmOperand::SymFn { value } => {
1039                            write!(fmt, "sym_fn {value:?}")?;
1040                        }
1041                        InlineAsmOperand::SymStatic { def_id } => {
1042                            write!(fmt, "sym_static {def_id:?}")?;
1043                        }
1044                        InlineAsmOperand::Label { target_index } => {
1045                            write!(fmt, "label {target_index}")?;
1046                        }
1047                    }
1048                }
1049                write!(fmt, ", options({options:?}))")
1050            }
1051        }
1052    }
1053
1054    /// Returns the list of labels for the edges to the successor basic blocks.
1055    pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
1056        use self::TerminatorKind::*;
1057        match *self {
1058            Return
1059            | TailCall { .. }
1060            | UnwindResume
1061            | UnwindTerminate(_)
1062            | Unreachable
1063            | CoroutineDrop => vec![],
1064            Goto { .. } => vec!["".into()],
1065            SwitchInt { ref targets, .. } => targets
1066                .values
1067                .iter()
1068                .map(|&u| Cow::Owned(u.to_string()))
1069                .chain(iter::once("otherwise".into()))
1070                .collect(),
1071            Call { target: Some(_), unwind: UnwindAction::Cleanup(_), .. } => {
1072                vec!["return".into(), "unwind".into()]
1073            }
1074            Call { target: Some(_), unwind: _, .. } => vec!["return".into()],
1075            Call { target: None, unwind: UnwindAction::Cleanup(_), .. } => vec!["unwind".into()],
1076            Call { target: None, unwind: _, .. } => vec![],
1077            Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
1078            Yield { drop: None, .. } => vec!["resume".into()],
1079            Drop { unwind: UnwindAction::Cleanup(_), drop: Some(_), .. } => {
1080                vec!["return".into(), "unwind".into(), "drop".into()]
1081            }
1082            Drop { unwind: UnwindAction::Cleanup(_), drop: None, .. } => {
1083                vec!["return".into(), "unwind".into()]
1084            }
1085            Drop { unwind: _, drop: Some(_), .. } => vec!["return".into(), "drop".into()],
1086            Drop { unwind: _, .. } => vec!["return".into()],
1087            Assert { unwind: UnwindAction::Cleanup(_), .. } => {
1088                vec!["success".into(), "unwind".into()]
1089            }
1090            Assert { unwind: _, .. } => vec!["success".into()],
1091            FalseEdge { .. } => vec!["real".into(), "imaginary".into()],
1092            FalseUnwind { unwind: UnwindAction::Cleanup(_), .. } => {
1093                vec!["real".into(), "unwind".into()]
1094            }
1095            FalseUnwind { unwind: _, .. } => vec!["real".into()],
1096            InlineAsm { asm_macro, options, ref targets, unwind, .. } => {
1097                let mut vec = Vec::with_capacity(targets.len() + 1);
1098                if !asm_macro.diverges(options) {
1099                    vec.push("return".into());
1100                }
1101                vec.resize(targets.len(), "label".into());
1102
1103                if let UnwindAction::Cleanup(_) = unwind {
1104                    vec.push("unwind".into());
1105                }
1106
1107                vec
1108            }
1109        }
1110    }
1111}
1112
1113impl<'tcx> Debug for Rvalue<'tcx> {
1114    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1115        use self::Rvalue::*;
1116
1117        match *self {
1118            Use(ref place) => write!(fmt, "{place:?}"),
1119            Repeat(ref a, b) => {
1120                write!(fmt, "[{a:?}; ")?;
1121                pretty_print_const(b, fmt, false)?;
1122                write!(fmt, "]")
1123            }
1124            Len(ref a) => write!(fmt, "Len({a:?})"),
1125            Cast(ref kind, ref place, ref ty) => {
1126                with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
1127            }
1128            BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
1129            UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
1130            Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
1131            NullaryOp(ref op, ref t) => {
1132                let t = with_no_trimmed_paths!(format!("{}", t));
1133                match op {
1134                    NullOp::SizeOf => write!(fmt, "SizeOf({t})"),
1135                    NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
1136                    NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
1137                    NullOp::UbChecks => write!(fmt, "UbChecks()"),
1138                    NullOp::ContractChecks => write!(fmt, "ContractChecks()"),
1139                }
1140            }
1141            ThreadLocalRef(did) => ty::tls::with(|tcx| {
1142                let muta = tcx.static_mutability(did).unwrap().prefix_str();
1143                write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
1144            }),
1145            Ref(region, borrow_kind, ref place) => {
1146                let kind_str = match borrow_kind {
1147                    BorrowKind::Shared => "",
1148                    BorrowKind::Fake(FakeBorrowKind::Deep) => "fake ",
1149                    BorrowKind::Fake(FakeBorrowKind::Shallow) => "fake shallow ",
1150                    BorrowKind::Mut { .. } => "mut ",
1151                };
1152
1153                // When printing regions, add trailing space if necessary.
1154                let print_region = ty::tls::with(|tcx| {
1155                    tcx.sess.verbose_internals() || tcx.sess.opts.unstable_opts.identify_regions
1156                });
1157                let region = if print_region {
1158                    let mut region = region.to_string();
1159                    if !region.is_empty() {
1160                        region.push(' ');
1161                    }
1162                    region
1163                } else {
1164                    // Do not even print 'static
1165                    String::new()
1166                };
1167                write!(fmt, "&{region}{kind_str}{place:?}")
1168            }
1169
1170            CopyForDeref(ref place) => write!(fmt, "deref_copy {place:#?}"),
1171
1172            RawPtr(mutability, ref place) => {
1173                write!(fmt, "&raw {mut_str} {place:?}", mut_str = mutability.ptr_str())
1174            }
1175
1176            Aggregate(ref kind, ref places) => {
1177                let fmt_tuple = |fmt: &mut Formatter<'_>, name: &str| {
1178                    let mut tuple_fmt = fmt.debug_tuple(name);
1179                    for place in places {
1180                        tuple_fmt.field(place);
1181                    }
1182                    tuple_fmt.finish()
1183                };
1184
1185                match **kind {
1186                    AggregateKind::Array(_) => write!(fmt, "{places:?}"),
1187
1188                    AggregateKind::Tuple => {
1189                        if places.is_empty() {
1190                            write!(fmt, "()")
1191                        } else {
1192                            fmt_tuple(fmt, "")
1193                        }
1194                    }
1195
1196                    AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => {
1197                        ty::tls::with(|tcx| {
1198                            let variant_def = &tcx.adt_def(adt_did).variant(variant);
1199                            let args = tcx.lift(args).expect("could not lift for printing");
1200                            let name = FmtPrinter::print_string(tcx, Namespace::ValueNS, |cx| {
1201                                cx.print_def_path(variant_def.def_id, args)
1202                            })?;
1203
1204                            match variant_def.ctor_kind() {
1205                                Some(CtorKind::Const) => fmt.write_str(&name),
1206                                Some(CtorKind::Fn) => fmt_tuple(fmt, &name),
1207                                None => {
1208                                    let mut struct_fmt = fmt.debug_struct(&name);
1209                                    for (field, place) in iter::zip(&variant_def.fields, places) {
1210                                        struct_fmt.field(field.name.as_str(), place);
1211                                    }
1212                                    struct_fmt.finish()
1213                                }
1214                            }
1215                        })
1216                    }
1217
1218                    AggregateKind::Closure(def_id, args)
1219                    | AggregateKind::CoroutineClosure(def_id, args) => ty::tls::with(|tcx| {
1220                        let name = if tcx.sess.opts.unstable_opts.span_free_formats {
1221                            let args = tcx.lift(args).unwrap();
1222                            format!("{{closure@{}}}", tcx.def_path_str_with_args(def_id, args),)
1223                        } else {
1224                            let span = tcx.def_span(def_id);
1225                            format!(
1226                                "{{closure@{}}}",
1227                                tcx.sess.source_map().span_to_diagnostic_string(span)
1228                            )
1229                        };
1230                        let mut struct_fmt = fmt.debug_struct(&name);
1231
1232                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1233                        if let Some(def_id) = def_id.as_local()
1234                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1235                        {
1236                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1237                                let var_name = tcx.hir_name(var_id);
1238                                struct_fmt.field(var_name.as_str(), place);
1239                            }
1240                        } else {
1241                            for (index, place) in places.iter().enumerate() {
1242                                struct_fmt.field(&format!("{index}"), place);
1243                            }
1244                        }
1245
1246                        struct_fmt.finish()
1247                    }),
1248
1249                    AggregateKind::Coroutine(def_id, _) => ty::tls::with(|tcx| {
1250                        let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id));
1251                        let mut struct_fmt = fmt.debug_struct(&name);
1252
1253                        // FIXME(project-rfc-2229#48): This should be a list of capture names/places
1254                        if let Some(def_id) = def_id.as_local()
1255                            && let Some(upvars) = tcx.upvars_mentioned(def_id)
1256                        {
1257                            for (&var_id, place) in iter::zip(upvars.keys(), places) {
1258                                let var_name = tcx.hir_name(var_id);
1259                                struct_fmt.field(var_name.as_str(), place);
1260                            }
1261                        } else {
1262                            for (index, place) in places.iter().enumerate() {
1263                                struct_fmt.field(&format!("{index}"), place);
1264                            }
1265                        }
1266
1267                        struct_fmt.finish()
1268                    }),
1269
1270                    AggregateKind::RawPtr(pointee_ty, mutability) => {
1271                        let kind_str = match mutability {
1272                            Mutability::Mut => "mut",
1273                            Mutability::Not => "const",
1274                        };
1275                        with_no_trimmed_paths!(write!(fmt, "*{kind_str} {pointee_ty} from "))?;
1276                        fmt_tuple(fmt, "")
1277                    }
1278                }
1279            }
1280
1281            ShallowInitBox(ref place, ref ty) => {
1282                with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
1283            }
1284
1285            WrapUnsafeBinder(ref op, ty) => {
1286                with_no_trimmed_paths!(write!(fmt, "wrap_binder!({op:?}; {ty})"))
1287            }
1288        }
1289    }
1290}
1291
1292impl<'tcx> Debug for Operand<'tcx> {
1293    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1294        use self::Operand::*;
1295        match *self {
1296            Constant(ref a) => write!(fmt, "{a:?}"),
1297            Copy(ref place) => write!(fmt, "copy {place:?}"),
1298            Move(ref place) => write!(fmt, "move {place:?}"),
1299        }
1300    }
1301}
1302
1303impl<'tcx> Debug for ConstOperand<'tcx> {
1304    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1305        write!(fmt, "{self}")
1306    }
1307}
1308
1309impl<'tcx> Display for ConstOperand<'tcx> {
1310    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1311        match self.ty().kind() {
1312            ty::FnDef(..) => {}
1313            _ => write!(fmt, "const ")?,
1314        }
1315        Display::fmt(&self.const_, fmt)
1316    }
1317}
1318
1319impl Debug for Place<'_> {
1320    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1321        self.as_ref().fmt(fmt)
1322    }
1323}
1324
1325impl Debug for PlaceRef<'_> {
1326    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
1327        pre_fmt_projection(self.projection, fmt)?;
1328        write!(fmt, "{:?}", self.local)?;
1329        post_fmt_projection(self.projection, fmt)
1330    }
1331}
1332
1333fn pre_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1334    for &elem in projection.iter().rev() {
1335        match elem {
1336            ProjectionElem::OpaqueCast(_)
1337            | ProjectionElem::Subtype(_)
1338            | ProjectionElem::Downcast(_, _)
1339            | ProjectionElem::Field(_, _) => {
1340                write!(fmt, "(")?;
1341            }
1342            ProjectionElem::Deref => {
1343                write!(fmt, "(*")?;
1344            }
1345            ProjectionElem::Index(_)
1346            | ProjectionElem::ConstantIndex { .. }
1347            | ProjectionElem::Subslice { .. } => {}
1348            ProjectionElem::UnwrapUnsafeBinder(_) => {
1349                write!(fmt, "unwrap_binder!(")?;
1350            }
1351        }
1352    }
1353
1354    Ok(())
1355}
1356
1357fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) -> fmt::Result {
1358    for &elem in projection.iter() {
1359        match elem {
1360            ProjectionElem::OpaqueCast(ty) => {
1361                write!(fmt, " as {ty})")?;
1362            }
1363            ProjectionElem::Subtype(ty) => {
1364                write!(fmt, " as subtype {ty})")?;
1365            }
1366            ProjectionElem::Downcast(Some(name), _index) => {
1367                write!(fmt, " as {name})")?;
1368            }
1369            ProjectionElem::Downcast(None, index) => {
1370                write!(fmt, " as variant#{index:?})")?;
1371            }
1372            ProjectionElem::Deref => {
1373                write!(fmt, ")")?;
1374            }
1375            ProjectionElem::Field(field, ty) => {
1376                with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
1377            }
1378            ProjectionElem::Index(ref index) => {
1379                write!(fmt, "[{index:?}]")?;
1380            }
1381            ProjectionElem::ConstantIndex { offset, min_length, from_end: false } => {
1382                write!(fmt, "[{offset:?} of {min_length:?}]")?;
1383            }
1384            ProjectionElem::ConstantIndex { offset, min_length, from_end: true } => {
1385                write!(fmt, "[-{offset:?} of {min_length:?}]")?;
1386            }
1387            ProjectionElem::Subslice { from, to: 0, from_end: true } => {
1388                write!(fmt, "[{from:?}:]")?;
1389            }
1390            ProjectionElem::Subslice { from: 0, to, from_end: true } => {
1391                write!(fmt, "[:-{to:?}]")?;
1392            }
1393            ProjectionElem::Subslice { from, to, from_end: true } => {
1394                write!(fmt, "[{from:?}:-{to:?}]")?;
1395            }
1396            ProjectionElem::Subslice { from, to, from_end: false } => {
1397                write!(fmt, "[{from:?}..{to:?}]")?;
1398            }
1399            ProjectionElem::UnwrapUnsafeBinder(ty) => {
1400                write!(fmt, "; {ty})")?;
1401            }
1402        }
1403    }
1404
1405    Ok(())
1406}
1407
1408/// After we print the main statement, we sometimes dump extra
1409/// information. There's often a lot of little things "nuzzled up" in
1410/// a statement.
1411fn write_extra<'tcx, F>(
1412    tcx: TyCtxt<'tcx>,
1413    write: &mut dyn io::Write,
1414    mut visit_op: F,
1415    options: PrettyPrintMirOptions,
1416) -> io::Result<()>
1417where
1418    F: FnMut(&mut ExtraComments<'tcx>),
1419{
1420    if options.include_extra_comments {
1421        let mut extra_comments = ExtraComments { tcx, comments: vec![] };
1422        visit_op(&mut extra_comments);
1423        for comment in extra_comments.comments {
1424            writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
1425        }
1426    }
1427    Ok(())
1428}
1429
1430struct ExtraComments<'tcx> {
1431    tcx: TyCtxt<'tcx>,
1432    comments: Vec<String>,
1433}
1434
1435impl<'tcx> ExtraComments<'tcx> {
1436    fn push(&mut self, lines: &str) {
1437        for line in lines.split('\n') {
1438            self.comments.push(line.to_string());
1439        }
1440    }
1441}
1442
1443fn use_verbose(ty: Ty<'_>, fn_def: bool) -> bool {
1444    match *ty.kind() {
1445        ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
1446        // Unit type
1447        ty::Tuple(g_args) if g_args.is_empty() => false,
1448        ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(g_arg, fn_def)),
1449        ty::Array(ty, _) => use_verbose(ty, fn_def),
1450        ty::FnDef(..) => fn_def,
1451        _ => true,
1452    }
1453}
1454
1455impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> {
1456    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, _location: Location) {
1457        let ConstOperand { span, user_ty, const_ } = constant;
1458        if use_verbose(const_.ty(), true) {
1459            self.push("mir::ConstOperand");
1460            self.push(&format!(
1461                "+ span: {}",
1462                self.tcx.sess.source_map().span_to_embeddable_string(*span)
1463            ));
1464            if let Some(user_ty) = user_ty {
1465                self.push(&format!("+ user_ty: {user_ty:?}"));
1466            }
1467
1468            let fmt_val = |val: ConstValue<'tcx>, ty: Ty<'tcx>| {
1469                let tcx = self.tcx;
1470                rustc_data_structures::make_display(move |fmt| {
1471                    pretty_print_const_value_tcx(tcx, val, ty, fmt)
1472                })
1473            };
1474
1475            let fmt_valtree = |cv: &ty::Value<'tcx>| {
1476                let mut cx = FmtPrinter::new(self.tcx, Namespace::ValueNS);
1477                cx.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap();
1478                cx.into_buffer()
1479            };
1480
1481            let val = match const_ {
1482                Const::Ty(_, ct) => match ct.kind() {
1483                    ty::ConstKind::Param(p) => format!("ty::Param({p})"),
1484                    ty::ConstKind::Unevaluated(uv) => {
1485                        format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,)
1486                    }
1487                    ty::ConstKind::Value(cv) => {
1488                        format!("ty::Valtree({})", fmt_valtree(&cv))
1489                    }
1490                    // No `ty::` prefix since we also use this to represent errors from `mir::Unevaluated`.
1491                    ty::ConstKind::Error(_) => "Error".to_string(),
1492                    // These variants shouldn't exist in the MIR.
1493                    ty::ConstKind::Placeholder(_)
1494                    | ty::ConstKind::Infer(_)
1495                    | ty::ConstKind::Expr(_)
1496                    | ty::ConstKind::Bound(..) => bug!("unexpected MIR constant: {:?}", const_),
1497                },
1498                Const::Unevaluated(uv, _) => {
1499                    format!(
1500                        "Unevaluated({}, {:?}, {:?})",
1501                        self.tcx.def_path_str(uv.def),
1502                        uv.args,
1503                        uv.promoted,
1504                    )
1505                }
1506                Const::Val(val, ty) => format!("Value({})", fmt_val(*val, *ty)),
1507            };
1508
1509            // This reflects what `Const` looked liked before `val` was renamed
1510            // as `kind`. We print it like this to avoid having to update
1511            // expected output in a lot of tests.
1512            self.push(&format!("+ const_: Const {{ ty: {}, val: {} }}", const_.ty(), val));
1513        }
1514    }
1515
1516    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1517        self.super_rvalue(rvalue, location);
1518        if let Rvalue::Aggregate(kind, _) = rvalue {
1519            match **kind {
1520                AggregateKind::Closure(def_id, args) => {
1521                    self.push("closure");
1522                    self.push(&format!("+ def_id: {def_id:?}"));
1523                    self.push(&format!("+ args: {args:#?}"));
1524                }
1525
1526                AggregateKind::Coroutine(def_id, args) => {
1527                    self.push("coroutine");
1528                    self.push(&format!("+ def_id: {def_id:?}"));
1529                    self.push(&format!("+ args: {args:#?}"));
1530                    self.push(&format!("+ kind: {:?}", self.tcx.coroutine_kind(def_id)));
1531                }
1532
1533                AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
1534                    self.push("adt");
1535                    self.push(&format!("+ user_ty: {user_ty:?}"));
1536                }
1537
1538                _ => {}
1539            }
1540        }
1541    }
1542}
1543
1544fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
1545    let location = tcx.sess.source_map().span_to_embeddable_string(span);
1546    format!("scope {} at {}", scope.index(), location,)
1547}
1548
1549///////////////////////////////////////////////////////////////////////////
1550// Allocations
1551
1552/// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
1553/// allocations.
1554pub fn write_allocations<'tcx>(
1555    tcx: TyCtxt<'tcx>,
1556    body: &Body<'_>,
1557    w: &mut dyn io::Write,
1558) -> io::Result<()> {
1559    fn alloc_ids_from_alloc(
1560        alloc: ConstAllocation<'_>,
1561    ) -> impl DoubleEndedIterator<Item = AllocId> {
1562        alloc.inner().provenance().ptrs().values().map(|p| p.alloc_id())
1563    }
1564
1565    fn alloc_id_from_const_val(val: ConstValue<'_>) -> Option<AllocId> {
1566        match val {
1567            ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _)) => Some(ptr.provenance.alloc_id()),
1568            ConstValue::Scalar(interpret::Scalar::Int { .. }) => None,
1569            ConstValue::ZeroSized => None,
1570            ConstValue::Slice { .. } => {
1571                // `u8`/`str` slices, shouldn't contain pointers that we want to print.
1572                None
1573            }
1574            ConstValue::Indirect { alloc_id, .. } => {
1575                // FIXME: we don't actually want to print all of these, since some are printed nicely directly as values inline in MIR.
1576                // Really we'd want `pretty_print_const_value` to decide which allocations to print, instead of having a separate visitor.
1577                Some(alloc_id)
1578            }
1579        }
1580    }
1581    struct CollectAllocIds(BTreeSet<AllocId>);
1582
1583    impl<'tcx> Visitor<'tcx> for CollectAllocIds {
1584        fn visit_const_operand(&mut self, c: &ConstOperand<'tcx>, _: Location) {
1585            match c.const_ {
1586                Const::Ty(_, _) | Const::Unevaluated(..) => {}
1587                Const::Val(val, _) => {
1588                    if let Some(id) = alloc_id_from_const_val(val) {
1589                        self.0.insert(id);
1590                    }
1591                }
1592            }
1593        }
1594    }
1595
1596    let mut visitor = CollectAllocIds(Default::default());
1597    visitor.visit_body(body);
1598
1599    // `seen` contains all seen allocations, including the ones we have *not* printed yet.
1600    // The protocol is to first `insert` into `seen`, and only if that returns `true`
1601    // then push to `todo`.
1602    let mut seen = visitor.0;
1603    let mut todo: Vec<_> = seen.iter().copied().collect();
1604    while let Some(id) = todo.pop() {
1605        let mut write_allocation_track_relocs =
1606            |w: &mut dyn io::Write, alloc: ConstAllocation<'tcx>| -> io::Result<()> {
1607                // `.rev()` because we are popping them from the back of the `todo` vector.
1608                for id in alloc_ids_from_alloc(alloc).rev() {
1609                    if seen.insert(id) {
1610                        todo.push(id);
1611                    }
1612                }
1613                write!(w, "{}", display_allocation(tcx, alloc.inner()))
1614            };
1615        write!(w, "\n{id:?}")?;
1616        match tcx.try_get_global_alloc(id) {
1617            // This can't really happen unless there are bugs, but it doesn't cost us anything to
1618            // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
1619            None => write!(w, " (deallocated)")?,
1620            Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?,
1621            Some(GlobalAlloc::VTable(ty, dyn_ty)) => {
1622                write!(w, " (vtable: impl {dyn_ty} for {ty})")?
1623            }
1624            Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
1625                write!(w, " (static: {}", tcx.def_path_str(did))?;
1626                if body.phase <= MirPhase::Runtime(RuntimePhase::PostCleanup)
1627                    && tcx.hir_body_const_context(body.source.def_id()).is_some()
1628                {
1629                    // Statics may be cyclic and evaluating them too early
1630                    // in the MIR pipeline may cause cycle errors even though
1631                    // normal compilation is fine.
1632                    write!(w, ")")?;
1633                } else {
1634                    match tcx.eval_static_initializer(did) {
1635                        Ok(alloc) => {
1636                            write!(w, ", ")?;
1637                            write_allocation_track_relocs(w, alloc)?;
1638                        }
1639                        Err(_) => write!(w, ", error during initializer evaluation)")?,
1640                    }
1641                }
1642            }
1643            Some(GlobalAlloc::Static(did)) => {
1644                write!(w, " (extern static: {})", tcx.def_path_str(did))?
1645            }
1646            Some(GlobalAlloc::Memory(alloc)) => {
1647                write!(w, " (")?;
1648                write_allocation_track_relocs(w, alloc)?
1649            }
1650        }
1651        writeln!(w)?;
1652    }
1653    Ok(())
1654}
1655
1656/// Dumps the size and metadata and content of an allocation to the given writer.
1657/// The expectation is that the caller first prints other relevant metadata, so the exact
1658/// format of this function is (*without* leading or trailing newline):
1659///
1660/// ```text
1661/// size: {}, align: {}) {
1662///     <bytes>
1663/// }
1664/// ```
1665///
1666/// The byte format is similar to how hex editors print bytes. Each line starts with the address of
1667/// the start of the line, followed by all bytes in hex format (space separated).
1668/// If the allocation is small enough to fit into a single line, no start address is given.
1669/// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
1670/// characters or characters whose value is larger than 127) with a `.`
1671/// This also prints provenance adequately.
1672pub fn display_allocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1673    tcx: TyCtxt<'tcx>,
1674    alloc: &'a Allocation<Prov, Extra, Bytes>,
1675) -> RenderAllocation<'a, 'tcx, Prov, Extra, Bytes> {
1676    RenderAllocation { tcx, alloc }
1677}
1678
1679#[doc(hidden)]
1680pub struct RenderAllocation<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> {
1681    tcx: TyCtxt<'tcx>,
1682    alloc: &'a Allocation<Prov, Extra, Bytes>,
1683}
1684
1685impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> std::fmt::Display
1686    for RenderAllocation<'a, 'tcx, Prov, Extra, Bytes>
1687{
1688    fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1689        let RenderAllocation { tcx, alloc } = *self;
1690        write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
1691        if alloc.size() == Size::ZERO {
1692            // We are done.
1693            return write!(w, " {{}}");
1694        }
1695        if tcx.sess.opts.unstable_opts.dump_mir_exclude_alloc_bytes {
1696            return write!(w, " {{ .. }}");
1697        }
1698        // Write allocation bytes.
1699        writeln!(w, " {{")?;
1700        write_allocation_bytes(tcx, alloc, w, "    ")?;
1701        write!(w, "}}")?;
1702        Ok(())
1703    }
1704}
1705
1706fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
1707    for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
1708        write!(w, "   ")?;
1709    }
1710    writeln!(w, " │ {ascii}")
1711}
1712
1713/// Number of bytes to print per allocation hex dump line.
1714const BYTES_PER_LINE: usize = 16;
1715
1716/// Prints the line start address and returns the new line start address.
1717fn write_allocation_newline(
1718    w: &mut dyn std::fmt::Write,
1719    mut line_start: Size,
1720    ascii: &str,
1721    pos_width: usize,
1722    prefix: &str,
1723) -> Result<Size, std::fmt::Error> {
1724    write_allocation_endline(w, ascii)?;
1725    line_start += Size::from_bytes(BYTES_PER_LINE);
1726    write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
1727    Ok(line_start)
1728}
1729
1730/// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
1731/// is only one line). Note that your prefix should contain a trailing space as the lines are
1732/// printed directly after it.
1733pub fn write_allocation_bytes<'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>(
1734    tcx: TyCtxt<'tcx>,
1735    alloc: &Allocation<Prov, Extra, Bytes>,
1736    w: &mut dyn std::fmt::Write,
1737    prefix: &str,
1738) -> std::fmt::Result {
1739    let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
1740    // Number of chars needed to represent all line numbers.
1741    let pos_width = hex_number_length(alloc.size().bytes());
1742
1743    if num_lines > 0 {
1744        write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
1745    } else {
1746        write!(w, "{prefix}")?;
1747    }
1748
1749    let mut i = Size::ZERO;
1750    let mut line_start = Size::ZERO;
1751
1752    let ptr_size = tcx.data_layout.pointer_size;
1753
1754    let mut ascii = String::new();
1755
1756    let oversized_ptr = |target: &mut String, width| {
1757        if target.len() > width {
1758            write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
1759        }
1760    };
1761
1762    while i < alloc.size() {
1763        // The line start already has a space. While we could remove that space from the line start
1764        // printing and unconditionally print a space here, that would cause the single-line case
1765        // to have a single space before it, which looks weird.
1766        if i != line_start {
1767            write!(w, " ")?;
1768        }
1769        if let Some(prov) = alloc.provenance().get_ptr(i) {
1770            // Memory with provenance must be defined
1771            assert!(alloc.init_mask().is_range_initialized(alloc_range(i, ptr_size)).is_ok());
1772            let j = i.bytes_usize();
1773            let offset = alloc
1774                .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
1775            let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
1776            let offset = Size::from_bytes(offset);
1777            let provenance_width = |bytes| bytes * 3;
1778            let ptr = Pointer::new(prov, offset);
1779            let mut target = format!("{ptr:?}");
1780            if target.len() > provenance_width(ptr_size.bytes_usize() - 1) {
1781                // This is too long, try to save some space.
1782                target = format!("{ptr:#?}");
1783            }
1784            if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
1785                // This branch handles the situation where a provenance starts in the current line
1786                // but ends in the next one.
1787                let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
1788                let overflow = ptr_size - remainder;
1789                let remainder_width = provenance_width(remainder.bytes_usize()) - 2;
1790                let overflow_width = provenance_width(overflow.bytes_usize() - 1) + 1;
1791                ascii.push('╾'); // HEAVY LEFT AND LIGHT RIGHT
1792                for _ in 1..remainder.bytes() {
1793                    ascii.push('─'); // LIGHT HORIZONTAL
1794                }
1795                if overflow_width > remainder_width && overflow_width >= target.len() {
1796                    // The case where the provenance fits into the part in the next line
1797                    write!(w, "╾{0:─^1$}", "", remainder_width)?;
1798                    line_start =
1799                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1800                    ascii.clear();
1801                    write!(w, "{target:─^overflow_width$}╼")?;
1802                } else {
1803                    oversized_ptr(&mut target, remainder_width);
1804                    write!(w, "╾{target:─^remainder_width$}")?;
1805                    line_start =
1806                        write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1807                    write!(w, "{0:─^1$}╼", "", overflow_width)?;
1808                    ascii.clear();
1809                }
1810                for _ in 0..overflow.bytes() - 1 {
1811                    ascii.push('─');
1812                }
1813                ascii.push('╼'); // LIGHT LEFT AND HEAVY RIGHT
1814                i += ptr_size;
1815                continue;
1816            } else {
1817                // This branch handles a provenance that starts and ends in the current line.
1818                let provenance_width = provenance_width(ptr_size.bytes_usize() - 1);
1819                oversized_ptr(&mut target, provenance_width);
1820                ascii.push('╾');
1821                write!(w, "╾{target:─^provenance_width$}╼")?;
1822                for _ in 0..ptr_size.bytes() - 2 {
1823                    ascii.push('─');
1824                }
1825                ascii.push('╼');
1826                i += ptr_size;
1827            }
1828        } else if let Some(prov) = alloc.provenance().get(i, &tcx) {
1829            // Memory with provenance must be defined
1830            assert!(
1831                alloc.init_mask().is_range_initialized(alloc_range(i, Size::from_bytes(1))).is_ok()
1832            );
1833            ascii.push('━'); // HEAVY HORIZONTAL
1834            // We have two characters to display this, which is obviously not enough.
1835            // Format is similar to "oversized" above.
1836            let j = i.bytes_usize();
1837            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1838            write!(w, "╾{c:02x}{prov:#?} (1 ptr byte)╼")?;
1839            i += Size::from_bytes(1);
1840        } else if alloc
1841            .init_mask()
1842            .is_range_initialized(alloc_range(i, Size::from_bytes(1)))
1843            .is_ok()
1844        {
1845            let j = i.bytes_usize();
1846
1847            // Checked definedness (and thus range) and provenance. This access also doesn't
1848            // influence interpreter execution but is only for debugging.
1849            let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
1850            write!(w, "{c:02x}")?;
1851            if c.is_ascii_control() || c >= 0x80 {
1852                ascii.push('.');
1853            } else {
1854                ascii.push(char::from(c));
1855            }
1856            i += Size::from_bytes(1);
1857        } else {
1858            write!(w, "__")?;
1859            ascii.push('░');
1860            i += Size::from_bytes(1);
1861        }
1862        // Print a new line header if the next line still has some bytes to print.
1863        if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
1864            line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
1865            ascii.clear();
1866        }
1867    }
1868    write_allocation_endline(w, &ascii)?;
1869
1870    Ok(())
1871}
1872
1873///////////////////////////////////////////////////////////////////////////
1874// Constants
1875
1876fn pretty_print_byte_str(fmt: &mut Formatter<'_>, byte_str: &[u8]) -> fmt::Result {
1877    write!(fmt, "b\"{}\"", byte_str.escape_ascii())
1878}
1879
1880fn comma_sep<'tcx>(
1881    tcx: TyCtxt<'tcx>,
1882    fmt: &mut Formatter<'_>,
1883    elems: Vec<(ConstValue<'tcx>, Ty<'tcx>)>,
1884) -> fmt::Result {
1885    let mut first = true;
1886    for (ct, ty) in elems {
1887        if !first {
1888            fmt.write_str(", ")?;
1889        }
1890        pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1891        first = false;
1892    }
1893    Ok(())
1894}
1895
1896fn pretty_print_const_value_tcx<'tcx>(
1897    tcx: TyCtxt<'tcx>,
1898    ct: ConstValue<'tcx>,
1899    ty: Ty<'tcx>,
1900    fmt: &mut Formatter<'_>,
1901) -> fmt::Result {
1902    use crate::ty::print::PrettyPrinter;
1903
1904    if tcx.sess.verbose_internals() {
1905        fmt.write_str(&format!("ConstValue({ct:?}: {ty})"))?;
1906        return Ok(());
1907    }
1908
1909    let u8_type = tcx.types.u8;
1910    match (ct, ty.kind()) {
1911        // Byte/string slices, printed as (byte) string literals.
1912        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1913            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1914                fmt.write_str(&format!("{:?}", String::from_utf8_lossy(data)))?;
1915                return Ok(());
1916            }
1917        }
1918        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Slice(t) if *t == u8_type) => {
1919            if let Some(data) = ct.try_get_slice_bytes_for_diagnostics(tcx) {
1920                pretty_print_byte_str(fmt, data)?;
1921                return Ok(());
1922            }
1923        }
1924        (ConstValue::Indirect { alloc_id, offset }, ty::Array(t, n)) if *t == u8_type => {
1925            let n = n.try_to_target_usize(tcx).unwrap();
1926            let alloc = tcx.global_alloc(alloc_id).unwrap_memory();
1927            // cast is ok because we already checked for pointer size (32 or 64 bit) above
1928            let range = AllocRange { start: offset, size: Size::from_bytes(n) };
1929            let byte_str = alloc.inner().get_bytes_strip_provenance(&tcx, range).unwrap();
1930            fmt.write_str("*")?;
1931            pretty_print_byte_str(fmt, byte_str)?;
1932            return Ok(());
1933        }
1934        // Aggregates, printed as array/tuple/struct/variant construction syntax.
1935        //
1936        // NB: the `has_non_region_param` check ensures that we can use
1937        // the `destructure_const` query with an empty `ty::ParamEnv` without
1938        // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1939        // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1940        // to be able to destructure the tuple into `(0u8, *mut T)`
1941        (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
1942            let ct = tcx.lift(ct).unwrap();
1943            let ty = tcx.lift(ty).unwrap();
1944            if let Some(contents) = tcx.try_destructure_mir_constant_for_user_output(ct, ty) {
1945                let fields: Vec<(ConstValue<'_>, Ty<'_>)> = contents.fields.to_vec();
1946                match *ty.kind() {
1947                    ty::Array(..) => {
1948                        fmt.write_str("[")?;
1949                        comma_sep(tcx, fmt, fields)?;
1950                        fmt.write_str("]")?;
1951                    }
1952                    ty::Tuple(..) => {
1953                        fmt.write_str("(")?;
1954                        comma_sep(tcx, fmt, fields)?;
1955                        if contents.fields.len() == 1 {
1956                            fmt.write_str(",")?;
1957                        }
1958                        fmt.write_str(")")?;
1959                    }
1960                    ty::Adt(def, _) if def.variants().is_empty() => {
1961                        fmt.write_str(&format!("{{unreachable(): {ty}}}"))?;
1962                    }
1963                    ty::Adt(def, args) => {
1964                        let variant_idx = contents
1965                            .variant
1966                            .expect("destructed mir constant of adt without variant idx");
1967                        let variant_def = &def.variant(variant_idx);
1968                        let args = tcx.lift(args).unwrap();
1969                        let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
1970                        cx.print_alloc_ids = true;
1971                        cx.print_value_path(variant_def.def_id, args)?;
1972                        fmt.write_str(&cx.into_buffer())?;
1973
1974                        match variant_def.ctor_kind() {
1975                            Some(CtorKind::Const) => {}
1976                            Some(CtorKind::Fn) => {
1977                                fmt.write_str("(")?;
1978                                comma_sep(tcx, fmt, fields)?;
1979                                fmt.write_str(")")?;
1980                            }
1981                            None => {
1982                                fmt.write_str(" {{ ")?;
1983                                let mut first = true;
1984                                for (field_def, (ct, ty)) in iter::zip(&variant_def.fields, fields)
1985                                {
1986                                    if !first {
1987                                        fmt.write_str(", ")?;
1988                                    }
1989                                    write!(fmt, "{}: ", field_def.name)?;
1990                                    pretty_print_const_value_tcx(tcx, ct, ty, fmt)?;
1991                                    first = false;
1992                                }
1993                                fmt.write_str(" }}")?;
1994                            }
1995                        }
1996                    }
1997                    _ => unreachable!(),
1998                }
1999                return Ok(());
2000            }
2001        }
2002        (ConstValue::Scalar(scalar), _) => {
2003            let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2004            cx.print_alloc_ids = true;
2005            let ty = tcx.lift(ty).unwrap();
2006            cx.pretty_print_const_scalar(scalar, ty)?;
2007            fmt.write_str(&cx.into_buffer())?;
2008            return Ok(());
2009        }
2010        (ConstValue::ZeroSized, ty::FnDef(d, s)) => {
2011            let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
2012            cx.print_alloc_ids = true;
2013            cx.print_value_path(*d, s)?;
2014            fmt.write_str(&cx.into_buffer())?;
2015            return Ok(());
2016        }
2017        // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
2018        // their fields instead of just dumping the memory.
2019        _ => {}
2020    }
2021    // Fall back to debug pretty printing for invalid constants.
2022    write!(fmt, "{ct:?}: {ty}")
2023}
2024
2025pub(crate) fn pretty_print_const_value<'tcx>(
2026    ct: ConstValue<'tcx>,
2027    ty: Ty<'tcx>,
2028    fmt: &mut Formatter<'_>,
2029) -> fmt::Result {
2030    ty::tls::with(|tcx| {
2031        let ct = tcx.lift(ct).unwrap();
2032        let ty = tcx.lift(ty).unwrap();
2033        pretty_print_const_value_tcx(tcx, ct, ty, fmt)
2034    })
2035}
2036
2037///////////////////////////////////////////////////////////////////////////
2038// Miscellaneous
2039
2040/// Calc converted u64 decimal into hex and return its length in chars.
2041///
2042/// ```ignore (cannot-test-private-function)
2043/// assert_eq!(1, hex_number_length(0));
2044/// assert_eq!(1, hex_number_length(1));
2045/// assert_eq!(2, hex_number_length(16));
2046/// ```
2047fn hex_number_length(x: u64) -> usize {
2048    if x == 0 {
2049        return 1;
2050    }
2051    let mut length = 0;
2052    let mut x_left = x;
2053    while x_left > 0 {
2054        x_left /= 16;
2055        length += 1;
2056    }
2057    length
2058}