Skip to main content

charon_lib/transform/resugar/
reconstruct_static_accesses.rs

1//! MIR places can't name statics, so rustc accesses a static through a temporary holding its
2//! address, e.g. `_1 = const {alloc}; _0 = copy (*_1)` where the constant points to the static.
3//! We turn `*_1` back into the static itself and remove the temporary.
4//! This is needed to reliably tell what static accesses are unsafe (see `HasSafety`), as rustc
5//! will lower safe static access to otherwise unsafe raw pointer accesses.
6use rustc_hash::FxHashMap as HashMap;
7
8use crate::transform::TransformCtx;
9use crate::transform::ctx::UllbcPass;
10use crate::ullbc_ast::*;
11
12/// A local assigned the address of a static.
13struct StaticInfo {
14    global: GlobalDeclRef,
15    assign_loc: StmtLoc,
16    uses: usize,
17    derefs: usize,
18}
19
20pub struct Transform;
21impl UllbcPass for Transform {
22    fn transform_body(&self, ctx: &mut TransformCtx, body: &mut ExprBody) {
23        // Find the locals assigned the address of a static, and where they're assigned.
24        let mut statics: HashMap<LocalId, StaticInfo> = body
25            .body
26            .iter_enumerated()
27            .flat_map(|(block_id, block)| {
28                let locs = (0..).map(move |i| StmtLoc::new(block_id, i));
29                locs.zip(&block.statements)
30            })
31            .filter_map(|(loc, st)| {
32                let (dest, rvalue) = &st.kind.as_assign()?;
33                let local = dest
34                    .as_local()
35                    .filter(|l| !body.locals.is_return_or_arg(*l))?;
36                // This is only sound to do for raw pointers! Eliminating refs would
37                // skip a retagging, which could miss UB
38                let global = match rvalue {
39                    Rvalue::Use(Operand::Const(c), _)
40                        if let ConstantExprKind::Ptr(_, pointee, _) = c.kind()
41                            && let GlobalPlaceKind::Global(GlobalProvenance::Global(global)) =
42                                &pointee.kind =>
43                    {
44                        global
45                    }
46                    // Thread-local statics are accessed through `Rvalue::ThreadLocalRef` in MIR.
47                    Rvalue::RawPtr { place, .. } => place.kind.as_global()?,
48                    _ => return None,
49                };
50                let decl = ctx.translated.global_decls.get(global.id)?;
51                if !matches!(decl.global_kind, GlobalKind::Static { .. }) {
52                    return None;
53                }
54                let info = StaticInfo {
55                    global: global.clone(),
56                    assign_loc: loc,
57                    uses: 0,
58                    derefs: 0,
59                };
60                Some((local, info))
61            })
62            .collect();
63        // Discard locals mentioned in drop flags or type constraints.
64        body.locals.dyn_visit_in_body(|place: &Place| {
65            if let Some(local) = place.as_local() {
66                statics.remove(&local);
67            }
68        });
69        if statics.is_empty() {
70            return;
71        }
72
73        // All desugared uses of a static go through its address, i.e. all its uses
74        // are `*_static_addr` except when it is assigned to.
75        body.body.dyn_visit_in_body(|place: &Place| {
76            if let Some(local) = place.as_local()
77                && let Some(info) = statics.get_mut(&local)
78            {
79                info.uses += 1;
80            } else if let Some((sub, ProjectionElem::Deref)) = place.as_projection()
81                && let Some(local) = sub.as_local()
82                && let Some(info) = statics.get_mut(&local)
83            {
84                info.derefs += 1;
85            }
86        });
87        statics.retain(|_, info| info.uses == info.derefs + 1);
88        if statics.is_empty() {
89            return;
90        }
91
92        // Remove the initial assignment (`_static_addr = const {alloc}`)
93        for info in statics.values() {
94            body[info.assign_loc].kind = StatementKind::Nop;
95        }
96        // ...and replace all derefs of the local with the static itself.
97        body.body.dyn_visit_in_body_mut(|place: &mut Place| {
98            if let Some((sub, ProjectionElem::Deref)) = place.as_projection()
99                && let Some(local) = sub.as_local()
100                && let Some(info) = statics.get(&local)
101            {
102                *place = Place::new_global(info.global.clone(), place.ty.clone());
103            }
104        });
105    }
106}