Skip to main content

charon_lib/transform/simplify_output/
anon_const_to_call.rs

1use std::collections::{HashMap, HashSet};
2
3use crate::transform::CowBox;
4use crate::transform::{TransformCtx, ctx::UllbcPass};
5use crate::ullbc_ast::*;
6
7pub struct Transform {
8    anon_consts: HashMap<GlobalDeclId, FunDeclId>,
9}
10
11/// These globals and their initializers must remain available: a constant repeat cannot use a
12/// runtime call to evaluate its elements, as the element type may not be `Copy`/`Clone`.
13pub(super) fn globals_in_constant_repeats(krate: &TranslatedCrate) -> HashSet<GlobalDeclId> {
14    let mut globals = HashSet::new();
15    krate.dyn_visit(|kind: &ConstantExprKind| {
16        if let ConstantExprKind::Repeat { .. } = kind {
17            kind.dyn_visit(|gref: &GlobalDeclRef| {
18                globals.insert(gref.id);
19            });
20        }
21    });
22    globals
23}
24
25impl Transform {
26    pub fn new(ctx: &mut TransformCtx) -> CowBox<dyn UllbcPass> {
27        // Map each anon const id to its initializer.
28        let anon_consts = ctx
29            .translated
30            .global_decls
31            .iter()
32            .filter(|gdecl| matches!(gdecl.global_kind, GlobalKind::AnonConst))
33            .filter_map(|gdecl| Some((gdecl.def_id, gdecl.init_fun_id()?)))
34            .collect();
35        CowBox::Owned(Box::new(Transform { anon_consts }))
36    }
37}
38impl UllbcPass for Transform {
39    fn should_run(&self, options: &crate::options::TranslateOptions) -> bool {
40        options.inline_anon_consts && !self.anon_consts.is_empty()
41    }
42    fn transform_body(&self, _ctx: &mut TransformCtx, body: &mut ullbc_ast::ExprBody) {
43        for block_id in body.body.indices() {
44            let Some(block) = body.body.get_mut(block_id) else {
45                continue;
46            };
47            let mut new_calls: Vec<(Place, Call)> = vec![];
48            block.dyn_visit_in_body_mut(|op: &mut Operand| {
49                if let Operand::Const(c) = op
50                    && let ConstantExprKind::Global(gref) = c.kind()
51                    && let Some(initializer) = self.anon_consts.get(&gref.id)
52                {
53                    let return_place = body.locals.new_var(None, c.ty().clone());
54                    new_calls.push((
55                        return_place.clone(),
56                        Call {
57                            func: FnOperand::Regular(FnPtr::new(
58                                FnPtrKind::Fun(*initializer),
59                                gref.generics.clone(),
60                            )),
61                            args: vec![],
62                            safety: CallSafety::Inherit,
63                        },
64                    ));
65                    *op = Operand::Move(return_place);
66                }
67            });
68            if !new_calls.is_empty() {
69                let kind = body.body[block_id].kind;
70                // Move the current block out of the way.
71                let block = body.body[block_id].take();
72                let mut next_block = body.body.push(block);
73                // Each new block jumps to the previous one after completion
74                for (dest, call) in new_calls {
75                    // Const eval mustn't unwind into runtime.
76                    let unwind = body
77                        .body
78                        .push(BlockData::new_unreachable(kind.further_unwind_kind()));
79                    next_block = body.body.push(BlockData {
80                        statements: vec![Statement::new(
81                            Span::dummy(),
82                            StatementKind::StorageLive(dest.as_local().unwrap()),
83                        )],
84                        terminator: Terminator::new(
85                            Span::dummy(),
86                            TerminatorKind::Call {
87                                call,
88                                dest,
89                                target: next_block,
90                                on_unwind: unwind,
91                            },
92                        ),
93                        kind,
94                    });
95                }
96                // Instead of the current block, start evaluating the new bodies.
97                body.body[block_id] = BlockData::new_goto(Span::dummy(), next_block, kind);
98            }
99        }
100    }
101    fn finalize(&self, ctx: &mut TransformCtx) {
102        let repeated_globals = globals_in_constant_repeats(&ctx.translated);
103        for gid in self.anon_consts.keys() {
104            if !repeated_globals.contains(gid) {
105                ctx.translated.global_decls.remove(*gid);
106            }
107        }
108    }
109}