Skip to main content

rustc_mir_transform/
strip_debuginfo.rs

1use rustc_middle::mir::*;
2use rustc_middle::ty::TyCtxt;
3use rustc_mir_dataflow::debuginfo::debuginfo_locals;
4use rustc_session::config::MirStripDebugInfo;
5
6use crate::PassPolicy;
7
8/// Conditionally remove some of the VarDebugInfo in MIR.
9///
10/// In particular, stripping non-parameter debug info for tiny, primitive-like
11/// methods in core saves work later, and nobody ever wanted to use it anyway.
12pub(super) struct StripDebugInfo;
13
14impl<'tcx> crate::MirPass<'tcx> for StripDebugInfo {
15    fn policy(&self, sess: &rustc_session::Session) -> PassPolicy {
16        PassPolicy::optional_non_optimization(
17            sess.opts.unstable_opts.mir_strip_debuginfo != MirStripDebugInfo::None,
18        )
19    }
20
21    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
22        match tcx.sess.opts.unstable_opts.mir_strip_debuginfo {
23            MirStripDebugInfo::None => return,
24            MirStripDebugInfo::AllLocals => {}
25            MirStripDebugInfo::LocalsInTinyFunctions
26                if let TerminatorKind::Return { .. } =
27                    body.basic_blocks[START_BLOCK].terminator().kind => {}
28            MirStripDebugInfo::LocalsInTinyFunctions => return,
29        }
30
31        body.var_debug_info.retain(|vdi| {
32            matches!(
33                vdi.value,
34                VarDebugInfoContents::Place(place)
35                    if place.local.as_usize() <= body.arg_count && place.local != RETURN_PLACE,
36            )
37        });
38
39        drop_invalid_debuginfos(body);
40    }
41}
42
43// Drop invalid debuginfos when strip locals in `var_debug_info`.
44pub(super) fn drop_invalid_debuginfos(body: &mut Body<'_>) {
45    let debuginfo_locals = debuginfo_locals(body);
46    for data in body.basic_blocks.as_mut_preserves_cfg() {
47        for stmt in data.statements.iter_mut() {
48            stmt.debuginfos.retain_locals(&debuginfo_locals);
49        }
50        data.after_last_stmt_debuginfos.retain_locals(&debuginfo_locals);
51    }
52}