charon_lib/transform/
mod.rs

1pub mod ctx;
2pub mod typecheck_and_unify;
3pub mod utils;
4
5/// Passes that finish translation, i.e. required for the output to be a valid output.
6pub mod finish_translation {
7    pub mod filter_invisible_trait_impls;
8    pub mod insert_assign_return_unit;
9    pub mod insert_ptr_metadata;
10    pub mod insert_storage_lives;
11}
12
13/// Passes that compute extra info to be stored in the crate.
14pub mod add_missing_info {
15    pub mod compute_short_names;
16    pub mod recover_body_comments;
17    pub mod reorder_decls;
18    pub mod sccs;
19}
20
21/// Passes that effect some kind of normalization on the crate.
22pub mod normalize {
23    pub mod desugar_drops;
24    pub mod expand_associated_types;
25    pub mod filter_unreachable_blocks;
26    pub mod partial_monomorphization;
27    pub mod skip_trait_refs_when_known;
28    pub mod transform_dyn_trait_calls;
29}
30
31/// Passes that undo some lowering done by rustc to recover an operation closer to what the user
32/// wrote.
33pub mod resugar {
34    pub mod inline_local_panic_functions;
35    pub mod move_asserts_to_statements;
36    pub mod reconstruct_asserts;
37    pub mod reconstruct_boxes;
38    pub mod reconstruct_fallible_operations;
39    pub mod reconstruct_intrinsics;
40    pub mod reconstruct_matches;
41}
42
43/// Passes that make the output simpler/easier to consume.
44pub mod simplify_output {
45    pub mod filter_trivial_drops;
46    pub mod hide_allocator_param;
47    pub mod hide_marker_traits;
48    pub mod index_intermediate_assigns;
49    pub mod index_to_function_calls;
50    pub mod inline_anon_consts;
51    pub mod lift_associated_item_clauses;
52    pub mod ops_to_function_calls;
53    pub mod remove_adt_clauses;
54    pub mod remove_nops;
55    pub mod remove_unit_locals;
56    pub mod remove_unused_locals;
57    pub mod remove_unused_self_clause;
58    pub mod simplify_constants;
59    pub mod unbind_item_vars;
60    pub mod update_block_indices;
61}
62
63/// Passes that manipulate the control flow and reconstruct its structure.
64pub mod control_flow {
65    pub mod duplicate_return;
66    pub mod merge_goto_chains;
67    pub mod prettify_cfg;
68    pub mod ullbc_to_llbc;
69}
70
71use Pass::*;
72pub use ctx::TransformCtx;
73use ctx::{LlbcPass, TransformPass, UllbcPass};
74
75/// Item and type cleanup passes.
76pub static INITIAL_CLEANUP_PASSES: &[Pass] = &[
77    // Compute short names. We do it early to make pretty-printed output more legible in traces.
78    NonBody(&add_missing_info::compute_short_names::Transform),
79    // Check that translation emitted consistent types, and unify body lifetimes (best-effort).
80    NonBody(&typecheck_and_unify::Check::PostTranslation),
81    // # Micro-pass: filter the trait impls that were marked invisible since we couldn't filter
82    // them out earlier.
83    NonBody(&finish_translation::filter_invisible_trait_impls::Transform),
84    // Compute the metadata & insert for Rvalue
85    UnstructuredBody(&finish_translation::insert_ptr_metadata::Transform),
86    // # Micro-pass: add the missing assignments to the return value.
87    // When the function return type is unit, the generated MIR doesn't
88    // set the return value to `()`. This can be a concern: in the case
89    // of Aeneas, it means the return variable contains ⊥ upon returning.
90    // For this reason, when the function has return type unit, we insert
91    // an extra assignment just before returning.
92    UnstructuredBody(&finish_translation::insert_assign_return_unit::Transform),
93    // Insert `StorageLive` for locals that don't have one (that's allowed in MIR).
94    NonBody(&finish_translation::insert_storage_lives::Transform),
95    // Move clauses on associated types to be implied clauses of the trait.
96    NonBody(&simplify_output::lift_associated_item_clauses::Transform),
97    // # Micro-pass: hide some overly-common traits we don't need: Sized, Sync, Allocator, etc..
98    NonBody(&simplify_output::hide_marker_traits::Transform),
99    // Hide the `A` type parameter on standard library containers (`Box`, `Vec`, etc).
100    NonBody(&simplify_output::hide_allocator_param::Transform),
101    // # Micro-pass: remove the explicit `Self: Trait` clause of methods/assoc const declaration
102    // items if they're not used. This simplifies the graph of dependencies between definitions.
103    NonBody(&simplify_output::remove_unused_self_clause::Transform),
104    // Transform Drops into Calls to drop_in_place.
105    UnstructuredBody(&normalize::desugar_drops::Transform),
106    // # Micro-pass: whenever we reference a trait method on a known type, refer to the method
107    // `FunDecl` directly instead of going via a `TraitRef`. This is done before `reorder_decls` to
108    // remove some sources of mutual recursion.
109    NonBody(&normalize::skip_trait_refs_when_known::Transform),
110    // Transform dyn trait method calls to vtable function pointer calls
111    // This should be early to handle the calls before other transformations
112    UnstructuredBody(&normalize::transform_dyn_trait_calls::Transform),
113    // Change trait associated types to be type parameters instead. See the module for details.
114    // This also normalizes any use of an associated type that we can resolve.
115    NonBody(&normalize::expand_associated_types::Transform),
116    // `--remove-adt-clauses`: Remove all trait clauses from type declarations.
117    NonBody(&simplify_output::remove_adt_clauses::Transform),
118];
119
120/// Body cleanup passes on the ullbc.
121pub static ULLBC_PASSES: &[Pass] = &[
122    // Inline promoted and inline consts into their parent bodies.
123    UnstructuredBody(&simplify_output::inline_anon_consts::Transform),
124    // Remove drop statements that are noops.
125    UnstructuredBody(&simplify_output::filter_trivial_drops::Transform),
126    // Inline all asserts that correspond to dynamic checks into statements.
127    // The following pass will then merge the generated gotos as part of this substitution,
128    // and [reconstruct_fallible_operations] can then use the inlined asserts to reconstruct
129    // the fallible operations.
130    UnstructuredBody(&resugar::move_asserts_to_statements::Transform),
131    // # Micro-pass: merge single-origin gotos into their parent. This drastically reduces the
132    // graph size of the CFG.
133    // This must be done early as some resugaring passes depend on it.
134    UnstructuredBody(&control_flow::merge_goto_chains::Transform),
135    // # Micro-pass: Remove overflow/div-by-zero/bounds checks since they are already part of the
136    // arithmetic/array operation in the semantics of (U)LLBC.
137    // **WARNING**: this pass uses the fact that the dynamic checks introduced by Rustc use a
138    // special "assert" construct. Because of this, it must happen *before* the
139    // [reconstruct_asserts] pass. See the comments in [crate::remove_dynamic_checks].
140    // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of this,
141    // it must happen before passes that insert statements like [simplify_constants].
142    UnstructuredBody(&resugar::reconstruct_fallible_operations::Transform),
143    // Recognize calls to the `offset_of` intrinsics and replace them with the corresponding
144    // `NullOp`.
145    UnstructuredBody(&resugar::reconstruct_intrinsics::Transform),
146    // # Micro-pass: reconstruct the special `Box::new` operations inserted e.g. in the `vec![]`
147    // macro.
148    // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of this,
149    // it must happen before passes that insert statements like [simplify_constants].
150    // **WARNING**: this pass works across calls, hence must happen after `merge_goto_chains`,
151    UnstructuredBody(&resugar::reconstruct_boxes::Transform),
152    // # Micro-pass: reconstruct the asserts
153    UnstructuredBody(&resugar::reconstruct_asserts::Transform),
154    // # Micro-pass: `panic!()` expands to a new function definition each time. This pass cleans
155    // those up.
156    UnstructuredBody(&resugar::inline_local_panic_functions::Transform),
157    // # Micro-pass: desugar the constants to other values/operands as much
158    // as possible.
159    UnstructuredBody(&simplify_output::simplify_constants::Transform),
160    // # Micro-pass: introduce intermediate assignments in preparation of the
161    // [`index_to_function_calls`] pass.
162    UnstructuredBody(&simplify_output::index_intermediate_assigns::Transform),
163    // # Micro-pass: remove locals of type `()` which show up a lot.
164    UnstructuredBody(&simplify_output::remove_unit_locals::Transform),
165    // # Micro-pass: duplicate the return blocks
166    UnstructuredBody(&control_flow::duplicate_return::Transform),
167    // Remove the locals which are never used.
168    NonBody(&simplify_output::remove_unused_locals::Transform),
169    // Another round.
170    UnstructuredBody(&control_flow::merge_goto_chains::Transform),
171    // # Micro-pass: filter the "dangling" blocks. Those might have been introduced by,
172    // for instance, [`merge_goto_chains`].
173    UnstructuredBody(&normalize::filter_unreachable_blocks::Transform),
174    // # Micro-pass: make sure the block ids used in the ULLBC are consecutive
175    UnstructuredBody(&simplify_output::update_block_indices::Transform),
176];
177
178/// Body cleanup passes after control flow reconstruction.
179pub static LLBC_PASSES: &[Pass] = &[
180    // # Go from ULLBC to LLBC (Low-Level Borrow Calculus) by reconstructing the control flow.
181    NonBody(&control_flow::ullbc_to_llbc::Transform),
182    // Reconstruct matches on enum variants.
183    StructuredBody(&resugar::reconstruct_matches::Transform),
184    // Cleanup the cfg.
185    StructuredBody(&control_flow::prettify_cfg::Transform),
186    // # Micro-pass: replace some unops/binops and the array aggregates with
187    // function calls (introduces: ArrayToSlice, etc.)
188    StructuredBody(&simplify_output::ops_to_function_calls::Transform),
189    // # Micro-pass: replace the arrays/slices index operations with function
190    // calls.
191    // (introduces: ArrayIndexShared, ArrayIndexMut, etc.)
192    StructuredBody(&simplify_output::index_to_function_calls::Transform),
193];
194
195/// Cleanup passes useful for both llbc and ullbc.
196pub static SHARED_FINALIZING_PASSES: &[Pass] = &[
197    // # Micro-pass: remove the locals which are never used.
198    NonBody(&simplify_output::remove_unused_locals::Transform),
199    // # Micro-pass: remove the useless `StatementKind::Nop`s.
200    NonBody(&simplify_output::remove_nops::Transform),
201    // # Micro-pass: take all the comments found in the original body and assign them to
202    // statements. This must be last after all the statement-affecting passes to avoid losing
203    // comments.
204    NonBody(&add_missing_info::recover_body_comments::Transform),
205    // Partially monomorphize items so that no item is ever instanciated with a mutable reference
206    // or a type containing one.
207    NonBody(&normalize::partial_monomorphization::Transform),
208    // # Reorder the graph of dependencies and compute the strictly connex components to:
209    // - compute the order in which to extract the definitions
210    // - find the recursive definitions
211    // - group the mutually recursive definitions
212    // This is done last to account for the final item graph, not the initial one.
213    NonBody(&add_missing_info::reorder_decls::Transform),
214];
215
216/// Final passes to run at the end, after pretty-printing the llbc if applicable. These are only
217/// split from the above list to get test outputs even when generics fail to match.
218pub static FINAL_CLEANUP_PASSES: &[Pass] = &[
219    // Check that types are still consistent after the transformation passes.
220    NonBody(&typecheck_and_unify::Check::PostTransformation),
221    // Use `DeBruijnVar::Free` for the variables bound in item signatures.
222    NonBody(&simplify_output::unbind_item_vars::Check),
223];
224
225#[derive(Clone, Copy)]
226pub enum Pass {
227    NonBody(&'static dyn TransformPass),
228    UnstructuredBody(&'static dyn UllbcPass),
229    StructuredBody(&'static dyn LlbcPass),
230}
231
232impl Pass {
233    pub fn run(self, ctx: &mut TransformCtx) {
234        match self {
235            NonBody(pass) => {
236                if pass.should_run(&ctx.options) {
237                    pass.transform_ctx(ctx)
238                }
239            }
240            UnstructuredBody(pass) => {
241                if pass.should_run(&ctx.options) {
242                    pass.transform_ctx(ctx)
243                }
244            }
245            StructuredBody(pass) => {
246                if pass.should_run(&ctx.options) {
247                    pass.transform_ctx(ctx)
248                }
249            }
250        }
251    }
252
253    pub fn name(&self) -> &str {
254        match self {
255            NonBody(pass) => pass.name(),
256            UnstructuredBody(pass) => pass.name(),
257            StructuredBody(pass) => pass.name(),
258        }
259    }
260}
261
262pub struct PrintCtxPass {
263    pub message: String,
264    /// Whether we're printing to stdout or only logging.
265    pub to_stdout: bool,
266}
267
268impl PrintCtxPass {
269    pub fn new(to_stdout: bool, message: String) -> &'static Self {
270        let ret = Self { message, to_stdout };
271        Box::leak(Box::new(ret))
272    }
273}
274
275impl TransformPass for PrintCtxPass {
276    fn transform_ctx(&self, ctx: &mut TransformCtx) {
277        let message = &self.message;
278        if self.to_stdout {
279            println!("{message}:\n\n{ctx}\n");
280        } else {
281            trace!("{message}:\n\n{ctx}\n");
282        }
283    }
284}