Skip to main content

charon_lib/transform/resugar/
reconstruct_box_derefs.rs

1//! Resugar the box derefs that got desugared in elaborated MIR.
2//!
3//! In elaborated MIR, box derefs become actual accesses to the contained raw pointer. Under
4//! `--treat-box-as-builtin`, we convert these back to derefs on the box.
5use std::ops::ControlFlow;
6
7use crate::transform::TransformCtx;
8use crate::transform::ctx::UllbcPass;
9use crate::ullbc_ast::*;
10
11pub struct Transform;
12
13/// Look for
14/// ```ignore
15/// transmute::<Unique<T>, *const T>(copy (*b))
16/// transmute::<NonNull<T>, *const T>(copy (*b).0)
17/// ```
18/// Returns `b`
19fn box_pointer_assignment(rvalue: &Rvalue) -> Option<Place> {
20    let Rvalue::UnaryOp(
21        UnOp::Cast(CastKind::Transmute(raw_ptr_ty)),
22        Operand::Copy(hidden_pointer, _),
23    ) = &rvalue
24    else {
25        return None;
26    };
27    let unique_place = match hidden_pointer.as_projection()? {
28        (field_base, ProjectionElem::Field(_, FieldId::ZERO)) => field_base,
29        _ => hidden_pointer,
30    };
31    let (box_place, ProjectionElem::Deref) = unique_place.as_projection()? else {
32        return None;
33    };
34    let TyKind::Adt(tref) = box_place.ty().kind() else {
35        return None;
36    };
37    if !tref.is_box() {
38        return None;
39    }
40    let box_generics = &tref.generics;
41    if !box_generics.types[0].eq_modulo_regions(raw_ptr_ty.as_raw_ptr()?.0) {
42        return None;
43    }
44    Some(box_place.clone())
45}
46
47#[derive(Default)]
48struct LocalStatus {
49    /// Whether that local is the target of the special `transmute` statement we're looking for.
50    /// Stores the box `b`.
51    box_assignment: Option<(StmtLoc, Place)>,
52    /// Whether that local is the target of more than one such special `transmute`.
53    ambiguous: bool,
54    /// Whether that local is ever used outside of a deref or metadata projection (apart from the
55    /// initial assignment).
56    used_outside_projections: bool,
57}
58
59impl LocalStatus {
60    fn rewritable_box(&self) -> Option<&(StmtLoc, Place)> {
61        if self.ambiguous || self.used_outside_projections {
62            return None;
63        }
64        self.box_assignment.as_ref()
65    }
66}
67
68struct LocalStatusCollector {
69    local_status: IndexVec<LocalId, LocalStatus>,
70    current_statement: Option<StmtLoc>,
71}
72
73impl Visitor for LocalStatusCollector {
74    type Break = std::convert::Infallible;
75}
76
77impl VisitBody for LocalStatusCollector {
78    fn visit_place(&mut self, place: &Place) -> ControlFlow<Self::Break> {
79        match &place.kind {
80            // Skip uses of a local where the last projection is a deref or a metadata access.
81            PlaceKind::Projection(
82                subplace,
83                ProjectionElem::Deref | ProjectionElem::PtrMetadata,
84            ) if subplace.is_local() => {
85                return ControlFlow::Continue(());
86            }
87            // This didn't get caught by the branch above, so it's an invalid use.
88            PlaceKind::Local(local) => self.local_status[*local].used_outside_projections = true,
89            _ => {}
90        }
91        self.visit_inner(place)
92    }
93
94    fn visit_ullbc_statement(&mut self, st: &ullbc_ast::Statement) -> ControlFlow<Self::Break> {
95        if let StatementKind::Assign(dst, rvalue) = &st.kind
96            && let Some(local) = dst.as_local()
97            && let Some(box_place) = box_pointer_assignment(rvalue)
98        {
99            let status = &mut self.local_status[local];
100            if status.box_assignment.is_some() {
101                status.ambiguous = true;
102            } else {
103                let loc = self.current_statement.unwrap();
104                status.box_assignment = Some((loc, box_place));
105            }
106            // Ignore the assignment destination: this initialization is the one non-projected
107            // interaction allowed for the temporary pointer.
108            self.visit(rvalue)
109        } else {
110            self.visit_inner(st)
111        }
112    }
113}
114
115fn collect_local_status(body: &ExprBody) -> IndexVec<LocalId, LocalStatus> {
116    let mut collector = LocalStatusCollector {
117        local_status: body.locals.locals.map_ref(|_| Default::default()),
118        current_statement: None,
119    };
120    // Use in a drop flag or a type annotation counts as a non-deref use.
121    body.locals.dyn_visit_in_body(|place: &Place| {
122        if let Some(local) = place.as_local() {
123            collector.local_status[local].used_outside_projections = true;
124        }
125    });
126    for (block, block_data) in body.body.iter_enumerated() {
127        for (statement, st) in block_data.statements.iter().enumerate() {
128            collector.current_statement = Some(StmtLoc::new(block, statement));
129            let _ = collector.visit(st);
130        }
131        collector.current_statement = None;
132        let _ = collector.visit(&block_data.terminator);
133    }
134    collector.local_status
135}
136
137impl UllbcPass for Transform {
138    fn should_run(&self, options: &crate::options::TranslateOptions) -> bool {
139        options.treat_box_as_builtin
140    }
141
142    fn transform_body(&self, _ctx: &mut TransformCtx, body: &mut ExprBody) {
143        let local_status = collect_local_status(body);
144
145        body.body.dyn_visit_in_body_mut(|place: &mut Place| {
146            if let PlaceKind::Projection(
147                subplace,
148                ProjectionElem::Deref | ProjectionElem::PtrMetadata,
149            ) = &mut place.kind
150                && let Some(local) = subplace.as_local()
151                && let Some((_, box_place)) = local_status[local].rewritable_box()
152            {
153                **subplace = box_place.clone();
154            }
155        });
156
157        for status in local_status {
158            if let Some((assign_loc, _)) = status.rewritable_box() {
159                body[*assign_loc].kind = StatementKind::Nop;
160            }
161        }
162    }
163}