Skip to main content

charon_lib/transform/
ctx.rs

1use crate::ast::*;
2use crate::errors::{ErrorCtx, Level};
3use crate::formatter::{FmtCtx, IntoFormatter};
4use crate::llbc_ast;
5use crate::options::TranslateOptions;
6use crate::pretty::FmtWithCtx;
7use crate::register_error;
8use crate::transform::CowBox;
9use crate::ullbc_ast;
10use std::cell::RefCell;
11use std::{fmt, mem};
12
13/// Simpler context used for rustc-independent code transformation. This only depends on rustc for
14/// its error reporting machinery.
15pub struct TransformCtx {
16    /// The options that control transformation.
17    pub options: TranslateOptions,
18    /// The translated data.
19    pub translated: TranslatedCrate,
20    /// Context for tracking and reporting errors.
21    pub errors: RefCell<ErrorCtx>,
22}
23
24/// A pass that modifies ullbc bodies and can be fused with previous passes so that we run all of
25/// them on a given body.
26pub trait UllbcPass: Sync {
27    /// Whether the pass should run.
28    fn should_run(&self, _options: &TranslateOptions) -> bool {
29        true
30    }
31
32    /// Transform a body.
33    fn transform_body(&self, _ctx: &mut TransformCtx, _body: &mut ullbc_ast::ExprBody) {}
34
35    /// Transform a function declaration. This forwards to `transform_body` by default.
36    fn transform_function(&self, ctx: &mut TransformCtx, decl: &mut FunDecl) {
37        if let Some(body) = decl.body.as_unstructured_mut() {
38            self.transform_body(ctx, body)
39        }
40    }
41
42    /// Transform an item. This forwards to `transform_function` by default.
43    fn transform_item(&self, ctx: &mut TransformCtx, item: ItemRefMut<'_>) {
44        if let ItemRefMut::Fun(decl) = item {
45            self.transform_function(ctx, decl);
46        }
47    }
48
49    /// Some passes carry function bodies, which must also be transformed. This is called before
50    /// the batch of passes starts, with all the passes that come before this one. Rougly only
51    /// useful for passes that inline some functions into others.
52    fn apply_preceding_passes(
53        &mut self,
54        _ctx: &mut TransformCtx,
55        _passes: &[CowBox<dyn UllbcPass>],
56    ) {
57    }
58
59    /// Run after all the fused passes in the current block are done.
60    fn finalize(&self, _ctx: &mut TransformCtx) {}
61
62    /// The name of the pass, used for debug logging. The default implementation uses the type
63    /// name.
64    fn name(&self) -> &str {
65        std::any::type_name::<Self>()
66    }
67}
68
69/// A pass that modifies llbc bodies.
70pub trait LlbcPass: Sync {
71    /// Whether the pass should run.
72    fn should_run(&self, _options: &TranslateOptions) -> bool {
73        true
74    }
75
76    /// Transform a body.
77    fn transform_body(&self, _ctx: &mut TransformCtx, _body: &mut llbc_ast::ExprBody) {}
78
79    /// Transform a function declaration. This forwards to `transform_body` by default.
80    fn transform_function(&self, ctx: &mut TransformCtx, decl: &mut FunDecl) {
81        if let Some(body) = decl.body.as_structured_mut() {
82            self.transform_body(ctx, body)
83        }
84    }
85
86    /// The name of the pass, used for debug logging. The default implementation uses the type
87    /// name.
88    fn name(&self) -> &str {
89        std::any::type_name::<Self>()
90    }
91}
92
93/// A pass that transforms the crate data.
94pub trait TransformPass: Sync {
95    /// Whether the pass should run.
96    fn should_run(&self, _options: &TranslateOptions) -> bool {
97        true
98    }
99
100    fn transform_ctx(&self, ctx: &mut TransformCtx);
101
102    /// The name of the pass, used for debug logging. The default implementation uses the type
103    /// name.
104    fn name(&self) -> &str {
105        std::any::type_name::<Self>()
106    }
107}
108
109impl TransformCtx {
110    pub(crate) fn has_errors(&self) -> bool {
111        self.errors.borrow().has_errors()
112    }
113
114    /// Span an error and register the error.
115    pub(crate) fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
116        self.errors
117            .borrow_mut()
118            .span_err(&self.translated, span, msg, level)
119    }
120
121    pub(crate) fn opacity_for_name(&self, name: &Name) -> ItemOpacity {
122        self.options.opacity_for_name(&self.translated, name)
123    }
124
125    /// Run an item transformation with its error context, reporting any panic on that item.
126    pub(crate) fn with_def_id(
127        &mut self,
128        def_id: impl Into<ItemId>,
129        def_id_is_local: bool,
130        span: Span,
131        f: impl FnOnce(&mut Self),
132    ) {
133        let def_id = def_id.into();
134        let mut errors = self.errors.borrow_mut();
135        let current_def_id = errors.def_id.replace(def_id);
136        let current_def_id_is_local = mem::replace(&mut errors.def_id_is_local, def_id_is_local);
137        drop(errors); // important: release the refcell "lock"
138        if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))).is_err() {
139            register_error!(
140                self,
141                span,
142                "Thread panicked while transforming item `{def_id:?}`."
143            );
144        }
145        let mut errors = self.errors.borrow_mut();
146        errors.def_id = current_def_id;
147        errors.def_id_is_local = current_def_id_is_local;
148    }
149
150    /// Mutably iterate over the bodies.
151    /// Warning: we replace each body with `Err(Opaque)` while inspecting it so we can keep access
152    /// to the rest of the crate.
153    pub(crate) fn for_each_body(&mut self, mut f: impl FnMut(&mut Self, &mut Body)) {
154        let fn_ids = self.translated.fun_decls.all_indices();
155        for id in fn_ids {
156            if let Some(decl) = self.translated.fun_decls.get_mut(id)
157                && decl.body.has_contents()
158            {
159                let mut body = mem::replace(&mut decl.body, Body::Opaque);
160                let fun_decl_id = decl.def_id;
161                let is_local = decl.item_meta.is_local;
162                let span = decl.item_meta.span;
163                self.with_def_id(fun_decl_id, is_local, span, |ctx| f(ctx, &mut body));
164                let decl = &mut self.translated.fun_decls[id];
165                decl.body = body;
166                decl.item_meta.has_errors |= self.errors.borrow().item_has_errors(fun_decl_id);
167            }
168        }
169    }
170
171    /// Mutably iterate over the function declarations.
172    /// Warning: each inspected function declaration becomes inaccessible from `ctx` during the
173    /// course of this function.
174    pub(crate) fn for_each_fun_decl(&mut self, mut f: impl FnMut(&mut Self, &mut FunDecl)) {
175        let fn_ids = self.translated.fun_decls.all_indices();
176        for id in fn_ids {
177            if let Some(mut decl) = self.translated.fun_decls.remove(id) {
178                let fun_decl_id = decl.def_id;
179                let is_local = decl.item_meta.is_local;
180                let span = decl.item_meta.span;
181                self.with_def_id(fun_decl_id, is_local, span, |ctx| f(ctx, &mut decl));
182                decl.item_meta.has_errors |= self.errors.borrow().item_has_errors(fun_decl_id);
183                self.translated.fun_decls.set_slot(id, decl);
184            }
185        }
186    }
187
188    /// Mutably iterate over the type declarations.
189    /// Warning: each inspected type declaration becomes inaccessible from `ctx` during the course
190    /// of this function.
191    pub(crate) fn for_each_type_decl(&mut self, mut f: impl FnMut(&mut Self, &mut TypeDecl)) {
192        let type_ids = self.translated.type_decls.all_indices();
193        for id in type_ids {
194            if let Some(mut decl) = self.translated.type_decls.remove(id) {
195                let type_decl_id = decl.def_id;
196                let is_local = decl.item_meta.is_local;
197                let span = decl.item_meta.span;
198                self.with_def_id(type_decl_id, is_local, span, |ctx| f(ctx, &mut decl));
199                decl.item_meta.has_errors |= self.errors.borrow().item_has_errors(type_decl_id);
200                self.translated.type_decls.set_slot(id, decl);
201            }
202        }
203    }
204
205    /// Iterate mutably over all items, keeping access to `self`. To make this work, we move out
206    /// each item before iterating over it. Items added during traversal will not be iterated over.
207    /// This keeps `item_names` up to date with changes to the item names.
208    pub fn for_each_item_mut(&mut self, mut f: impl for<'a> FnMut(&'a mut Self, ItemRefMut<'a>)) {
209        for id in self.translated.all_ids() {
210            if let Some(mut decl) = self.translated.remove_item_temporarily(id) {
211                let is_local = decl.as_ref().item_meta().is_local;
212                let span = decl.as_ref().item_meta().span;
213                self.with_def_id(id, is_local, span, |ctx| f(ctx, decl.as_mut()));
214                decl.as_mut().item_meta().has_errors |= self.errors.borrow().item_has_errors(id);
215                let name = &decl.as_ref().item_meta().name;
216                if self.translated.item_names.get(&id) != Some(name) {
217                    self.translated.item_names.insert(id, name.clone());
218                }
219                self.translated.put_item_back(id, decl);
220            }
221        }
222    }
223}
224
225impl<'a> IntoFormatter for &'a TransformCtx {
226    type C = FmtCtx<'a>;
227
228    fn into_fmt(self) -> Self::C {
229        self.translated.into_fmt()
230    }
231}
232
233impl fmt::Display for TransformCtx {
234    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
235        self.translated.fmt_with_ctx(&self.into_fmt(), f)
236    }
237}
238
239/// A helper trait that captures common operations in body transformation.
240pub trait BodyTransformCtx: Sized {
241    fn get_crate(&self) -> &TranslatedCrate;
242    fn get_options(&self) -> &TranslateOptions;
243    fn get_params(&self) -> &GenericParams;
244    fn get_locals_mut(&mut self) -> &mut Locals;
245
246    fn insert_storage_live_stmt(&mut self, local: LocalId);
247    fn insert_storage_dead_stmt(&mut self, local: LocalId);
248    fn insert_assn_stmt(&mut self, place: Place, rvalue: Rvalue);
249
250    fn to_fmt(&self) -> FmtCtx<'_> {
251        self.get_crate().into_fmt()
252    }
253
254    /// Create a local & return the place pointing to it
255    fn fresh_var(&mut self, name: Option<String>, ty: Ty) -> Place {
256        let var = self.get_locals_mut().new_var(name, ty);
257        self.insert_storage_live_stmt(var.local_id().unwrap());
258        var
259    }
260
261    /// Assign an rvalue to a place, unless the rvalue is a move in which case we just use the
262    /// moved place.
263    fn rval_to_place(&mut self, rvalue: Rvalue, ty: Ty) -> Place {
264        if let Rvalue::Use(Operand::Move(place), WithRetag::No) = rvalue {
265            place
266        } else {
267            let var = self.fresh_var(None, ty);
268            self.insert_assn_stmt(var.clone(), rvalue);
269            var
270        }
271    }
272
273    /// When `from_end` is true, we need to compute `len(p) - last_arg` instead of just using `last_arg`.
274    /// Otherwise, we simply return `last_arg`.
275    /// New local variables are created as needed.
276    ///
277    /// The `last_arg` is either the `offset` for `Index` or the `to` for `Subslice` for the projections.
278    fn compute_subslice_end_idx(
279        &mut self,
280        len_place: &Place,
281        last_arg: Operand,
282        from_end: bool,
283    ) -> Operand {
284        if from_end {
285            let len = match len_place.ty().kind() {
286                TyKind::Array(_, len, _) => Operand::Const(len.clone()),
287                TyKind::Slice(..) => self.compute_place_metadata(len_place),
288                _ => panic!(
289                    "called `compute_subslice_end_idx` on something that isn't an array or slice: {:?}",
290                    len_place.ty()
291                ),
292            };
293            // `storage_live(index_var)`
294            // `index_var = len - last_arg`
295            let index_var = self.fresh_var(None, Ty::mk_usize());
296            self.insert_assn_stmt(
297                index_var.clone(),
298                Rvalue::BinaryOp(BinOp::Sub(OverflowMode::UB), len, last_arg),
299            );
300            Operand::Read(index_var)
301        } else {
302            last_arg
303        }
304    }
305
306    fn is_sized_type_var(&mut self, ty: &Ty) -> bool {
307        match ty.kind() {
308            TyKind::TypeVar(..) => {
309                if self.get_options().hide_marker_traits {
310                    // If we're hiding `Sized`, let's consider everything to be sized.
311                    return true;
312                }
313                let params = self.get_params();
314                for clause in &params.trait_clauses {
315                    let tref = clause.trait_.clone().erase();
316                    // Check if it is `Sized<T>`
317                    if tref.generics.types[0] == *ty
318                        && self
319                            .get_crate()
320                            .trait_decls
321                            .get(tref.id)
322                            .and_then(|decl| decl.item_meta.lang_item.as_ref())
323                            == Some(&from_rustc::LangItem::Sized)
324                    {
325                        return true;
326                    }
327                }
328                false
329            }
330            _ => false,
331        }
332    }
333
334    /// Emit statements that compute the metadata of the given place. Returns an operand containing the
335    /// metadata value.
336    ///
337    /// E.g., for:
338    /// ```ignore
339    /// let x = &(*ptr).field;
340    /// ```
341    /// if `(*ptr).field` is a DST like `[i32]`, this will get the metadata from the appropriate
342    /// pointer:
343    /// ```ignore
344    /// let len = ptr.metadata;
345    /// ```
346    /// and return `Operand::Move(len)`.
347    ///
348    fn compute_place_metadata(&mut self, place: &Place) -> Operand {
349        /// Compute the metadata for a place. Return `None` if the place has no metadata.
350        fn compute_place_metadata_inner<T: BodyTransformCtx>(
351            ctx: &mut T,
352            place: &Place,
353            metadata_ty: &Ty,
354        ) -> Option<Operand> {
355            let (subplace, proj) = match &place.kind {
356                PlaceKind::Local(_) => return None,
357                PlaceKind::Global(gref) => {
358                    let global = ctx.get_crate().global_decls.get(gref.id)?;
359                    return Some(Operand::Const(global.ptr_metadata.clone()));
360                }
361                PlaceKind::Projection(proj) => (&proj.0, &proj.1),
362            };
363            match proj {
364                // The outermost deref we encountered gives us the metadata of the place.
365                ProjectionElem::Deref => {
366                    let metadata_place = subplace
367                        .clone()
368                        .project(ProjectionElem::PtrMetadata, metadata_ty.clone());
369                    Some(Operand::Read(metadata_place))
370                }
371                ProjectionElem::Field { .. } => {
372                    compute_place_metadata_inner(ctx, subplace, metadata_ty)
373                }
374                // The pointee of an offset is sized, hence no metadata.
375                ProjectionElem::Offset { .. } => None,
376                // Indexing for array & slice will only result in sized types, hence no metadata
377                ProjectionElem::Index { .. } => None,
378                // Ptr metadata is always sized.
379                ProjectionElem::PtrMetadata => None,
380                // A subslice of an array whose bounds are known at compile-time.
381                // FIXME: track that distinction in `ProjectionElem::Subslice` instead.
382                ProjectionElem::Subslice { .. } if place.ty.kind().is_array() => None,
383                // Otherwise the subslice is a slice, whose metadata is its length `to` - `from`.
384                ProjectionElem::Subslice { from, to, from_end } => {
385                    let to_idx = ctx.compute_subslice_end_idx(subplace, *to.clone(), *from_end);
386                    let diff_place = ctx.fresh_var(None, Ty::mk_usize());
387                    ctx.insert_assn_stmt(
388                        diff_place.clone(),
389                        // Overflow is UB and should have been prevented by a bound check beforehand.
390                        Rvalue::BinaryOp(BinOp::Sub(OverflowMode::UB), to_idx, *from.clone()),
391                    );
392                    Some(Operand::Read(diff_place))
393                }
394            }
395        }
396        trace!(
397            "getting ptr metadata for place: {}",
398            place.with_ctx(&self.to_fmt())
399        );
400        let metadata_ty = place.ty().get_ptr_metadata(self.get_crate()).into_type();
401        if metadata_ty.is_unit()
402            || matches!(metadata_ty.kind(), TyKind::PtrMetadata(ty) if self.is_sized_type_var(ty))
403        {
404            // If the type var is known to be `Sized`, then no metadata is needed
405            return Operand::mk_const_unit();
406        }
407        trace!(
408            "computed metadata type: {}",
409            metadata_ty.with_ctx(&self.to_fmt())
410        );
411        compute_place_metadata_inner(self, place, &metadata_ty)
412            .unwrap_or_else(Operand::mk_const_unit)
413    }
414
415    /// The projection to the place of type `output_ty` located `count * size_of::<ty>()` bytes
416    /// after the current place, or `count` bytes if `ty` is `None` (see `ProjectionElem::Offset`).
417    /// `output_is_sized` is the proof that `output_ty` is sized.
418    fn offset_projection(
419        &mut self,
420        count: Operand,
421        ty: Option<&Ty>,
422        in_bounds: bool,
423        output_ty: Ty,
424        ty_is_sized: Option<TraitRef>,
425    ) -> ProjectionElem {
426        let bytes = match ty {
427            None => count,
428            Some(ty) => {
429                let count_ty = count.ty().clone();
430                let size =
431                    ConstantExpr::new(ConstantExprKind::SizeOf(ty.clone()), count_ty.clone());
432                let mode = if in_bounds {
433                    OverflowMode::UB
434                } else {
435                    OverflowMode::Wrap
436                };
437                let rval = Rvalue::BinaryOp(BinOp::Mul(mode), count, Operand::Const(size));
438                Operand::Read(self.rval_to_place(rval, count_ty))
439            }
440        };
441        ProjectionElem::Offset {
442            bytes: Box::new(bytes),
443            in_bounds,
444            ty: output_ty,
445            ty_is_sized,
446        }
447    }
448
449    /// Create a `&` borrow of the place.
450    fn borrow(&mut self, place: Place, kind: BorrowKind) -> Rvalue {
451        let ptr_metadata = self.compute_place_metadata(&place);
452        Rvalue::Ref {
453            place,
454            kind,
455            ptr_metadata,
456        }
457    }
458    /// Create a `&raw` borrow of the place.
459    fn raw_borrow(&mut self, place: Place, kind: RefKind) -> Rvalue {
460        let ptr_metadata = self.compute_place_metadata(&place);
461        Rvalue::RawPtr {
462            place,
463            kind,
464            ptr_metadata,
465        }
466    }
467
468    /// Store a `&` borrow of the place into a new place.
469    fn borrow_to_new_var(&mut self, place: Place, kind: BorrowKind, name: Option<String>) -> Place {
470        let ref_ty = TyKind::Ref(Region::Erased, place.ty().clone(), kind.into()).into_ty();
471        let target_place = self.fresh_var(name, ref_ty);
472        let rvalue = self.borrow(place, kind);
473        self.insert_assn_stmt(target_place.clone(), rvalue);
474        target_place
475    }
476    /// Store a `&raw` borrow of the place into a new place.
477    fn raw_borrow_to_new_var(
478        &mut self,
479        place: Place,
480        kind: RefKind,
481        name: Option<String>,
482    ) -> Place {
483        let ref_ty = TyKind::RawPtr(place.ty().clone(), kind).into_ty();
484        let target_place = self.fresh_var(name, ref_ty);
485        let rvalue = self.raw_borrow(place, kind);
486        self.insert_assn_stmt(target_place.clone(), rvalue);
487        target_place
488    }
489}
490
491pub struct UllbcStatementTransformCtx<'a> {
492    pub ctx: &'a mut TransformCtx,
493    pub params: &'a GenericParams,
494    pub def_id: &'a FunDeclId,
495    pub locals: &'a mut Locals,
496    /// Span of the statement being explored
497    pub span: Span,
498    /// Statements to prepend to the statement currently being explored.
499    pub statements: Vec<ullbc_ast::Statement>,
500}
501
502impl BodyTransformCtx for UllbcStatementTransformCtx<'_> {
503    fn get_crate(&self) -> &TranslatedCrate {
504        &self.ctx.translated
505    }
506    fn get_options(&self) -> &TranslateOptions {
507        &self.ctx.options
508    }
509    fn get_params(&self) -> &GenericParams {
510        self.params
511    }
512    fn get_locals_mut(&mut self) -> &mut Locals {
513        self.locals
514    }
515
516    fn insert_storage_live_stmt(&mut self, local: LocalId) {
517        self.statements.push(ullbc_ast::Statement::new(
518            self.span,
519            ullbc_ast::StatementKind::StorageLive(local),
520        ));
521    }
522
523    fn insert_assn_stmt(&mut self, place: Place, rvalue: Rvalue) {
524        self.statements.push(ullbc_ast::Statement::new(
525            self.span,
526            ullbc_ast::StatementKind::Assign(place, rvalue),
527        ));
528    }
529
530    fn insert_storage_dead_stmt(&mut self, local: LocalId) {
531        self.statements.push(ullbc_ast::Statement::new(
532            self.span,
533            ullbc_ast::StatementKind::StorageDead(local),
534        ));
535    }
536}
537
538pub struct LlbcStatementTransformCtx<'a> {
539    pub ctx: &'a mut TransformCtx,
540    pub params: &'a GenericParams,
541    pub locals: &'a mut Locals,
542    /// Span of the statement being explored
543    pub span: Span,
544    /// Statements to prepend to the statement currently being explored.
545    pub statements: Vec<llbc_ast::Statement>,
546}
547
548impl BodyTransformCtx for LlbcStatementTransformCtx<'_> {
549    fn get_crate(&self) -> &TranslatedCrate {
550        &self.ctx.translated
551    }
552    fn get_options(&self) -> &TranslateOptions {
553        &self.ctx.options
554    }
555    fn get_params(&self) -> &GenericParams {
556        self.params
557    }
558    fn get_locals_mut(&mut self) -> &mut Locals {
559        self.locals
560    }
561
562    fn insert_storage_live_stmt(&mut self, local: LocalId) {
563        self.statements.push(llbc_ast::Statement::new(
564            self.span,
565            llbc_ast::StatementKind::StorageLive(local),
566        ));
567    }
568
569    fn insert_assn_stmt(&mut self, place: Place, rvalue: Rvalue) {
570        self.statements.push(llbc_ast::Statement::new(
571            self.span,
572            llbc_ast::StatementKind::Assign(place, Box::new(rvalue)),
573        ));
574    }
575
576    fn insert_storage_dead_stmt(&mut self, local: LocalId) {
577        self.statements.push(llbc_ast::Statement::new(
578            self.span,
579            llbc_ast::StatementKind::StorageDead(local),
580        ));
581    }
582}
583
584impl FunDecl {
585    pub fn transform_ullbc_statements(
586        &mut self,
587        ctx: &mut TransformCtx,
588        mut f: impl FnMut(&mut UllbcStatementTransformCtx, &mut ullbc_ast::Statement),
589    ) {
590        if let Some(body) = self.body.as_unstructured_mut() {
591            let mut ctx = UllbcStatementTransformCtx {
592                ctx,
593                params: &self.generics,
594                def_id: &self.def_id,
595                locals: &mut body.locals,
596                span: self.item_meta.span,
597                statements: Vec::new(),
598            };
599            body.body.iter_mut().for_each(|block| {
600                ctx.statements = Vec::with_capacity(block.statements.len());
601                for mut st in mem::take(&mut block.statements) {
602                    ctx.span = st.span;
603                    f(&mut ctx, &mut st);
604                    ctx.statements.push(st);
605                }
606                block.statements = mem::take(&mut ctx.statements);
607            });
608        }
609    }
610
611    pub fn transform_ullbc_terminators(
612        &mut self,
613        ctx: &mut TransformCtx,
614        mut f: impl FnMut(&mut UllbcStatementTransformCtx, &mut ullbc_ast::Terminator),
615    ) {
616        if let Some(body) = self.body.as_unstructured_mut() {
617            let mut ctx = UllbcStatementTransformCtx {
618                ctx,
619                params: &self.generics,
620                def_id: &self.def_id,
621                locals: &mut body.locals,
622                span: self.item_meta.span,
623                statements: Vec::new(),
624            };
625            body.body.iter_mut().for_each(|block| {
626                ctx.span = block.terminator.span;
627                ctx.statements = mem::take(&mut block.statements);
628                f(&mut ctx, &mut block.terminator);
629                block.statements = mem::take(&mut ctx.statements);
630            });
631        }
632    }
633
634    pub fn transform_ullbc_operands(
635        &mut self,
636        ctx: &mut TransformCtx,
637        mut f: impl FnMut(&mut UllbcStatementTransformCtx, &mut Operand),
638    ) {
639        self.transform_ullbc_statements(ctx, |ctx, st| {
640            st.kind.dyn_visit_in_body_mut(|op: &mut Operand| f(ctx, op));
641        });
642        self.transform_ullbc_terminators(ctx, |ctx, st| {
643            st.kind.dyn_visit_in_body_mut(|op: &mut Operand| f(ctx, op));
644        });
645    }
646
647    pub fn transform_llbc_statements(
648        &mut self,
649        ctx: &mut TransformCtx,
650        mut f: impl FnMut(&mut LlbcStatementTransformCtx, &mut llbc_ast::Statement),
651    ) {
652        if let Some(body) = self.body.as_structured_mut() {
653            let mut ctx = LlbcStatementTransformCtx {
654                ctx,
655                locals: &mut body.locals,
656                statements: Vec::new(),
657                span: self.item_meta.span,
658                params: &self.generics,
659            };
660            body.body.visit_blocks_bwd(|block: &mut llbc_ast::Block| {
661                ctx.statements = Vec::with_capacity(block.statements.len());
662                for mut st in mem::take(&mut block.statements) {
663                    ctx.span = st.span;
664                    f(&mut ctx, &mut st);
665                    ctx.statements.push(st);
666                }
667                block.statements = mem::take(&mut ctx.statements)
668            })
669        }
670    }
671}