charon_lib/transform/mod.rs
1pub mod check_generics;
2pub mod ctx;
3pub mod duplicate_defaulted_methods;
4pub mod duplicate_return;
5pub mod expand_associated_types;
6pub mod filter_invisible_trait_impls;
7pub mod filter_unreachable_blocks;
8pub mod graphs;
9pub mod hide_marker_traits;
10pub mod index_intermediate_assigns;
11pub mod index_to_function_calls;
12pub mod inline_local_panic_functions;
13pub mod insert_assign_return_unit;
14pub mod insert_storage_lives;
15pub mod lift_associated_item_clauses;
16pub mod merge_goto_chains;
17pub mod monomorphize;
18pub mod ops_to_function_calls;
19pub mod prettify_cfg;
20pub mod reconstruct_asserts;
21pub mod reconstruct_boxes;
22pub mod recover_body_comments;
23pub mod remove_arithmetic_overflow_checks;
24pub mod remove_drop_never;
25pub mod remove_dynamic_checks;
26pub mod remove_nops;
27pub mod remove_read_discriminant;
28pub mod remove_unit_locals;
29pub mod remove_unused_locals;
30pub mod remove_unused_methods;
31pub mod reorder_decls;
32pub mod simplify_constants;
33pub mod skip_trait_refs_when_known;
34pub mod ullbc_to_llbc;
35pub mod unbind_item_vars;
36pub mod update_block_indices;
37pub mod update_closure_signatures;
38
39pub use ctx::TransformCtx;
40use ctx::{LlbcPass, TransformPass, UllbcPass};
41use Pass::*;
42
43/// Item and type cleanup passes.
44pub static INITIAL_CLEANUP_PASSES: &[Pass] = &[
45 // Remove the trait/impl methods that were not translated (because not used).
46 NonBody(&remove_unused_methods::Transform),
47 // Move clauses on associated types to be parent clauses
48 NonBody(&lift_associated_item_clauses::Transform),
49 // Check that all supplied generic types match the corresponding generic parameters.
50 // Needs `lift_associated_item_clauses`.
51 NonBody(&check_generics::Check("after translation")),
52 // # Micro-pass: hide some overly-common traits we don't need: Sized, Sync, Allocator, etc..
53 NonBody(&hide_marker_traits::Transform),
54 // # Micro-pass: filter the trait impls that were marked invisible since we couldn't filter
55 // them out earlier.
56 NonBody(&filter_invisible_trait_impls::Transform),
57 // Add missing methods to trait impls by duplicating the default method.
58 NonBody(&duplicate_defaulted_methods::Transform),
59 // # Micro-pass: whenever we call a trait method on a known type, refer to the method `FunDecl`
60 // directly instead of going via a `TraitRef`. This is done before `reorder_decls` to remove
61 // some sources of mutual recursion.
62 UnstructuredBody(&skip_trait_refs_when_known::Transform),
63 // Change trait associated types to be type parameters instead. See the module for details.
64 NonBody(&expand_associated_types::Transform),
65];
66
67/// Body cleanup passes on the ullbc.
68pub static ULLBC_PASSES: &[Pass] = &[
69 // # Micro-pass: merge single-origin gotos into their parent. This drastically reduces the
70 // graph size of the CFG.
71 UnstructuredBody(&merge_goto_chains::Transform),
72 // # Micro-pass: Remove overflow/div-by-zero/bounds checks since they are already part of the
73 // arithmetic/array operation in the semantics of (U)LLBC.
74 // **WARNING**: this pass uses the fact that the dynamic checks introduced by Rustc use a
75 // special "assert" construct. Because of this, it must happen *before* the
76 // [reconstruct_asserts] pass. See the comments in [crate::remove_dynamic_checks].
77 // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of this,
78 // it must happen before passes that insert statements like [simplify_constants].
79 UnstructuredBody(&remove_dynamic_checks::Transform),
80 // # Micro-pass: reconstruct the special `Box::new` operations inserted e.g. in the `vec![]`
81 // macro.
82 // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of this,
83 // it must happen before passes that insert statements like [simplify_constants].
84 // **WARNING**: this pass works across calls, hence must happen after `merge_goto_chains`,
85 UnstructuredBody(&reconstruct_boxes::Transform),
86 // # Micro-pass: desugar the constants to other values/operands as much
87 // as possible.
88 UnstructuredBody(&simplify_constants::Transform),
89 // # Micro-pass: the first local variable of closures is the
90 // closure itself. This is not consistent with the closure signature,
91 // which ignores this first variable. This micro-pass updates this.
92 UnstructuredBody(&update_closure_signatures::Transform),
93 // # Micro-pass: remove the dynamic checks we couldn't remove in [`remove_dynamic_checks`].
94 // **WARNING**: this pass uses the fact that the dynamic checks
95 // introduced by Rustc use a special "assert" construct. Because of
96 // this, it must happen *before* the [reconstruct_asserts] pass.
97 UnstructuredBody(&remove_arithmetic_overflow_checks::Transform),
98 // # Micro-pass: replace some unops/binops and the array aggregates with
99 // function calls (introduces: ArrayToSlice, etc.)
100 UnstructuredBody(&ops_to_function_calls::Transform),
101 // # Micro-pass: make sure the block ids used in the ULLBC are consecutive
102 UnstructuredBody(&update_block_indices::Transform),
103 // # Micro-pass: reconstruct the asserts
104 UnstructuredBody(&reconstruct_asserts::Transform),
105 // # Micro-pass: duplicate the return blocks
106 UnstructuredBody(&duplicate_return::Transform),
107 // # Micro-pass: filter the "dangling" blocks. Those might have been introduced by,
108 // for instance, [`reconstruct_asserts`].
109 UnstructuredBody(&filter_unreachable_blocks::Transform),
110 // # Micro-pass: `panic!()` expands to a new function definition each time. This pass cleans
111 // those up.
112 UnstructuredBody(&inline_local_panic_functions::Transform),
113 // # Micro-pass: introduce intermediate assignments in preparation of the
114 // [`index_to_function_calls`] pass.
115 UnstructuredBody(&index_intermediate_assigns::Transform),
116 // # Micro-pass: replace the arrays/slices index operations with function
117 // calls.
118 // (introduces: ArrayIndexShared, ArrayIndexMut, etc.)
119 UnstructuredBody(&index_to_function_calls::Transform),
120 // # Micro-pass: add the missing assignments to the return value.
121 // When the function return type is unit, the generated MIR doesn't
122 // set the return value to `()`. This can be a concern: in the case
123 // of Aeneas, it means the return variable contains ⊥ upon returning.
124 // For this reason, when the function has return type unit, we insert
125 // an extra assignment just before returning.
126 UnstructuredBody(&insert_assign_return_unit::Transform),
127 // # Micro-pass: remove locals of type `()` which show up a lot.
128 UnstructuredBody(&remove_unit_locals::Transform),
129 // # Micro-pass: remove the drops of locals whose type is `Never` (`!`). This
130 // is in preparation of the next transformation.
131 UnstructuredBody(&remove_drop_never::Transform),
132];
133
134/// Body cleanup passes after control flow reconstruction.
135pub static LLBC_PASSES: &[Pass] = &[
136 // # Go from ULLBC to LLBC (Low-Level Borrow Calculus) by reconstructing the control flow.
137 NonBody(&ullbc_to_llbc::Transform),
138 // # Micro-pass: Remove the discriminant reads (merge them with the switches)
139 StructuredBody(&remove_read_discriminant::Transform),
140 // Cleanup the cfg.
141 StructuredBody(&prettify_cfg::Transform),
142];
143
144/// Cleanup passes useful for both llbc and ullbc.
145pub static SHARED_FINALIZING_PASSES: &[Pass] = &[
146 // # Micro-pass: remove the locals which are never used.
147 NonBody(&remove_unused_locals::Transform),
148 // Insert storage lives for locals that are always allocated at the beginning of the function.
149 NonBody(&insert_storage_lives::Transform),
150 // # Micro-pass: remove the useless `StatementKind::Nop`s.
151 NonBody(&remove_nops::Transform),
152 // Monomorphize the functions and types.
153 NonBody(&monomorphize::Transform),
154 // # Micro-pass: take all the comments found in the original body and assign them to
155 // statements. This must be last after all the statement-affecting passes to avoid losing
156 // comments.
157 NonBody(&recover_body_comments::Transform),
158 // # Reorder the graph of dependencies and compute the strictly connex components to:
159 // - compute the order in which to extract the definitions
160 // - find the recursive definitions
161 // - group the mutually recursive definitions
162 NonBody(&reorder_decls::Transform),
163];
164
165/// Final passes to run at the end, after pretty-printing the llbc if applicable. These are only
166/// split from the above list to get test outputs even when generics fail to match.
167pub static FINAL_CLEANUP_PASSES: &[Pass] = &[
168 // Check that all supplied generic types match the corresponding generic parameters.
169 NonBody(&check_generics::Check("after transformations")),
170 // Use `DeBruijnVar::Free` for the variables bound in item signatures.
171 NonBody(&unbind_item_vars::Check),
172];
173
174#[derive(Clone, Copy)]
175pub enum Pass {
176 NonBody(&'static dyn TransformPass),
177 UnstructuredBody(&'static dyn UllbcPass),
178 StructuredBody(&'static dyn LlbcPass),
179}
180
181impl Pass {
182 pub fn run(self, ctx: &mut TransformCtx) {
183 match self {
184 NonBody(pass) => pass.transform_ctx(ctx),
185 UnstructuredBody(pass) => pass.transform_ctx(ctx),
186 StructuredBody(pass) => pass.transform_ctx(ctx),
187 }
188 }
189
190 pub fn name(&self) -> &str {
191 match self {
192 NonBody(pass) => pass.name(),
193 UnstructuredBody(pass) => pass.name(),
194 StructuredBody(pass) => pass.name(),
195 }
196 }
197}
198
199pub struct PrintCtxPass {
200 pub message: String,
201 /// Whether we're printing to stdout or only logging.
202 pub to_stdout: bool,
203}
204
205impl PrintCtxPass {
206 pub fn new(to_stdout: bool, message: String) -> &'static Self {
207 let ret = Self { message, to_stdout };
208 Box::leak(Box::new(ret))
209 }
210}
211
212impl TransformPass for PrintCtxPass {
213 fn transform_ctx(&self, ctx: &mut TransformCtx) {
214 let message = &self.message;
215 if self.to_stdout {
216 println!("{message}:\n\n{ctx}\n");
217 } else {
218 trace!("{message}:\n\n{ctx}\n");
219 }
220 }
221}