1 use std::collections::BTreeSet;
2 use std::fmt::Display;
3 use std::fmt::Write as _;
4 use std::fs;
5 use std::io::{self, Write};
6 use std::path::{Path, PathBuf};
7
8 use super::graphviz::write_mir_fn_graphviz;
9 use super::spanview::write_mir_fn_spanview;
10 use either::Either;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_hir::def_id::DefId;
13 use rustc_index::vec::Idx;
14 use rustc_middle::mir::interpret::{
15 read_target_uint, AllocId, Allocation, ConstValue, GlobalAlloc, Pointer, Provenance,
16 };
17 use rustc_middle::mir::visit::Visitor;
18 use rustc_middle::mir::MirSource;
19 use rustc_middle::mir::*;
20 use rustc_middle::ty::{self, TyCtxt, TyS, TypeFoldable, TypeVisitor};
21 use rustc_target::abi::Size;
22 use std::ops::ControlFlow;
23
24 const INDENT: &str = " ";
25 /// Alignment for lining up comments following MIR statements
26 pub(crate) const ALIGN: usize = 40;
27
28 /// An indication of where we are in the control flow graph. Used for printing
29 /// extra information in `dump_mir`
30 pub enum PassWhere {
31 /// We have not started dumping the control flow graph, but we are about to.
32 BeforeCFG,
33
34 /// We just finished dumping the control flow graph. This is right before EOF
35 AfterCFG,
36
37 /// We are about to start dumping the given basic block.
38 BeforeBlock(BasicBlock),
39
40 /// We are just about to dump the given statement or terminator.
41 BeforeLocation(Location),
42
43 /// We just dumped the given statement or terminator.
44 AfterLocation(Location),
45
46 /// We just dumped the terminator for a block but not the closing `}`.
47 AfterTerminator(BasicBlock),
48 }
49
50 /// If the session is properly configured, dumps a human-readable
51 /// representation of the mir into:
52 ///
53 /// ```text
54 /// rustc.node<node_id>.<pass_num>.<pass_name>.<disambiguator>
55 /// ```
56 ///
57 /// Output from this function is controlled by passing `-Z dump-mir=<filter>`,
58 /// where `<filter>` takes the following forms:
59 ///
60 /// - `all` -- dump MIR for all fns, all passes, all everything
61 /// - a filter defined by a set of substrings combined with `&` and `|`
62 /// (`&` has higher precedence). At least one of the `|`-separated groups
63 /// must match; an `|`-separated group matches if all of its `&`-separated
64 /// substrings are matched.
65 ///
66 /// Example:
67 ///
68 /// - `nll` == match if `nll` appears in the name
69 /// - `foo & nll` == match if `foo` and `nll` both appear in the name
70 /// - `foo & nll | typeck` == match if `foo` and `nll` both appear in the name
71 /// or `typeck` appears in the name.
72 /// - `foo & nll | bar & typeck` == match if `foo` and `nll` both appear in the name
73 /// or `typeck` and `bar` both appear in the name.
74 #[inline]
dump_mir<'tcx, F>( tcx: TyCtxt<'tcx>, pass_num: Option<&dyn Display>, pass_name: &str, disambiguator: &dyn Display, body: &Body<'tcx>, extra_data: F, ) where F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,75 pub fn dump_mir<'tcx, F>(
76 tcx: TyCtxt<'tcx>,
77 pass_num: Option<&dyn Display>,
78 pass_name: &str,
79 disambiguator: &dyn Display,
80 body: &Body<'tcx>,
81 extra_data: F,
82 ) where
83 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
84 {
85 if !dump_enabled(tcx, pass_name, body.source.def_id()) {
86 return;
87 }
88
89 dump_matched_mir_node(tcx, pass_num, pass_name, disambiguator, body, extra_data);
90 }
91
dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, def_id: DefId) -> bool92 pub fn dump_enabled<'tcx>(tcx: TyCtxt<'tcx>, pass_name: &str, def_id: DefId) -> bool {
93 let filters = match tcx.sess.opts.debugging_opts.dump_mir {
94 None => return false,
95 Some(ref filters) => filters,
96 };
97 let node_path = ty::print::with_forced_impl_filename_line(|| {
98 // see notes on #41697 below
99 tcx.def_path_str(def_id)
100 });
101 filters.split('|').any(|or_filter| {
102 or_filter.split('&').all(|and_filter| {
103 let and_filter_trimmed = and_filter.trim();
104 and_filter_trimmed == "all"
105 || pass_name.contains(and_filter_trimmed)
106 || node_path.contains(and_filter_trimmed)
107 })
108 })
109 }
110
111 // #41697 -- we use `with_forced_impl_filename_line()` because
112 // `def_path_str()` would otherwise trigger `type_of`, and this can
113 // run while we are already attempting to evaluate `type_of`.
114
dump_matched_mir_node<'tcx, F>( tcx: TyCtxt<'tcx>, pass_num: Option<&dyn Display>, pass_name: &str, disambiguator: &dyn Display, body: &Body<'tcx>, mut extra_data: F, ) where F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,115 fn dump_matched_mir_node<'tcx, F>(
116 tcx: TyCtxt<'tcx>,
117 pass_num: Option<&dyn Display>,
118 pass_name: &str,
119 disambiguator: &dyn Display,
120 body: &Body<'tcx>,
121 mut extra_data: F,
122 ) where
123 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
124 {
125 let _: io::Result<()> = try {
126 let mut file =
127 create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, body.source)?;
128 let def_path = ty::print::with_forced_impl_filename_line(|| {
129 // see notes on #41697 above
130 tcx.def_path_str(body.source.def_id())
131 });
132 write!(file, "// MIR for `{}", def_path)?;
133 match body.source.promoted {
134 None => write!(file, "`")?,
135 Some(promoted) => write!(file, "::{:?}`", promoted)?,
136 }
137 writeln!(file, " {} {}", disambiguator, pass_name)?;
138 if let Some(ref layout) = body.generator_layout() {
139 writeln!(file, "/* generator_layout = {:#?} */", layout)?;
140 }
141 writeln!(file)?;
142 extra_data(PassWhere::BeforeCFG, &mut file)?;
143 write_user_type_annotations(tcx, body, &mut file)?;
144 write_mir_fn(tcx, body, &mut extra_data, &mut file)?;
145 extra_data(PassWhere::AfterCFG, &mut file)?;
146 };
147
148 if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
149 let _: io::Result<()> = try {
150 let mut file =
151 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, body.source)?;
152 write_mir_fn_graphviz(tcx, body, false, &mut file)?;
153 };
154 }
155
156 if let Some(spanview) = tcx.sess.opts.debugging_opts.dump_mir_spanview {
157 let _: io::Result<()> = try {
158 let file_basename =
159 dump_file_basename(tcx, pass_num, pass_name, disambiguator, body.source);
160 let mut file = create_dump_file_with_basename(tcx, &file_basename, "html")?;
161 if body.source.def_id().is_local() {
162 write_mir_fn_spanview(tcx, body, spanview, &file_basename, &mut file)?;
163 }
164 };
165 }
166 }
167
168 /// Returns the file basename portion (without extension) of a filename path
169 /// where we should dump a MIR representation output files.
dump_file_basename( tcx: TyCtxt<'_>, pass_num: Option<&dyn Display>, pass_name: &str, disambiguator: &dyn Display, source: MirSource<'tcx>, ) -> String170 fn dump_file_basename(
171 tcx: TyCtxt<'_>,
172 pass_num: Option<&dyn Display>,
173 pass_name: &str,
174 disambiguator: &dyn Display,
175 source: MirSource<'tcx>,
176 ) -> String {
177 let promotion_id = match source.promoted {
178 Some(id) => format!("-{:?}", id),
179 None => String::new(),
180 };
181
182 let pass_num = if tcx.sess.opts.debugging_opts.dump_mir_exclude_pass_number {
183 String::new()
184 } else {
185 match pass_num {
186 None => ".-------".to_string(),
187 Some(pass_num) => format!(".{}", pass_num),
188 }
189 };
190
191 let crate_name = tcx.crate_name(source.def_id().krate);
192 let item_name = tcx.def_path(source.def_id()).to_filename_friendly_no_crate();
193 // All drop shims have the same DefId, so we have to add the type
194 // to get unique file names.
195 let shim_disambiguator = match source.instance {
196 ty::InstanceDef::DropGlue(_, Some(ty)) => {
197 // Unfortunately, pretty-printed typed are not very filename-friendly.
198 // We dome some filtering.
199 let mut s = ".".to_owned();
200 s.extend(ty.to_string().chars().filter_map(|c| match c {
201 ' ' => None,
202 ':' | '<' | '>' => Some('_'),
203 c => Some(c),
204 }));
205 s
206 }
207 _ => String::new(),
208 };
209
210 format!(
211 "{}.{}{}{}{}.{}.{}",
212 crate_name, item_name, shim_disambiguator, promotion_id, pass_num, pass_name, disambiguator,
213 )
214 }
215
216 /// Returns the path to the filename where we should dump a given MIR.
217 /// Also used by other bits of code (e.g., NLL inference) that dump
218 /// graphviz data or other things.
dump_path(tcx: TyCtxt<'_>, basename: &str, extension: &str) -> PathBuf219 fn dump_path(tcx: TyCtxt<'_>, basename: &str, extension: &str) -> PathBuf {
220 let mut file_path = PathBuf::new();
221 file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
222
223 let file_name = format!("{}.{}", basename, extension,);
224
225 file_path.push(&file_name);
226
227 file_path
228 }
229
230 /// Attempts to open the MIR dump file with the given name and extension.
create_dump_file_with_basename( tcx: TyCtxt<'_>, file_basename: &str, extension: &str, ) -> io::Result<io::BufWriter<fs::File>>231 fn create_dump_file_with_basename(
232 tcx: TyCtxt<'_>,
233 file_basename: &str,
234 extension: &str,
235 ) -> io::Result<io::BufWriter<fs::File>> {
236 let file_path = dump_path(tcx, file_basename, extension);
237 if let Some(parent) = file_path.parent() {
238 fs::create_dir_all(parent).map_err(|e| {
239 io::Error::new(
240 e.kind(),
241 format!("IO error creating MIR dump directory: {:?}; {}", parent, e),
242 )
243 })?;
244 }
245 Ok(io::BufWriter::new(fs::File::create(&file_path).map_err(|e| {
246 io::Error::new(e.kind(), format!("IO error creating MIR dump file: {:?}; {}", file_path, e))
247 })?))
248 }
249
250 /// Attempts to open a file where we should dump a given MIR or other
251 /// bit of MIR-related data. Used by `mir-dump`, but also by other
252 /// bits of code (e.g., NLL inference) that dump graphviz data or
253 /// other things, and hence takes the extension as an argument.
create_dump_file( tcx: TyCtxt<'_>, extension: &str, pass_num: Option<&dyn Display>, pass_name: &str, disambiguator: &dyn Display, source: MirSource<'tcx>, ) -> io::Result<io::BufWriter<fs::File>>254 pub fn create_dump_file(
255 tcx: TyCtxt<'_>,
256 extension: &str,
257 pass_num: Option<&dyn Display>,
258 pass_name: &str,
259 disambiguator: &dyn Display,
260 source: MirSource<'tcx>,
261 ) -> io::Result<io::BufWriter<fs::File>> {
262 create_dump_file_with_basename(
263 tcx,
264 &dump_file_basename(tcx, pass_num, pass_name, disambiguator, source),
265 extension,
266 )
267 }
268
269 /// Write out a human-readable textual representation for the given MIR.
write_mir_pretty<'tcx>( tcx: TyCtxt<'tcx>, single: Option<DefId>, w: &mut dyn Write, ) -> io::Result<()>270 pub fn write_mir_pretty<'tcx>(
271 tcx: TyCtxt<'tcx>,
272 single: Option<DefId>,
273 w: &mut dyn Write,
274 ) -> io::Result<()> {
275 writeln!(w, "// WARNING: This output format is intended for human consumers only")?;
276 writeln!(w, "// and is subject to change without notice. Knock yourself out.")?;
277
278 let mut first = true;
279 for def_id in dump_mir_def_ids(tcx, single) {
280 if first {
281 first = false;
282 } else {
283 // Put empty lines between all items
284 writeln!(w)?;
285 }
286
287 let render_body = |w: &mut dyn Write, body| -> io::Result<()> {
288 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
289
290 for body in tcx.promoted_mir(def_id) {
291 writeln!(w)?;
292 write_mir_fn(tcx, body, &mut |_, _| Ok(()), w)?;
293 }
294 Ok(())
295 };
296
297 // For `const fn` we want to render both the optimized MIR and the MIR for ctfe.
298 if tcx.is_const_fn_raw(def_id) {
299 render_body(w, tcx.optimized_mir(def_id))?;
300 writeln!(w)?;
301 writeln!(w, "// MIR FOR CTFE")?;
302 // Do not use `render_body`, as that would render the promoteds again, but these
303 // are shared between mir_for_ctfe and optimized_mir
304 write_mir_fn(tcx, tcx.mir_for_ctfe(def_id), &mut |_, _| Ok(()), w)?;
305 } else {
306 let instance_mir =
307 tcx.instance_mir(ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)));
308 render_body(w, instance_mir)?;
309 }
310 }
311 Ok(())
312 }
313
314 /// Write out a human-readable textual representation for the given function.
write_mir_fn<'tcx, F>( tcx: TyCtxt<'tcx>, body: &Body<'tcx>, extra_data: &mut F, w: &mut dyn Write, ) -> io::Result<()> where F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,315 pub fn write_mir_fn<'tcx, F>(
316 tcx: TyCtxt<'tcx>,
317 body: &Body<'tcx>,
318 extra_data: &mut F,
319 w: &mut dyn Write,
320 ) -> io::Result<()>
321 where
322 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
323 {
324 write_mir_intro(tcx, body, w)?;
325 for block in body.basic_blocks().indices() {
326 extra_data(PassWhere::BeforeBlock(block), w)?;
327 write_basic_block(tcx, block, body, extra_data, w)?;
328 if block.index() + 1 != body.basic_blocks().len() {
329 writeln!(w)?;
330 }
331 }
332
333 writeln!(w, "}}")?;
334
335 write_allocations(tcx, body, w)?;
336
337 Ok(())
338 }
339
340 /// Write out a human-readable textual representation for the given basic block.
write_basic_block<'tcx, F>( tcx: TyCtxt<'tcx>, block: BasicBlock, body: &Body<'tcx>, extra_data: &mut F, w: &mut dyn Write, ) -> io::Result<()> where F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,341 pub fn write_basic_block<'tcx, F>(
342 tcx: TyCtxt<'tcx>,
343 block: BasicBlock,
344 body: &Body<'tcx>,
345 extra_data: &mut F,
346 w: &mut dyn Write,
347 ) -> io::Result<()>
348 where
349 F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
350 {
351 let data = &body[block];
352
353 // Basic block label at the top.
354 let cleanup_text = if data.is_cleanup { " (cleanup)" } else { "" };
355 writeln!(w, "{}{:?}{}: {{", INDENT, block, cleanup_text)?;
356
357 // List of statements in the middle.
358 let mut current_location = Location { block, statement_index: 0 };
359 for statement in &data.statements {
360 extra_data(PassWhere::BeforeLocation(current_location), w)?;
361 let indented_body = format!("{0}{0}{1:?};", INDENT, statement);
362 writeln!(
363 w,
364 "{:A$} // {}{}",
365 indented_body,
366 if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
367 comment(tcx, statement.source_info),
368 A = ALIGN,
369 )?;
370
371 write_extra(tcx, w, |visitor| {
372 visitor.visit_statement(statement, current_location);
373 })?;
374
375 extra_data(PassWhere::AfterLocation(current_location), w)?;
376
377 current_location.statement_index += 1;
378 }
379
380 // Terminator at the bottom.
381 extra_data(PassWhere::BeforeLocation(current_location), w)?;
382 let indented_terminator = format!("{0}{0}{1:?};", INDENT, data.terminator().kind);
383 writeln!(
384 w,
385 "{:A$} // {}{}",
386 indented_terminator,
387 if tcx.sess.verbose() { format!("{:?}: ", current_location) } else { String::new() },
388 comment(tcx, data.terminator().source_info),
389 A = ALIGN,
390 )?;
391
392 write_extra(tcx, w, |visitor| {
393 visitor.visit_terminator(data.terminator(), current_location);
394 })?;
395
396 extra_data(PassWhere::AfterLocation(current_location), w)?;
397 extra_data(PassWhere::AfterTerminator(block), w)?;
398
399 writeln!(w, "{}}}", INDENT)
400 }
401
402 /// After we print the main statement, we sometimes dump extra
403 /// information. There's often a lot of little things "nuzzled up" in
404 /// a statement.
write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()> where F: FnMut(&mut ExtraComments<'tcx>),405 fn write_extra<'tcx, F>(tcx: TyCtxt<'tcx>, write: &mut dyn Write, mut visit_op: F) -> io::Result<()>
406 where
407 F: FnMut(&mut ExtraComments<'tcx>),
408 {
409 let mut extra_comments = ExtraComments { tcx, comments: vec![] };
410 visit_op(&mut extra_comments);
411 for comment in extra_comments.comments {
412 writeln!(write, "{:A$} // {}", "", comment, A = ALIGN)?;
413 }
414 Ok(())
415 }
416
417 struct ExtraComments<'tcx> {
418 tcx: TyCtxt<'tcx>,
419 comments: Vec<String>,
420 }
421
422 impl ExtraComments<'tcx> {
push(&mut self, lines: &str)423 fn push(&mut self, lines: &str) {
424 for line in lines.split('\n') {
425 self.comments.push(line.to_string());
426 }
427 }
428 }
429
use_verbose(ty: &&TyS<'tcx>, fn_def: bool) -> bool430 fn use_verbose(ty: &&TyS<'tcx>, fn_def: bool) -> bool {
431 match ty.kind() {
432 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) => false,
433 // Unit type
434 ty::Tuple(g_args) if g_args.is_empty() => false,
435 ty::Tuple(g_args) => g_args.iter().any(|g_arg| use_verbose(&g_arg.expect_ty(), fn_def)),
436 ty::Array(ty, _) => use_verbose(ty, fn_def),
437 ty::FnDef(..) => fn_def,
438 _ => true,
439 }
440 }
441
442 impl Visitor<'tcx> for ExtraComments<'tcx> {
visit_constant(&mut self, constant: &Constant<'tcx>, location: Location)443 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
444 self.super_constant(constant, location);
445 let Constant { span, user_ty, literal } = constant;
446 if use_verbose(&literal.ty(), true) {
447 self.push("mir::Constant");
448 self.push(&format!(
449 "+ span: {}",
450 self.tcx.sess.source_map().span_to_embeddable_string(*span)
451 ));
452 if let Some(user_ty) = user_ty {
453 self.push(&format!("+ user_ty: {:?}", user_ty));
454 }
455 match literal {
456 ConstantKind::Ty(literal) => self.push(&format!("+ literal: {:?}", literal)),
457 ConstantKind::Val(val, ty) => {
458 // To keep the diffs small, we render this almost like we render ty::Const
459 self.push(&format!("+ literal: Const {{ ty: {}, val: Value({:?}) }}", ty, val))
460 }
461 }
462 }
463 }
464
visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location)465 fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, _: Location) {
466 self.super_const(constant);
467 let ty::Const { ty, val, .. } = constant;
468 if use_verbose(ty, false) {
469 self.push("ty::Const");
470 self.push(&format!("+ ty: {:?}", ty));
471 let val = match val {
472 ty::ConstKind::Param(p) => format!("Param({})", p),
473 ty::ConstKind::Infer(infer) => format!("Infer({:?})", infer),
474 ty::ConstKind::Bound(idx, var) => format!("Bound({:?}, {:?})", idx, var),
475 ty::ConstKind::Placeholder(ph) => format!("PlaceHolder({:?})", ph),
476 ty::ConstKind::Unevaluated(uv) => format!(
477 "Unevaluated({}, {:?}, {:?})",
478 self.tcx.def_path_str(uv.def.did),
479 uv.substs(self.tcx),
480 uv.promoted
481 ),
482 ty::ConstKind::Value(val) => format!("Value({:?})", val),
483 ty::ConstKind::Error(_) => "Error".to_string(),
484 };
485 self.push(&format!("+ val: {}", val));
486 }
487 }
488
visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location)489 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
490 self.super_rvalue(rvalue, location);
491 if let Rvalue::Aggregate(kind, _) = rvalue {
492 match **kind {
493 AggregateKind::Closure(def_id, substs) => {
494 self.push("closure");
495 self.push(&format!("+ def_id: {:?}", def_id));
496 self.push(&format!("+ substs: {:#?}", substs));
497 }
498
499 AggregateKind::Generator(def_id, substs, movability) => {
500 self.push("generator");
501 self.push(&format!("+ def_id: {:?}", def_id));
502 self.push(&format!("+ substs: {:#?}", substs));
503 self.push(&format!("+ movability: {:?}", movability));
504 }
505
506 AggregateKind::Adt(_, _, _, Some(user_ty), _) => {
507 self.push("adt");
508 self.push(&format!("+ user_ty: {:?}", user_ty));
509 }
510
511 _ => {}
512 }
513 }
514 }
515 }
516
517 fn comment(tcx: TyCtxt<'_>, SourceInfo { span, scope }: SourceInfo) -> String {
518 format!("scope {} at {}", scope.index(), tcx.sess.source_map().span_to_embeddable_string(span))
519 }
520
521 /// Prints local variables in a scope tree.
write_scope_tree( tcx: TyCtxt<'_>, body: &Body<'_>, scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>, w: &mut dyn Write, parent: SourceScope, depth: usize, ) -> io::Result<()>522 fn write_scope_tree(
523 tcx: TyCtxt<'_>,
524 body: &Body<'_>,
525 scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
526 w: &mut dyn Write,
527 parent: SourceScope,
528 depth: usize,
529 ) -> io::Result<()> {
530 let indent = depth * INDENT.len();
531
532 // Local variable debuginfo.
533 for var_debug_info in &body.var_debug_info {
534 if var_debug_info.source_info.scope != parent {
535 // Not declared in this scope.
536 continue;
537 }
538
539 let indented_debug_info = format!(
540 "{0:1$}debug {2} => {3:?};",
541 INDENT, indent, var_debug_info.name, var_debug_info.value,
542 );
543
544 writeln!(
545 w,
546 "{0:1$} // in {2}",
547 indented_debug_info,
548 ALIGN,
549 comment(tcx, var_debug_info.source_info),
550 )?;
551 }
552
553 // Local variable types.
554 for (local, local_decl) in body.local_decls.iter_enumerated() {
555 if (1..body.arg_count + 1).contains(&local.index()) {
556 // Skip over argument locals, they're printed in the signature.
557 continue;
558 }
559
560 if local_decl.source_info.scope != parent {
561 // Not declared in this scope.
562 continue;
563 }
564
565 let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };
566
567 let mut indented_decl =
568 format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
569 if let Some(user_ty) = &local_decl.user_ty {
570 for user_ty in user_ty.projections() {
571 write!(indented_decl, " as {:?}", user_ty).unwrap();
572 }
573 }
574 indented_decl.push(';');
575
576 let local_name =
577 if local == RETURN_PLACE { " return place".to_string() } else { String::new() };
578
579 writeln!(
580 w,
581 "{0:1$} //{2} in {3}",
582 indented_decl,
583 ALIGN,
584 local_name,
585 comment(tcx, local_decl.source_info),
586 )?;
587 }
588
589 let children = match scope_tree.get(&parent) {
590 Some(children) => children,
591 None => return Ok(()),
592 };
593
594 for &child in children {
595 let child_data = &body.source_scopes[child];
596 assert_eq!(child_data.parent_scope, Some(parent));
597
598 let (special, span) = if let Some((callee, callsite_span)) = child_data.inlined {
599 (
600 format!(
601 " (inlined {}{})",
602 if callee.def.requires_caller_location(tcx) { "#[track_caller] " } else { "" },
603 callee
604 ),
605 Some(callsite_span),
606 )
607 } else {
608 (String::new(), None)
609 };
610
611 let indented_header = format!("{0:1$}scope {2}{3} {{", "", indent, child.index(), special);
612
613 if let Some(span) = span {
614 writeln!(
615 w,
616 "{0:1$} // at {2}",
617 indented_header,
618 ALIGN,
619 tcx.sess.source_map().span_to_embeddable_string(span),
620 )?;
621 } else {
622 writeln!(w, "{}", indented_header)?;
623 }
624
625 write_scope_tree(tcx, body, scope_tree, w, child, depth + 1)?;
626 writeln!(w, "{0:1$}}}", "", depth * INDENT.len())?;
627 }
628
629 Ok(())
630 }
631
632 /// Write out a human-readable textual representation of the MIR's `fn` type and the types of its
633 /// local variables (both user-defined bindings and compiler temporaries).
write_mir_intro<'tcx>( tcx: TyCtxt<'tcx>, body: &Body<'_>, w: &mut dyn Write, ) -> io::Result<()>634 pub fn write_mir_intro<'tcx>(
635 tcx: TyCtxt<'tcx>,
636 body: &Body<'_>,
637 w: &mut dyn Write,
638 ) -> io::Result<()> {
639 write_mir_sig(tcx, body, w)?;
640 writeln!(w, "{{")?;
641
642 // construct a scope tree and write it out
643 let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
644 for (index, scope_data) in body.source_scopes.iter().enumerate() {
645 if let Some(parent) = scope_data.parent_scope {
646 scope_tree.entry(parent).or_default().push(SourceScope::new(index));
647 } else {
648 // Only the argument scope has no parent, because it's the root.
649 assert_eq!(index, OUTERMOST_SOURCE_SCOPE.index());
650 }
651 }
652
653 write_scope_tree(tcx, body, &scope_tree, w, OUTERMOST_SOURCE_SCOPE, 1)?;
654
655 // Add an empty line before the first block is printed.
656 writeln!(w)?;
657
658 Ok(())
659 }
660
661 /// Find all `AllocId`s mentioned (recursively) in the MIR body and print their corresponding
662 /// allocations.
write_allocations<'tcx>( tcx: TyCtxt<'tcx>, body: &Body<'_>, w: &mut dyn Write, ) -> io::Result<()>663 pub fn write_allocations<'tcx>(
664 tcx: TyCtxt<'tcx>,
665 body: &Body<'_>,
666 w: &mut dyn Write,
667 ) -> io::Result<()> {
668 fn alloc_ids_from_alloc(alloc: &Allocation) -> impl DoubleEndedIterator<Item = AllocId> + '_ {
669 alloc.relocations().values().map(|id| *id)
670 }
671 fn alloc_ids_from_const(val: ConstValue<'_>) -> impl Iterator<Item = AllocId> + '_ {
672 match val {
673 ConstValue::Scalar(interpret::Scalar::Ptr(ptr, _size)) => {
674 Either::Left(Either::Left(std::iter::once(ptr.provenance)))
675 }
676 ConstValue::Scalar(interpret::Scalar::Int { .. }) => {
677 Either::Left(Either::Right(std::iter::empty()))
678 }
679 ConstValue::ByRef { alloc, .. } | ConstValue::Slice { data: alloc, .. } => {
680 Either::Right(alloc_ids_from_alloc(alloc))
681 }
682 }
683 }
684 struct CollectAllocIds(BTreeSet<AllocId>);
685 impl<'tcx> TypeVisitor<'tcx> for CollectAllocIds {
686 fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
687 // `AllocId`s are only inside of `ConstKind::Value` which
688 // can't be part of the anon const default substs.
689 None
690 }
691
692 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
693 if let ty::ConstKind::Value(val) = c.val {
694 self.0.extend(alloc_ids_from_const(val));
695 }
696 c.super_visit_with(self)
697 }
698 }
699 let mut visitor = CollectAllocIds(Default::default());
700 body.visit_with(&mut visitor);
701 // `seen` contains all seen allocations, including the ones we have *not* printed yet.
702 // The protocol is to first `insert` into `seen`, and only if that returns `true`
703 // then push to `todo`.
704 let mut seen = visitor.0;
705 let mut todo: Vec<_> = seen.iter().copied().collect();
706 while let Some(id) = todo.pop() {
707 let mut write_allocation_track_relocs =
708 |w: &mut dyn Write, alloc: &Allocation| -> io::Result<()> {
709 // `.rev()` because we are popping them from the back of the `todo` vector.
710 for id in alloc_ids_from_alloc(alloc).rev() {
711 if seen.insert(id) {
712 todo.push(id);
713 }
714 }
715 write!(w, "{}", display_allocation(tcx, alloc))
716 };
717 write!(w, "\n{}", id)?;
718 match tcx.get_global_alloc(id) {
719 // This can't really happen unless there are bugs, but it doesn't cost us anything to
720 // gracefully handle it and allow buggy rustc to be debugged via allocation printing.
721 None => write!(w, " (deallocated)")?,
722 Some(GlobalAlloc::Function(inst)) => write!(w, " (fn: {})", inst)?,
723 Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => {
724 match tcx.eval_static_initializer(did) {
725 Ok(alloc) => {
726 write!(w, " (static: {}, ", tcx.def_path_str(did))?;
727 write_allocation_track_relocs(w, alloc)?;
728 }
729 Err(_) => write!(
730 w,
731 " (static: {}, error during initializer evaluation)",
732 tcx.def_path_str(did)
733 )?,
734 }
735 }
736 Some(GlobalAlloc::Static(did)) => {
737 write!(w, " (extern static: {})", tcx.def_path_str(did))?
738 }
739 Some(GlobalAlloc::Memory(alloc)) => {
740 write!(w, " (")?;
741 write_allocation_track_relocs(w, alloc)?
742 }
743 }
744 writeln!(w)?;
745 }
746 Ok(())
747 }
748
749 /// Dumps the size and metadata and content of an allocation to the given writer.
750 /// The expectation is that the caller first prints other relevant metadata, so the exact
751 /// format of this function is (*without* leading or trailing newline):
752 ///
753 /// ```text
754 /// size: {}, align: {}) {
755 /// <bytes>
756 /// }
757 /// ```
758 ///
759 /// The byte format is similar to how hex editors print bytes. Each line starts with the address of
760 /// the start of the line, followed by all bytes in hex format (space separated).
761 /// If the allocation is small enough to fit into a single line, no start address is given.
762 /// After the hex dump, an ascii dump follows, replacing all unprintable characters (control
763 /// characters or characters whose value is larger than 127) with a `.`
764 /// This also prints relocations adequately.
display_allocation<Tag, Extra>( tcx: TyCtxt<'tcx>, alloc: &'a Allocation<Tag, Extra>, ) -> RenderAllocation<'a, 'tcx, Tag, Extra>765 pub fn display_allocation<Tag, Extra>(
766 tcx: TyCtxt<'tcx>,
767 alloc: &'a Allocation<Tag, Extra>,
768 ) -> RenderAllocation<'a, 'tcx, Tag, Extra> {
769 RenderAllocation { tcx, alloc }
770 }
771
772 #[doc(hidden)]
773 pub struct RenderAllocation<'a, 'tcx, Tag, Extra> {
774 tcx: TyCtxt<'tcx>,
775 alloc: &'a Allocation<Tag, Extra>,
776 }
777
778 impl<Tag: Provenance, Extra> std::fmt::Display for RenderAllocation<'a, 'tcx, Tag, Extra> {
fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result779 fn fmt(&self, w: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
780 let RenderAllocation { tcx, alloc } = *self;
781 write!(w, "size: {}, align: {})", alloc.size().bytes(), alloc.align.bytes())?;
782 if alloc.size() == Size::ZERO {
783 // We are done.
784 return write!(w, " {{}}");
785 }
786 // Write allocation bytes.
787 writeln!(w, " {{")?;
788 write_allocation_bytes(tcx, alloc, w, " ")?;
789 write!(w, "}}")?;
790 Ok(())
791 }
792 }
793
write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result794 fn write_allocation_endline(w: &mut dyn std::fmt::Write, ascii: &str) -> std::fmt::Result {
795 for _ in 0..(BYTES_PER_LINE - ascii.chars().count()) {
796 write!(w, " ")?;
797 }
798 writeln!(w, " │ {}", ascii)
799 }
800
801 /// Number of bytes to print per allocation hex dump line.
802 const BYTES_PER_LINE: usize = 16;
803
804 /// Prints the line start address and returns the new line start address.
write_allocation_newline( w: &mut dyn std::fmt::Write, mut line_start: Size, ascii: &str, pos_width: usize, prefix: &str, ) -> Result<Size, std::fmt::Error>805 fn write_allocation_newline(
806 w: &mut dyn std::fmt::Write,
807 mut line_start: Size,
808 ascii: &str,
809 pos_width: usize,
810 prefix: &str,
811 ) -> Result<Size, std::fmt::Error> {
812 write_allocation_endline(w, ascii)?;
813 line_start += Size::from_bytes(BYTES_PER_LINE);
814 write!(w, "{}0x{:02$x} │ ", prefix, line_start.bytes(), pos_width)?;
815 Ok(line_start)
816 }
817
818 /// The `prefix` argument allows callers to add an arbitrary prefix before each line (even if there
819 /// is only one line). Note that your prefix should contain a trailing space as the lines are
820 /// printed directly after it.
write_allocation_bytes<Tag: Provenance, Extra>( tcx: TyCtxt<'tcx>, alloc: &Allocation<Tag, Extra>, w: &mut dyn std::fmt::Write, prefix: &str, ) -> std::fmt::Result821 fn write_allocation_bytes<Tag: Provenance, Extra>(
822 tcx: TyCtxt<'tcx>,
823 alloc: &Allocation<Tag, Extra>,
824 w: &mut dyn std::fmt::Write,
825 prefix: &str,
826 ) -> std::fmt::Result {
827 let num_lines = alloc.size().bytes_usize().saturating_sub(BYTES_PER_LINE);
828 // Number of chars needed to represent all line numbers.
829 let pos_width = hex_number_length(alloc.size().bytes());
830
831 if num_lines > 0 {
832 write!(w, "{}0x{:02$x} │ ", prefix, 0, pos_width)?;
833 } else {
834 write!(w, "{}", prefix)?;
835 }
836
837 let mut i = Size::ZERO;
838 let mut line_start = Size::ZERO;
839
840 let ptr_size = tcx.data_layout.pointer_size;
841
842 let mut ascii = String::new();
843
844 let oversized_ptr = |target: &mut String, width| {
845 if target.len() > width {
846 write!(target, " ({} ptr bytes)", ptr_size.bytes()).unwrap();
847 }
848 };
849
850 while i < alloc.size() {
851 // The line start already has a space. While we could remove that space from the line start
852 // printing and unconditionally print a space here, that would cause the single-line case
853 // to have a single space before it, which looks weird.
854 if i != line_start {
855 write!(w, " ")?;
856 }
857 if let Some(&tag) = alloc.relocations().get(&i) {
858 // Memory with a relocation must be defined
859 let j = i.bytes_usize();
860 let offset = alloc
861 .inspect_with_uninit_and_ptr_outside_interpreter(j..j + ptr_size.bytes_usize());
862 let offset = read_target_uint(tcx.data_layout.endian, offset).unwrap();
863 let offset = Size::from_bytes(offset);
864 let relocation_width = |bytes| bytes * 3;
865 let ptr = Pointer::new(tag, offset);
866 let mut target = format!("{:?}", ptr);
867 if target.len() > relocation_width(ptr_size.bytes_usize() - 1) {
868 // This is too long, try to save some space.
869 target = format!("{:#?}", ptr);
870 }
871 if ((i - line_start) + ptr_size).bytes_usize() > BYTES_PER_LINE {
872 // This branch handles the situation where a relocation starts in the current line
873 // but ends in the next one.
874 let remainder = Size::from_bytes(BYTES_PER_LINE) - (i - line_start);
875 let overflow = ptr_size - remainder;
876 let remainder_width = relocation_width(remainder.bytes_usize()) - 2;
877 let overflow_width = relocation_width(overflow.bytes_usize() - 1) + 1;
878 ascii.push('╾');
879 for _ in 0..remainder.bytes() - 1 {
880 ascii.push('─');
881 }
882 if overflow_width > remainder_width && overflow_width >= target.len() {
883 // The case where the relocation fits into the part in the next line
884 write!(w, "╾{0:─^1$}", "", remainder_width)?;
885 line_start =
886 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
887 ascii.clear();
888 write!(w, "{0:─^1$}╼", target, overflow_width)?;
889 } else {
890 oversized_ptr(&mut target, remainder_width);
891 write!(w, "╾{0:─^1$}", target, remainder_width)?;
892 line_start =
893 write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
894 write!(w, "{0:─^1$}╼", "", overflow_width)?;
895 ascii.clear();
896 }
897 for _ in 0..overflow.bytes() - 1 {
898 ascii.push('─');
899 }
900 ascii.push('╼');
901 i += ptr_size;
902 continue;
903 } else {
904 // This branch handles a relocation that starts and ends in the current line.
905 let relocation_width = relocation_width(ptr_size.bytes_usize() - 1);
906 oversized_ptr(&mut target, relocation_width);
907 ascii.push('╾');
908 write!(w, "╾{0:─^1$}╼", target, relocation_width)?;
909 for _ in 0..ptr_size.bytes() - 2 {
910 ascii.push('─');
911 }
912 ascii.push('╼');
913 i += ptr_size;
914 }
915 } else if alloc.init_mask().is_range_initialized(i, i + Size::from_bytes(1)).is_ok() {
916 let j = i.bytes_usize();
917
918 // Checked definedness (and thus range) and relocations. This access also doesn't
919 // influence interpreter execution but is only for debugging.
920 let c = alloc.inspect_with_uninit_and_ptr_outside_interpreter(j..j + 1)[0];
921 write!(w, "{:02x}", c)?;
922 if c.is_ascii_control() || c >= 0x80 {
923 ascii.push('.');
924 } else {
925 ascii.push(char::from(c));
926 }
927 i += Size::from_bytes(1);
928 } else {
929 write!(w, "__")?;
930 ascii.push('░');
931 i += Size::from_bytes(1);
932 }
933 // Print a new line header if the next line still has some bytes to print.
934 if i == line_start + Size::from_bytes(BYTES_PER_LINE) && i != alloc.size() {
935 line_start = write_allocation_newline(w, line_start, &ascii, pos_width, prefix)?;
936 ascii.clear();
937 }
938 }
939 write_allocation_endline(w, &ascii)?;
940
941 Ok(())
942 }
943
write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Result<()>944 fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write) -> io::Result<()> {
945 use rustc_hir::def::DefKind;
946
947 trace!("write_mir_sig: {:?}", body.source.instance);
948 let def_id = body.source.def_id();
949 let kind = tcx.def_kind(def_id);
950 let is_function = match kind {
951 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) => true,
952 _ => tcx.is_closure(def_id),
953 };
954 match (kind, body.source.promoted) {
955 (_, Some(i)) => write!(w, "{:?} in ", i)?,
956 (DefKind::Const | DefKind::AssocConst, _) => write!(w, "const ")?,
957 (DefKind::Static, _) => {
958 write!(w, "static {}", if tcx.is_mutable_static(def_id) { "mut " } else { "" })?
959 }
960 (_, _) if is_function => write!(w, "fn ")?,
961 (DefKind::AnonConst | DefKind::InlineConst, _) => {} // things like anon const, not an item
962 _ => bug!("Unexpected def kind {:?}", kind),
963 }
964
965 ty::print::with_forced_impl_filename_line(|| {
966 // see notes on #41697 elsewhere
967 write!(w, "{}", tcx.def_path_str(def_id))
968 })?;
969
970 if body.source.promoted.is_none() && is_function {
971 write!(w, "(")?;
972
973 // fn argument types.
974 for (i, arg) in body.args_iter().enumerate() {
975 if i != 0 {
976 write!(w, ", ")?;
977 }
978 write!(w, "{:?}: {}", Place::from(arg), body.local_decls[arg].ty)?;
979 }
980
981 write!(w, ") -> {}", body.return_ty())?;
982 } else {
983 assert_eq!(body.arg_count, 0);
984 write!(w, ": {} =", body.return_ty())?;
985 }
986
987 if let Some(yield_ty) = body.yield_ty() {
988 writeln!(w)?;
989 writeln!(w, "yields {}", yield_ty)?;
990 }
991
992 write!(w, " ")?;
993 // Next thing that gets printed is the opening {
994
995 Ok(())
996 }
997
write_user_type_annotations( tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn Write, ) -> io::Result<()>998 fn write_user_type_annotations(
999 tcx: TyCtxt<'_>,
1000 body: &Body<'_>,
1001 w: &mut dyn Write,
1002 ) -> io::Result<()> {
1003 if !body.user_type_annotations.is_empty() {
1004 writeln!(w, "| User Type Annotations")?;
1005 }
1006 for (index, annotation) in body.user_type_annotations.iter_enumerated() {
1007 writeln!(
1008 w,
1009 "| {:?}: {:?} at {}",
1010 index.index(),
1011 annotation.user_ty,
1012 tcx.sess.source_map().span_to_embeddable_string(annotation.span)
1013 )?;
1014 }
1015 if !body.user_type_annotations.is_empty() {
1016 writeln!(w, "|")?;
1017 }
1018 Ok(())
1019 }
1020
dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId>1021 pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
1022 if let Some(i) = single {
1023 vec![i]
1024 } else {
1025 tcx.mir_keys(()).iter().map(|def_id| def_id.to_def_id()).collect()
1026 }
1027 }
1028
1029 /// Calc converted u64 decimal into hex and return it's length in chars
1030 ///
1031 /// ```ignore (cannot-test-private-function)
1032 /// assert_eq!(1, hex_number_length(0));
1033 /// assert_eq!(1, hex_number_length(1));
1034 /// assert_eq!(2, hex_number_length(16));
1035 /// ```
hex_number_length(x: u64) -> usize1036 fn hex_number_length(x: u64) -> usize {
1037 if x == 0 {
1038 return 1;
1039 }
1040 let mut length = 0;
1041 let mut x_left = x;
1042 while x_left > 0 {
1043 x_left /= 16;
1044 length += 1;
1045 }
1046 length
1047 }
1048