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