rustc_mir_transform/
deref_separator.rs
1use rustc_middle::mir::visit::NonUseContext::VarDebugInfo;
2use rustc_middle::mir::visit::{MutVisitor, PlaceContext};
3use rustc_middle::mir::*;
4use rustc_middle::ty::TyCtxt;
5
6use crate::patch::MirPatch;
7
8pub(super) struct Derefer;
9
10struct DerefChecker<'a, 'tcx> {
11 tcx: TyCtxt<'tcx>,
12 patcher: MirPatch<'tcx>,
13 local_decls: &'a LocalDecls<'tcx>,
14}
15
16impl<'a, 'tcx> MutVisitor<'tcx> for DerefChecker<'a, 'tcx> {
17 fn tcx(&self) -> TyCtxt<'tcx> {
18 self.tcx
19 }
20
21 fn visit_place(&mut self, place: &mut Place<'tcx>, cntxt: PlaceContext, loc: Location) {
22 if !place.projection.is_empty()
23 && cntxt != PlaceContext::NonUse(VarDebugInfo)
24 && place.projection[1..].contains(&ProjectionElem::Deref)
25 {
26 let mut place_local = place.local;
27 let mut last_len = 0;
28 let mut last_deref_idx = 0;
29
30 for (idx, elem) in place.projection[0..].iter().enumerate() {
31 if *elem == ProjectionElem::Deref {
32 last_deref_idx = idx;
33 }
34 }
35
36 for (idx, (p_ref, p_elem)) in place.iter_projections().enumerate() {
37 if !p_ref.projection.is_empty() && p_elem == ProjectionElem::Deref {
38 let ty = p_ref.ty(self.local_decls, self.tcx).ty;
39 let temp = self.patcher.new_local_with_info(
40 ty,
41 self.local_decls[p_ref.local].source_info.span,
42 LocalInfo::DerefTemp,
43 );
44
45 let deref_place = Place::from(place_local)
48 .project_deeper(&p_ref.projection[last_len..], self.tcx);
49
50 self.patcher.add_assign(
51 loc,
52 Place::from(temp),
53 Rvalue::CopyForDeref(deref_place),
54 );
55 place_local = temp;
56 last_len = p_ref.projection.len();
57
58 if idx == last_deref_idx {
60 let temp_place =
61 Place::from(temp).project_deeper(&place.projection[idx..], self.tcx);
62 *place = temp_place;
63 }
64 }
65 }
66 }
67 }
68}
69
70pub(super) fn deref_finder<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
71 let patch = MirPatch::new(body);
72 let mut checker = DerefChecker { tcx, patcher: patch, local_decls: &body.local_decls };
73
74 for (bb, data) in body.basic_blocks.as_mut_preserves_cfg().iter_enumerated_mut() {
75 checker.visit_basic_block_data(bb, data);
76 }
77
78 checker.patcher.apply(body);
79}
80
81impl<'tcx> crate::MirPass<'tcx> for Derefer {
82 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
83 deref_finder(tcx, body);
84 }
85
86 fn is_required(&self) -> bool {
87 true
88 }
89}