Skip to main content

charon_driver/translate/
translate_bodies.rs

1//! Translate functions from the rust compiler MIR to our internal representation.
2//! Our internal representation is very close to MIR, but is more convenient for
3//! us to handle, and easier to maintain - rustc's representation can evolve
4//! independently.
5
6use itertools::Itertools;
7use rustc_attr_ir::LangItem;
8use std::borrow::Cow;
9use std::collections::VecDeque;
10use std::mem;
11use std::ops::Deref;
12use std::ops::DerefMut;
13use std::panic;
14use std::rc::Rc;
15
16use crate::hax;
17use rustc_middle::mir;
18use rustc_middle::ty;
19use rustc_span::{Symbol, kw, sym};
20
21use super::translate_crate::*;
22use super::translate_ctx::*;
23use super::user_type_annotations::UserTypeAnnotations;
24use charon_lib::formatter::{FmtCtx, IntoFormatter, compute_local_names};
25use charon_lib::name_matcher::NamePattern;
26use charon_lib::options::TranslateOptions;
27use charon_lib::pretty::FmtWithCtx;
28use charon_lib::transform::ctx::BodyTransformCtx;
29use charon_lib::ullbc_ast::*;
30
31/// A translation context for function bodies.
32pub(crate) struct BodyTransCtx<'tcx, 'tctx, 'ictx> {
33    /// The translation context for the item.
34    pub i_ctx: &'ictx mut ItemTransCtx<'tcx, 'tctx>,
35    /// List of body locals.
36    pub local_decls: &'ictx rustc_index::IndexVec<mir::Local, mir::LocalDecl<'tcx>>,
37    /// Types supplied explicitly by the user.
38    pub user_type_annotations: UserTypeAnnotations,
39
40    /// What kind of drops we get in this body.
41    pub drop_kind: DropKind,
42    /// The (regular) variables in the current function body.
43    pub locals: Locals,
44    /// The map from rust variable indices to translated variables indices.
45    pub locals_map: rustc_index::IndexVec<mir::Local, LocalId>,
46    /// The translated blocks.
47    pub blocks: IndexMap<BlockId, BlockData>,
48    /// The map from rust blocks to translated blocks.
49    /// Note that when translating terminators like DropAndReplace, we might have
50    /// to introduce new blocks which don't appear in the original MIR.
51    pub blocks_map: rustc_index::IndexVec<mir::BasicBlock, Option<BlockId>>,
52    /// We register the blocks to translate in a stack, so as to avoid
53    /// writing the translation functions as recursive functions. We do
54    /// so because we had stack overflows in the past.
55    pub blocks_stack: VecDeque<mir::BasicBlock>,
56}
57
58impl<'tcx, 'tctx, 'ictx> BodyTransCtx<'tcx, 'tctx, 'ictx> {
59    pub(crate) fn new(
60        i_ctx: &'ictx mut ItemTransCtx<'tcx, 'tctx>,
61        body: &'ictx Rc<mir::Body<'tcx>>,
62        drop_kind: DropKind,
63    ) -> Result<Self, Error> {
64        i_ctx.lifetime_freshener = (!i_ctx.options.erase_body_lifetimes).then(IndexMap::new);
65        let user_type_annotations = UserTypeAnnotations::new(i_ctx, body)?;
66
67        // Translate the local variables.
68        let mut locals = Locals {
69            arg_count: body.arg_count,
70            ..Default::default()
71        };
72        let mut locals_map = rustc_index::IndexVec::with_capacity(body.local_decls.len());
73        let mut names = hax::local_names(body);
74        // Translate the parameters
75        for (index, var) in body.local_decls.iter_enumerated() {
76            let name = names[index].take();
77
78            // Translate the type
79            let span = i_ctx.translate_span(&var.source_info.span);
80            let (ty, borrowck_constraints) = user_type_annotations.translate_local_ty(
81                i_ctx,
82                span,
83                locals.locals.next_idx(),
84                var,
85            )?;
86
87            // Add the variable to the environment
88            let local_id = locals.locals.push_with(|index| Local {
89                index,
90                name,
91                span,
92                ty,
93                mutable: var.mutability.is_mut(),
94                borrowck_constraints,
95                drop_flag_for: None,
96            });
97            locals_map.push(local_id);
98        }
99
100        Ok(BodyTransCtx {
101            i_ctx,
102            local_decls: &body.local_decls,
103            user_type_annotations,
104            drop_kind,
105            locals,
106            locals_map,
107            blocks: Default::default(),
108            blocks_map: rustc_index::IndexVec::from_elem_n(None, body.basic_blocks.len()),
109            blocks_stack: Default::default(),
110        })
111    }
112}
113
114impl<'tcx, 'tctx, 'ictx> Deref for BodyTransCtx<'tcx, 'tctx, 'ictx> {
115    type Target = ItemTransCtx<'tcx, 'tctx>;
116    fn deref(&self) -> &Self::Target {
117        self.i_ctx
118    }
119}
120impl<'tcx, 'tctx, 'ictx> DerefMut for BodyTransCtx<'tcx, 'tctx, 'ictx> {
121    fn deref_mut(&mut self) -> &mut Self::Target {
122        self.i_ctx
123    }
124}
125
126/// A translation context for function blocks.
127pub(crate) struct BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
128    /// The translation context for the item.
129    pub b_ctx: &'bctx mut BodyTransCtx<'tcx, 'tctx, 'ictx>,
130    /// Block onto which we're adding statements.
131    pub current_block: BlockId,
132    /// The kind of the current block.
133    pub kind: UnwindKind,
134    /// Span of the statement or terminator currently being translated.
135    pub span: Span,
136    /// List of currently translated statements
137    pub statements: Vec<Statement>,
138}
139
140impl<'tcx, 'tctx, 'ictx, 'bctx> BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
141    pub(crate) fn new(
142        b_ctx: &'bctx mut BodyTransCtx<'tcx, 'tctx, 'ictx>,
143        current_block: BlockId,
144        kind: UnwindKind,
145    ) -> Self {
146        BlockTransCtx {
147            b_ctx,
148            current_block,
149            kind,
150            span: Span::dummy(),
151            statements: Vec::new(),
152        }
153    }
154
155    fn finish_current_block(self, terminator: Terminator) {
156        let block = BlockData {
157            statements: self.statements,
158            terminator,
159            kind: self.kind,
160        };
161        self.b_ctx.blocks.set_slot(self.current_block, block);
162    }
163
164    /// Used for non-diverging intrinsics.
165    fn push_nounwind_call(&mut self, span: Span, dest: Place, call: Call) {
166        let target = self.blocks.reserve_slot();
167        let unwind_kind = self.kind.further_unwind_kind();
168        let on_unwind = self
169            .blocks
170            .push(Terminator::new(span, TerminatorKind::UndefinedBehavior).into_block(unwind_kind));
171        let block = BlockData {
172            statements: mem::take(&mut self.statements),
173            terminator: Terminator::new(
174                span,
175                TerminatorKind::Call {
176                    call,
177                    dest,
178                    target,
179                    on_unwind,
180                },
181            ),
182            kind: self.kind,
183        };
184        let current_block = mem::replace(&mut self.current_block, target);
185        self.blocks.set_slot(current_block, block);
186    }
187}
188
189impl<'tcx, 'tctx, 'ictx, 'bctx> Deref for BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
190    type Target = BodyTransCtx<'tcx, 'tctx, 'ictx>;
191    fn deref(&self) -> &Self::Target {
192        self.b_ctx
193    }
194}
195impl<'tcx, 'tctx, 'ictx, 'bctx> DerefMut for BlockTransCtx<'tcx, 'tctx, 'ictx, 'bctx> {
196    fn deref_mut(&mut self) -> &mut Self::Target {
197        self.b_ctx
198    }
199}
200
201impl<'tcx> TranslateCtx<'tcx> {
202    pub fn translate_variant_id(&self, id: hax::VariantIdx) -> VariantId {
203        VariantId::new(id.as_usize())
204    }
205
206    pub fn translate_field_id(&self, id: hax::FieldIdx) -> FieldId {
207        FieldId::new(id.index())
208    }
209
210    pub fn translate_metadata_path(&self, path: &[hax::FieldIdx]) -> MetadataPath {
211        path.iter().map(|id| self.translate_field_id(*id)).collect()
212    }
213
214    fn translate_borrow_kind(
215        &self,
216        span: Span,
217        borrow_kind: mir::BorrowKind,
218    ) -> Result<BorrowKind, Error> {
219        Ok(match borrow_kind {
220            mir::BorrowKind::Shared => BorrowKind::Shared,
221            mir::BorrowKind::Mut { kind } => match kind {
222                mir::MutBorrowKind::Default => BorrowKind::Mut,
223                mir::MutBorrowKind::TwoPhaseBorrow => BorrowKind::TwoPhaseMut,
224                mir::MutBorrowKind::ClosureCapture => BorrowKind::UniqueImmutable,
225            },
226            mir::BorrowKind::Fake(mir::FakeBorrowKind::Shallow) => BorrowKind::Shallow,
227            // This one is used only in deref patterns.
228            mir::BorrowKind::Fake(mir::FakeBorrowKind::Deep) => {
229                raise_error!(self, span, "deref patterns are not supported")
230            }
231        })
232    }
233}
234
235impl<'tcx> ItemTransCtx<'tcx, '_> {
236    /// Translate the names of the arguments of this function, if they are available.
237    pub fn translate_argument_names(
238        &mut self,
239        def: &hax::FullDef<'tcx>,
240        n_args: usize,
241    ) -> Vec<Option<String>> {
242        let Some(def_id) = def.def_id().as_real_def_id() else {
243            return vec![None; n_args];
244        };
245        (self.tcx.fn_arg_idents(def_id).iter())
246            .map(|ident| Some(ident.filter(|i| i.name != kw::Underscore)?.to_string()))
247            .collect()
248    }
249
250    /// Translate the MIR body of this definition if it has one. Catches any error and returns
251    /// `Body::Error` instead
252    pub fn translate_def_body(&mut self, span: Span, def: &hax::FullDef<'tcx>) -> Body {
253        match self.translate_def_body_inner(span, def) {
254            Ok(body) => body,
255            Err(e) => Body::Error(e),
256        }
257    }
258
259    fn translate_def_body_inner(
260        &mut self,
261        span: Span,
262        def: &hax::FullDef<'tcx>,
263    ) -> Result<Body, Error> {
264        // Retrieve the body
265        if let Some(body) = self.get_mir(def.this(), span)? {
266            Ok(self.translate_body(span, body, &def.source_text(self.tcx)))
267        } else if let Some(value) =
268            def.evaluate(self.hax_state_with_id(), hax::ReadMode::Structured)
269        {
270            // For globals without MIR, generate a body by evaluating the global. This is how we
271            // get the value of statics (which have no cross-crate MIR at all) and of "trivial"
272            // consts (whose value rustc stores directly instead of encoding MIR for it).
273            let c = self.translate_constant_expr(span, &value)?;
274            let mut bb = BodyBuilder::new(span, 0);
275            let ret = bb.new_var(None, c.ty().clone());
276            bb.push_statement(StatementKind::Assign(
277                ret,
278                Rvalue::Use(Operand::Const(c), WithRetag::No),
279            ));
280            Ok(Body::Unstructured(bb.build()))
281        } else {
282            Ok(Body::Missing)
283        }
284    }
285
286    /// Translate a function body. Catches errors and returns `Body::Error` instead.
287    /// That's the entrypoint of this module.
288    pub fn translate_body(
289        &mut self,
290        span: Span,
291        body: mir::Body<'tcx>,
292        source_text: &Option<String>,
293    ) -> Body {
294        let _guard = charon_lib::timing::scope("translate-body");
295        let drop_kind = match body.phase {
296            mir::MirPhase::Built | mir::MirPhase::Analysis(..) => DropKind::Conditional,
297            mir::MirPhase::Runtime(..) => DropKind::Precise,
298        };
299        let mut ctx = panic::AssertUnwindSafe(&mut *self);
300        let body = panic::AssertUnwindSafe(body);
301        // Stopgap measure because there are still many panics in charon and hax.
302        let res = panic::catch_unwind(move || {
303            let body = Rc::new({ body }.0);
304            let ctx = BodyTransCtx::new(*ctx, &body, drop_kind)?;
305            ctx.translate_body(&body, source_text)
306        });
307        match res {
308            Ok(Ok(body)) => body,
309            // Translation error
310            Ok(Err(e)) => Body::Error(e),
311            // Panic
312            Err(_) => {
313                let e = register_error!(self, span, "Thread panicked when extracting body.");
314                Body::Error(e)
315            }
316        }
317    }
318
319    pub(crate) fn translate_unsizing_metadata(
320        &mut self,
321        span: Span,
322        meta: &hax::UnsizingMetadata<'tcx>,
323    ) -> Result<UnsizingMetadata, Error> {
324        Ok(match meta {
325            hax::UnsizingMetadata::Length(len) => {
326                let len = self.translate_constant_expr(span, len)?;
327                UnsizingMetadata::Length(len)
328            }
329            hax::UnsizingMetadata::DirectVTable(trait_proof) => {
330                let tref = self.translate_trait_proof(span, trait_proof)?;
331                let vtable = self.translate_vtable_instance_const(span, trait_proof)?;
332                UnsizingMetadata::VTable(Box::new(tref), vtable)
333            }
334            hax::UnsizingMetadata::NestedVTable(dyn_trait_proof) => {
335                // This binds a fake `T: SrcTrait` variable.
336                let binder =
337                    self.translate_dyn_binder(span, dyn_trait_proof, |ctx, _, trait_proof| {
338                        ctx.translate_trait_proof(span, trait_proof)
339                    })?;
340
341                // Compute the supertrait path from the source tref to the target
342                // tref.
343                let target_proof = binder.skip_binder.clone().erase();
344                let mut target_tref = &target_proof;
345                let mut clause_path: Vec<(TraitDeclId, TraitClauseId)> = vec![];
346                while let TraitRefKind::ParentClause(tref, id, _) = &target_tref.kind {
347                    clause_path.push((tref.trait_id(), *id));
348                    target_tref = tref;
349                }
350
351                let mut field_path = thin_vec::ThinVec::new();
352                for &(trait_id, clause_id) in &clause_path {
353                    if let Ok(ItemRef::TraitDecl(tdecl)) = self.get_or_translate(trait_id.into())
354                        && let vtable_decl_id = tdecl.vtable.as_ref().unwrap().id
355                        && let Ok(ItemRef::Type(vtable_decl)) =
356                            self.get_or_translate(vtable_decl_id.into())
357                    {
358                        let TypeSource::VTable { supertrait_map, .. } = &vtable_decl.src else {
359                            unreachable!()
360                        };
361                        field_path.push(supertrait_map[clause_id].unwrap());
362                    } else {
363                        break;
364                    }
365                }
366
367                assert_eq!(field_path.len(), clause_path.len());
368                UnsizingMetadata::VTableUpcast(field_path)
369            }
370            hax::UnsizingMetadata::UnsizeClause(trait_proof) => UnsizingMetadata::UnsizeClause(
371                self.translate_trait_proof(span, trait_proof)?.erase(),
372            ),
373            hax::UnsizingMetadata::CoerceUnsizedClause(trait_proof) => {
374                UnsizingMetadata::CoerceUnsizedClause(
375                    self.translate_trait_proof(span, trait_proof)?.erase(),
376                )
377            }
378        })
379    }
380
381    /// Generate a fake function body for ADT constructors.
382    pub(crate) fn build_ctor_body(
383        &mut self,
384        span: Span,
385        def: &hax::FullDef<'tcx>,
386    ) -> Result<Body, Error> {
387        let hax::FullDefKind::Ctor(ctor) = def.kind() else {
388            unreachable!()
389        };
390        let tref = self.translate_type_decl_ref(
391            span,
392            &def.this().with_def_id(self.hax_state(), ctor.adt_def_id()),
393        )?;
394        let output_ty = self.translate_ty(span, ctor.output_ty())?;
395
396        let mut builder = BodyBuilder::new(span, ctor.fields().len());
397        let return_place = builder.new_var(None, output_ty);
398        let args: Vec<_> = ctor
399            .fields()
400            .iter()
401            .map(|field| -> Result<Operand, Error> {
402                let ty = self.translate_ty(span, &field.ty)?;
403                let place = builder.new_var(None, ty);
404                Ok(Operand::Move(place))
405            })
406            .try_collect()?;
407        let variant = match ctor.ctor_of() {
408            hax::CtorOf::Struct => None,
409            hax::CtorOf::Variant => Some(self.translate_variant_id(ctor.variant_id())),
410        };
411        builder.push_statement(StatementKind::Assign(
412            return_place,
413            Rvalue::Aggregate(AggregateKind::Adt(tref, variant, None), args),
414        ));
415        Ok(Body::Unstructured(builder.build()))
416    }
417
418    /// FIXME(#865): Generate a function body for the `box_assume_init_into_vec_unsafe` function,
419    /// because the MIR we get for it is too optimized to be usable.
420    pub(crate) fn build_box_assume_init_into_vec_unsafe(
421        &mut self,
422        span: Span,
423        def: &hax::FullDef<'tcx>,
424    ) -> Result<Body, Error> {
425        // pub fn box_assume_init_into_vec_unsafe<T, const N: usize>(
426        //     b: Box<MaybeUninit<[T; N]>>,
427        // ) -> Vec<T> {
428        //     let x: Box<[T; N]> = unsafe { Box::assume_init(b) };
429        //     let y = x as Box<[T]>;
430        //     core::slice::into_vec(y)
431        // }
432        let tcx = self.tcx;
433        let hax::FullDefKind::Fn(f) = def.kind() else {
434            unreachable!()
435        };
436        let hax_sig = f.sig().hax_skip_binder_ref();
437        let sig = self.translate_fun_sig(span, hax_sig)?;
438
439        // Get the `[T; N]` and `A` parameters.
440        let (array_rust_ty, alloc_rust_ty) = {
441            let input_box_rust_args = {
442                let hax::TyKind::Adt(input_box) = hax_sig.inputs[0].kind() else {
443                    raise_error!(self, span, "expected a boxed input in the hax signature");
444                };
445                input_box.item.rustc_args(self.hax_state_with_id())
446            };
447            let maybe_uninit_array_rust_ty = input_box_rust_args[0].as_type().unwrap();
448            let alloc_rust_ty = input_box_rust_args[1].as_type().unwrap();
449            let ty::Adt(_, maybe_uninit_rust_args) = maybe_uninit_array_rust_ty.kind() else {
450                raise_error!(
451                    self,
452                    span,
453                    "expected `MaybeUninit<[T; N]>` in the hax signature"
454                );
455            };
456            let Some(array_rust_ty) = maybe_uninit_rust_args[0].as_type() else {
457                raise_error!(
458                    self,
459                    span,
460                    "expected the first `MaybeUninit` parameter to be a type"
461                );
462            };
463            (array_rust_ty, alloc_rust_ty)
464        };
465        // `T`
466        let elem_rust_ty = array_rust_ty.builtin_index().unwrap();
467        // `[T]`
468        let slice_rust_ty = ty::Ty::new_slice(tcx, elem_rust_ty);
469        // `Box<[T; N]>`
470        let box_array_rust_ty = ty::Ty::new_box(tcx, array_rust_ty);
471        let box_array_ty = self.translate_rustc_ty(span, &box_array_rust_ty)?;
472        // `Box<[T]>`
473        let box_slice_rust_ty = ty::Ty::new_box(tcx, slice_rust_ty);
474        let box_slice_ty = self.translate_rustc_ty(span, &box_slice_rust_ty)?;
475
476        if !self.monomorphize() {
477            // Make `Box::new` and `Box::write` available to a later construction pass.
478            let path = NamePattern::parse(names::BOX_NEW).unwrap();
479            let box_new_def_id = self.resolve_single_path(span, &path)?;
480            let box_new_args = tcx.mk_args(&[array_rust_ty.into()]);
481            let box_new_item =
482                hax::ItemRef::translate(self.hax_state_with_id(), box_new_def_id, box_new_args);
483            let _ = self.translate_fn_ptr(span, &box_new_item, TransItemSourceKind::Fun)?;
484
485            let path = NamePattern::parse(names::BOX_WRITE).unwrap();
486            let box_write_def_id = self.resolve_single_path(span, &path)?;
487            let box_write_args = tcx.mk_args(&[array_rust_ty.into(), alloc_rust_ty.into()]);
488            let box_write_item =
489                hax::ItemRef::translate(self.hax_state_with_id(), box_write_def_id, box_write_args);
490            let _ = self.translate_fn_ptr(span, &box_write_item, TransItemSourceKind::Fun)?;
491        }
492
493        let body = {
494            let mut builder = BodyBuilder::new(span, sig.inputs.len());
495            let return_place = builder.new_var(Some("ret".to_string()), sig.output.clone());
496            let input = builder.new_var(Some("b".to_string()), sig.inputs[0].clone());
497            let initialized_box = builder.new_var(Some("x".to_string()), box_array_ty.clone());
498            let box_slice = builder.new_var(Some("y".to_string()), box_slice_ty.clone());
499
500            let call = {
501                let assume_init_fn = {
502                    let path = NamePattern::parse("alloc::boxed::Box::assume_init").unwrap();
503                    let assume_init_def_id = self
504                        .resolve_path(span, &path, true)?
505                        .into_iter()
506                        // There's `assume_init` on `Box<MU<T>>` and `Box<[MU<T>]>`, we want the former.
507                        .filter(|&def_id| {
508                            let sig = self.tcx.fn_sig(def_id);
509                            !sig.skip_binder().inputs().skip_binder()[0]
510                                .expect_boxed_ty()
511                                .is_slice()
512                        })
513                        .exactly_one()
514                        .unwrap();
515                    let assume_init_args =
516                        tcx.mk_args(&[array_rust_ty.into(), alloc_rust_ty.into()]);
517                    let assume_init_item = hax::ItemRef::translate(
518                        self.hax_state_with_id(),
519                        assume_init_def_id,
520                        assume_init_args,
521                    );
522                    self.translate_fn_ptr(span, &assume_init_item, TransItemSourceKind::Fun)?
523                };
524                Call {
525                    func: FnOperand::Regular(assume_init_fn),
526                    args: vec![Operand::Move(input)],
527                    safety: CallSafety::Inherit,
528                }
529            };
530            builder.call(initialized_box.clone(), call);
531
532            builder.push_statement({
533                let (path, meta) = hax::compute_unsizing_metadata(
534                    &self.hax_state,
535                    box_array_rust_ty,
536                    box_slice_rust_ty,
537                );
538                let meta = self.translate_unsizing_metadata(span, &meta)?;
539                let path = self.translate_metadata_path(&path);
540                StatementKind::Assign(
541                    box_slice.clone(),
542                    Rvalue::UnaryOp(
543                        UnOp::Cast(CastKind::Unsize(box_slice_ty, meta, path)),
544                        Operand::Move(initialized_box),
545                    ),
546                )
547            });
548
549            let call = {
550                let into_vec_fn = {
551                    let path = NamePattern::parse("slice::into_vec").unwrap();
552                    let into_vec_def_id = self.resolve_single_path(span, &path)?;
553                    let into_vec_args = tcx.mk_args(&[elem_rust_ty.into(), alloc_rust_ty.into()]);
554                    let into_vec_item = hax::ItemRef::translate(
555                        self.hax_state_with_id(),
556                        into_vec_def_id,
557                        into_vec_args,
558                    );
559                    self.translate_fn_ptr(span, &into_vec_item, TransItemSourceKind::Fun)?
560                };
561                Call {
562                    func: FnOperand::Regular(into_vec_fn),
563                    args: vec![Operand::Move(box_slice)],
564                    safety: CallSafety::Inherit,
565                }
566            };
567            builder.call(return_place, call);
568            builder.build()
569        };
570
571        Ok(Body::Unstructured(body))
572    }
573
574    /// Generate a function body for `core::intrinsics::type_id`.
575    pub(crate) fn build_type_id_body(
576        &mut self,
577        span: Span,
578        signature: &FunSig,
579    ) -> Result<Body, Error> {
580        let generics = self.outermost_generics().identity_args();
581        let type_id_ty = generics.types[0].clone();
582
583        let mut builder = BodyBuilder::new(span, signature.inputs.len());
584        let return_place = builder.new_var(Some("ret".to_string()), signature.output.clone());
585        let type_id = ConstantExpr::new(
586            ConstantExprKind::TypeId(type_id_ty),
587            signature.output.clone(),
588        );
589        builder.push_statement(StatementKind::Assign(
590            return_place,
591            Rvalue::Use(Operand::Const(type_id), WithRetag::No),
592        ));
593        Ok(Body::Unstructured(builder.build()))
594    }
595
596    /// Generate a function body for `core::ptr::drop_glue`.
597    pub(crate) fn build_drop_glue_body(
598        &mut self,
599        span: Span,
600        def: &hax::FullDef<'tcx>,
601        signature: &FunSig,
602    ) -> Result<Body, Error> {
603        let hax::FullDefKind::Fn(_) = def.kind() else {
604            unreachable!()
605        };
606        let def_id = def.def_id().as_real_def_id().unwrap();
607        let rustc_args = def.this().rustc_args(self.hax_state_with_id());
608        let rustc_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, rustc_args);
609        // `skip_binder` is ok because we have that lifetime in scope.
610        let input_ty = rustc_sig.skip_binder().inputs()[0];
611        let pointee_ty = input_ty
612            .builtin_deref(true)
613            .expect("`drop_glue` argument is not a pointer");
614        let fn_ptr = self.translate_drop_glue_method_call(span, pointee_ty)?;
615
616        let mut builder = BodyBuilder::new(span, signature.inputs.len());
617        let return_place = builder.new_var(Some("ret".to_string()), signature.output.clone());
618        builder.push_statement(StatementKind::Assign(return_place, Rvalue::unit_value()));
619        let input = builder.new_var(None, signature.inputs[0].clone());
620        builder.insert_drop(input.deref(), fn_ptr);
621        Ok(Body::Unstructured(builder.build()))
622    }
623}
624
625impl<'tcx> BodyTransCtx<'tcx, '_, '_> {
626    pub(crate) fn translate_local(&self, local: &mir::Local) -> Option<LocalId> {
627        self.locals_map.get(*local).copied()
628    }
629
630    /// Translate a basic block id and register it, if it hasn't been done.
631    fn translate_basic_block_id(&mut self, block_id: mir::BasicBlock) -> BlockId {
632        match self.blocks_map[block_id] {
633            Some(id) => id,
634            // Generate a fresh id - this also registers the block
635            None => {
636                // Push to the stack of blocks awaiting translation
637                self.blocks_stack.push_back(block_id);
638                let id = self.blocks.reserve_slot();
639                // Insert in the map
640                self.blocks_map[block_id] = Some(id);
641                id
642            }
643        }
644    }
645
646    fn translate_basic_block(
647        &mut self,
648        block_id: BlockId,
649        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
650        block: &mir::BasicBlockData<'tcx>,
651    ) -> Result<(), Error> {
652        // Translate the statements
653        let kind = if block.is_cleanup {
654            UnwindKind::Cleanup
655        } else {
656            UnwindKind::Regular
657        };
658        let mut block_ctx = BlockTransCtx::new(self, block_id, kind);
659        for statement in &block.statements {
660            trace!("statement: {:?}", statement);
661            block_ctx.translate_statement(source_scopes, statement)?;
662        }
663
664        // Translate the terminator
665        let terminator = block.terminator.as_ref().unwrap();
666        block_ctx.translate_terminator(source_scopes, terminator)?;
667
668        Ok(())
669    }
670
671    /// Gather all the lines that start with `//` inside the given span.
672    fn translate_body_comments(
673        &mut self,
674        source_text: &Option<String>,
675        charon_span: Span,
676    ) -> Vec<(u32, Vec<String>)> {
677        if let Some(body_text) = source_text {
678            let mut comments = body_text
679                .lines()
680                // Iter through the lines of this body in reverse order.
681                .rev()
682                .enumerate()
683                // Compute the absolute line number
684                .filter_map(|(i, line)| {
685                    Some(((charon_span.data().end.line).checked_sub(i as u32)?, line))
686                })
687                // Extract the comment if this line starts with `//`
688                .map(|(line_nbr, line)| (line_nbr, line.trim_start().strip_prefix("//")))
689                .peekable()
690                .batching(|iter| {
691                    // Get the next line. This is not a comment: it's either the last line of the
692                    // body or a line that wasn't consumed by `peeking_take_while`.
693                    let (line_nbr, _first) = iter.next()?;
694                    // Collect all the comments before this line.
695                    let mut comments = iter
696                        // `peeking_take_while` ensures we don't consume a line that returns
697                        // `false`. It will be consumed by the next round of `batching`.
698                        .peeking_take_while(|(_, opt_comment)| opt_comment.is_some())
699                        .map(|(_, opt_comment)| opt_comment.unwrap())
700                        .map(|s| s.strip_prefix(" ").unwrap_or(s))
701                        .map(str::to_owned)
702                        .collect_vec();
703                    comments.reverse();
704                    Some((line_nbr, comments))
705                })
706                .filter(|(_, comments)| !comments.is_empty())
707                .collect_vec();
708            comments.reverse();
709            comments
710        } else {
711            Vec::new()
712        }
713    }
714
715    fn translate_body(
716        mut self,
717        mir_body: &mir::Body<'tcx>,
718        source_text: &Option<String>,
719    ) -> Result<Body, Error> {
720        // Compute the span information
721        let span = self.translate_span(&mir_body.span);
722
723        // Translate the expression body
724        trace!("Translating the expression body");
725
726        // Register the start block
727        let id = self.translate_basic_block_id(rustc_index::Idx::new(mir::START_BLOCK.as_usize()));
728        assert!(id == START_BLOCK_ID);
729
730        // For as long as there are blocks in the stack, translate them
731        while let Some(mir_block_id) = self.blocks_stack.pop_front() {
732            let mir_block = mir_body.basic_blocks.get(mir_block_id).unwrap();
733            let block_id = self.translate_basic_block_id(mir_block_id);
734            self.translate_basic_block(block_id, &mir_body.source_scopes, mir_block)?;
735        }
736
737        // Record the outlives that need to hold throughout the body.
738        let outlives = self.user_type_annotations.outlives.drain(..).map(|pred| {
739            let kind = StatementKind::Borrowck(BorrowckStatement::SetOutlives(pred));
740            Statement::new(span, kind)
741        });
742        self.blocks[START_BLOCK_ID]
743            .statements
744            .splice(0..0, outlives);
745
746        // Create the body
747        let comments = self.translate_body_comments(source_text, span);
748        Ok(Body::Unstructured(ExprBody {
749            span,
750            locals: self.locals,
751            bound_body_regions: self
752                .i_ctx
753                .lifetime_freshener
754                .take()
755                .map_or(0, |v| v.slot_count()),
756            body: self.blocks.make_contiguous(),
757            comments,
758        }))
759    }
760}
761
762impl BodyTransformCtx for BlockTransCtx<'_, '_, '_, '_> {
763    fn get_crate(&self) -> &TranslatedCrate {
764        &self.translated
765    }
766
767    fn get_options(&self) -> &TranslateOptions {
768        &self.options
769    }
770
771    fn get_params(&self) -> &GenericParams {
772        self.outermost_generics()
773    }
774
775    fn get_locals_mut(&mut self) -> &mut Locals {
776        &mut self.locals
777    }
778
779    fn insert_storage_live_stmt(&mut self, local: LocalId) {
780        self.statements
781            .push(Statement::new(self.span, StatementKind::StorageLive(local)));
782    }
783
784    fn insert_storage_dead_stmt(&mut self, local: LocalId) {
785        self.statements
786            .push(Statement::new(self.span, StatementKind::StorageDead(local)));
787    }
788
789    fn insert_assn_stmt(&mut self, place: Place, rvalue: Rvalue) {
790        self.statements.push(Statement::new(
791            self.span,
792            StatementKind::Assign(place, rvalue),
793        ));
794    }
795}
796
797impl<'tcx> BlockTransCtx<'tcx, '_, '_, '_> {
798    fn missing_ptr_metadata() -> Operand {
799        Operand::Const(ConstantExpr::new(
800            ConstantExprKind::Opaque("Missing metadata".to_string()),
801            Ty::mk_unit(),
802        ))
803    }
804
805    fn translate_thread_local_ref(
806        &mut self,
807        span: Span,
808        def_id: rustc_hir::def_id::DefId,
809    ) -> Result<Rvalue, Error> {
810        let args = ty::GenericArgs::empty();
811        let item = hax::translate_item_ref(&self.hax_state, def_id, args);
812        let global_ref = self.translate_global_decl_ref(span, &item)?;
813
814        let ptr_ty = self.tcx.thread_local_ptr_ty(def_id);
815        let ty = ptr_ty.builtin_deref(true).unwrap();
816        let ty = self.translate_rustc_ty(span, &ty)?;
817        let place = Place::new_global(global_ref, ty);
818        match ptr_ty.kind() {
819            ty::TyKind::Ref(_, _, mutability) => {
820                let kind = if mutability.is_mut() {
821                    BorrowKind::Mut
822                } else {
823                    BorrowKind::Shared
824                };
825                Ok(Rvalue::Ref {
826                    place,
827                    kind,
828                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
829                    ptr_metadata: Self::missing_ptr_metadata(),
830                })
831            }
832            ty::TyKind::RawPtr(_, mutability) => {
833                let kind = if mutability.is_mut() {
834                    RefKind::Mut
835                } else {
836                    RefKind::Shared
837                };
838                Ok(Rvalue::RawPtr {
839                    place,
840                    kind,
841                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
842                    ptr_metadata: Self::missing_ptr_metadata(),
843                })
844            }
845            _ => raise_error!(
846                self,
847                span,
848                "unexpected type for thread-local reference: {ptr_ty:?}"
849            ),
850        }
851    }
852
853    fn translate_binaryop_kind(&mut self, _span: Span, binop: mir::BinOp) -> Result<BinOp, Error> {
854        Ok(match binop {
855            mir::BinOp::BitXor => BinOp::BitXor,
856            mir::BinOp::BitAnd => BinOp::BitAnd,
857            mir::BinOp::BitOr => BinOp::BitOr,
858            mir::BinOp::Eq => BinOp::Eq,
859            mir::BinOp::Lt => BinOp::Lt,
860            mir::BinOp::Le => BinOp::Le,
861            mir::BinOp::Ne => BinOp::Ne,
862            mir::BinOp::Ge => BinOp::Ge,
863            mir::BinOp::Gt => BinOp::Gt,
864            mir::BinOp::Add => BinOp::Add(OverflowMode::Wrap),
865            mir::BinOp::AddUnchecked => BinOp::Add(OverflowMode::UB),
866            mir::BinOp::Sub => BinOp::Sub(OverflowMode::Wrap),
867            mir::BinOp::SubUnchecked => BinOp::Sub(OverflowMode::UB),
868            mir::BinOp::Mul => BinOp::Mul(OverflowMode::Wrap),
869            mir::BinOp::MulUnchecked => BinOp::Mul(OverflowMode::UB),
870            mir::BinOp::Div => BinOp::Div(OverflowMode::UB),
871            mir::BinOp::Rem => BinOp::Rem(OverflowMode::UB),
872            mir::BinOp::AddWithOverflow
873            | mir::BinOp::SubWithOverflow
874            | mir::BinOp::MulWithOverflow => unreachable!("handled in `translate_statement`"),
875            mir::BinOp::Shl => BinOp::Shl(OverflowMode::Wrap),
876            mir::BinOp::ShlUnchecked => BinOp::Shl(OverflowMode::UB),
877            mir::BinOp::Shr => BinOp::Shr(OverflowMode::Wrap),
878            mir::BinOp::ShrUnchecked => BinOp::Shr(OverflowMode::UB),
879            mir::BinOp::Cmp => BinOp::Cmp,
880            mir::BinOp::Offset => unreachable!("handled in `translate_mir_rvalue`"),
881        })
882    }
883
884    fn translate_place(
885        &mut self,
886        span: Span,
887        mir_place: &mir::Place<'tcx>,
888    ) -> Result<Place, Error> {
889        use crate::hax::{BaseState, SInto};
890        use rustc_middle::ty;
891
892        let tcx = self.hax_state.base().tcx;
893        let local_decls = self.local_decls;
894        let mut place_ty: mir::PlaceTy = mir::Place::from(mir_place.local).ty(local_decls, tcx);
895        let var_id = self.translate_local(&mir_place.local).unwrap();
896        let mut place = self.locals.place_for_var(var_id);
897        for elem in mir_place.projection.as_slice() {
898            use mir::ProjectionElem::*;
899            if let TyKind::Error(msg) = place.ty().kind() {
900                return Err(Error {
901                    span,
902                    msg: msg.clone(),
903                });
904            }
905            let projected_place_ty = place_ty.projection_ty(tcx, *elem);
906            let next_place_ty = projected_place_ty.ty.sinto(&self.hax_state);
907            let next_place_ty = self.translate_ty(span, &next_place_ty)?;
908            let proj_elem = match elem {
909                Deref => ProjectionElem::Deref,
910                PhantomDeref => {
911                    raise_error!(self, span, "unsupported phantom dereference in MIR place");
912                }
913                Field(index, _) => {
914                    let TyKind::Adt(tref) = place.ty().kind() else {
915                        raise_error!(
916                            self,
917                            span,
918                            "found unexpected type in field projection: {}",
919                            next_place_ty.with_ctx(&self.into_fmt())
920                        )
921                    };
922                    let field_id = self.translate_field_id(*index);
923                    match place_ty.ty.kind() {
924                        ty::Adt(adt_def, _) => {
925                            let variant = place_ty.variant_index;
926                            let variant_id = variant.map(|id| self.translate_variant_id(id));
927                            let generics = &tref.generics;
928                            match tref.as_builtin() {
929                                None => {
930                                    assert!(
931                                        ((adt_def.is_struct() || adt_def.is_union())
932                                            && variant.is_none())
933                                            || (adt_def.is_enum() && variant.is_some())
934                                    );
935                                    ProjectionElem::Field(variant_id, field_id)
936                                }
937                                Some(BuiltinAdt::Tuple) => {
938                                    assert!(generics.regions.is_empty());
939                                    assert!(variant.is_none());
940                                    assert!(generics.const_generics.is_empty());
941                                    ProjectionElem::Field(None, field_id)
942                                }
943                                Some(BuiltinAdt::Box)
944                                    if self.t_ctx.options.treat_box_as_builtin =>
945                                {
946                                    // Some sanity checks
947                                    assert!(generics.regions.is_empty());
948                                    assert!(
949                                        self.t_ctx.options.monomorphize_with_hax
950                                            || generics.types.len() == 2
951                                    );
952                                    assert!(generics.const_generics.is_empty());
953                                    if field_id == FieldId::ZERO {
954                                        // We pretend the pointee field is a deref.
955                                        ProjectionElem::Deref
956                                    } else {
957                                        raise_error!(
958                                            self,
959                                            span,
960                                            "trying to access the allocator field from Box, \
961                                            but it is being treated as a builtin (without allocator)"
962                                        )
963                                    }
964                                }
965                                Some(BuiltinAdt::Box) => ProjectionElem::Field(None, field_id),
966                                Some(_) => {
967                                    raise_error!(self, span, "Unexpected field projection")
968                                }
969                            }
970                        }
971                        ty::Tuple(_types) => ProjectionElem::Field(None, field_id),
972                        // We get there when we access one of the fields of the state captured by a
973                        // closure.
974                        ty::Closure(..) => ProjectionElem::Field(None, field_id),
975                        _ => panic!(),
976                    }
977                }
978                Index(local) => {
979                    let offset =
980                        self.translate_operand(span, &mir::Operand::Copy((*local).into()))?;
981                    ProjectionElem::Index {
982                        offset: Box::new(offset),
983                        from_end: false,
984                    }
985                }
986                &ConstantIndex {
987                    offset, from_end, ..
988                } => {
989                    let offset =
990                        Operand::Const(IntegerValue::mk_usize(offset as u128).to_constant());
991                    ProjectionElem::Index {
992                        offset: Box::new(offset),
993                        from_end,
994                    }
995                }
996                &Subslice { from, to, from_end } => {
997                    let from = Operand::Const(IntegerValue::mk_usize(from as u128).to_constant());
998                    let to = Operand::Const(IntegerValue::mk_usize(to as u128).to_constant());
999                    ProjectionElem::Subslice {
1000                        from: Box::new(from),
1001                        to: Box::new(to),
1002                        from_end,
1003                    }
1004                }
1005                OpaqueCast(..) => {
1006                    raise_error!(self, span, "Unexpected ProjectionElem::OpaqueCast");
1007                }
1008                Downcast { .. } => {
1009                    // We keep the same `Place`, the variant is tracked in the `PlaceTy` and we can
1010                    // access it next loop iteration.
1011                    place_ty = projected_place_ty;
1012                    continue;
1013                }
1014                UnwrapUnsafeBinder { .. } => {
1015                    raise_error!(self, span, "unsupported feature: unsafe binders");
1016                }
1017            };
1018            place = place.project(proj_elem, next_place_ty);
1019            place_ty = projected_place_ty;
1020        }
1021        Ok(place)
1022    }
1023
1024    /// Translate an operand
1025    fn translate_operand(
1026        &mut self,
1027        span: Span,
1028        operand: &mir::Operand<'tcx>,
1029    ) -> Result<Operand, Error> {
1030        Ok(match operand {
1031            mir::Operand::Copy(place) => {
1032                let ty = place.ty(self.local_decls, self.tcx).ty;
1033                let p = self.translate_place(span, place)?;
1034                if let Some(proof) = hax::solve_copy(&self.hax_state, ty) {
1035                    let proof = self.translate_trait_proof(span, &proof)?.no_bound_vars();
1036                    Operand::Copy(p, proof)
1037                } else {
1038                    // Runtime MIR replaces `CopyForDeref` with `Copy`, so we may end up here for
1039                    // non-`Copy` types such as mutable references.
1040                    Operand::Read(p)
1041                }
1042            }
1043            mir::Operand::Move(place) => {
1044                let p = self.translate_place(span, place)?;
1045                Operand::Move(p)
1046            }
1047            mir::Operand::Constant(const_op) => {
1048                let annotated_ty = if let Some(base) = const_op.user_ty {
1049                    self.user_type_annotations.translate_annotation(base)
1050                } else {
1051                    None
1052                };
1053                let const_op = self.catch_sinto(span, &const_op)?;
1054                let operand = match &const_op.kind {
1055                    hax::ConstOperandKind::Value(constant) => {
1056                        let constant = self.translate_constant_expr(span, constant)?;
1057                        Operand::Const(constant)
1058                    }
1059                    hax::ConstOperandKind::Promoted(item) => {
1060                        // A promoted constant that could not be evaluated.
1061                        let global_ref = self.translate_global_decl_ref(span, item)?;
1062                        let constant = ConstantExpr::new(
1063                            ConstantExprKind::Global(global_ref),
1064                            self.translate_ty(span, &const_op.ty)?,
1065                        );
1066                        Operand::Const(constant)
1067                    }
1068                };
1069                if let Some(annotated_ty) = annotated_ty
1070                    && annotated_ty != *operand.ty()
1071                {
1072                    if let TyKind::FnDef(fn_ptr) = annotated_ty.kind() {
1073                        // The function type is a singleton hence determines the value uniquely.
1074                        // Prefer using the annotated type to preserve explicit turbofishing
1075                        // choices.
1076                        let fn_ptr = self.erase_region_binder(fn_ptr.clone());
1077                        Operand::Const(ConstantExpr::new(
1078                            ConstantExprKind::FnDef(fn_ptr),
1079                            annotated_ty,
1080                        ))
1081                    } else {
1082                        // For other constants, add the type annotation as a separate constraint.
1083                        let place = self.fresh_var(None, operand.ty().clone());
1084                        self.insert_assn_stmt(place.clone(), Rvalue::Use(operand, WithRetag::No));
1085                        self.statements.push(Statement::new(
1086                            span,
1087                            StatementKind::Borrowck(BorrowckStatement::SetType(
1088                                PlaceTypeConstraint {
1089                                    place: place.clone(),
1090                                    ty: annotated_ty,
1091                                    variance: Variance::Invariant,
1092                                },
1093                            )),
1094                        ));
1095                        Operand::Move(place)
1096                    }
1097                } else {
1098                    operand
1099                }
1100            }
1101            mir::Operand::RuntimeChecks(check) => {
1102                let op = match check {
1103                    mir::RuntimeChecks::UbChecks => NullOp::UbChecks,
1104                    mir::RuntimeChecks::OverflowChecks => NullOp::OverflowChecks,
1105                    mir::RuntimeChecks::ContractChecks => NullOp::ContractChecks,
1106                };
1107                let local = self.fresh_var(None, Ty::mk_bool());
1108                self.insert_assn_stmt(local.clone(), Rvalue::NullaryOp(op));
1109                Operand::Move(local)
1110            }
1111        })
1112    }
1113
1114    /// Translate an rvalue
1115    fn translate_mir_rvalue(
1116        &mut self,
1117        span: Span,
1118        rvalue: &mir::Rvalue<'tcx>,
1119        tgt_ty: &Ty,
1120    ) -> Result<Rvalue, Error> {
1121        match rvalue {
1122            mir::Rvalue::Use(operand, retag) => {
1123                let retag = match retag {
1124                    mir::WithRetag::Yes => WithRetag::Yes,
1125                    mir::WithRetag::No => WithRetag::No,
1126                };
1127                Ok(Rvalue::Use(self.translate_operand(span, operand)?, retag))
1128            }
1129            mir::Rvalue::CopyForDeref(place) => {
1130                // A read of a pointer, used only for derefing it. The pointer need not be `Copy`.
1131                let place = self.translate_place(span, place)?;
1132                Ok(Rvalue::Use(Operand::Read(place), WithRetag::No))
1133            }
1134            mir::Rvalue::Repeat(operand, _) => {
1135                let copy_proof = {
1136                    let rust_ty = operand.ty(self.local_decls, self.tcx);
1137                    hax::solve_copy(&self.hax_state, rust_ty)
1138                };
1139                let operand = self.translate_operand(span, operand)?;
1140                let TyKind::Array(elem_ty, len, ty_is_sized) = tgt_ty.kind() else {
1141                    raise_error!(self, span, "array repeat has non-array type")
1142                };
1143                if let Some(copy_proof) = copy_proof {
1144                    let elem_is_copy = self
1145                        .translate_trait_proof(span, &copy_proof)?
1146                        .no_bound_vars();
1147                    Ok(Rvalue::Repeat {
1148                        operand,
1149                        count: len.clone(),
1150                        elem_is_copy,
1151                        elem_is_sized: ty_is_sized.clone(),
1152                    })
1153                } else if let Operand::Const(value) = operand {
1154                    let value = ConstantExpr::new(
1155                        ConstantExprKind::Repeat {
1156                            value,
1157                            count: len.clone(),
1158                            value_is_sized: ty_is_sized.clone(),
1159                        },
1160                        tgt_ty.clone(),
1161                    );
1162                    Ok(Rvalue::Use(Operand::Const(value), WithRetag::Yes))
1163                } else if len.as_usize_literal() == Some(1) {
1164                    // A single element can be moved into the array without being `Copy`.
1165                    Ok(Rvalue::Aggregate(
1166                        AggregateKind::Array(elem_ty.clone(), len.clone(), ty_is_sized.clone()),
1167                        vec![operand],
1168                    ))
1169                } else {
1170                    raise_error!(
1171                        self,
1172                        span,
1173                        "Rvalue::Repeat found with an operand that is neither constant nor `Copy`"
1174                    )
1175                }
1176            }
1177            mir::Rvalue::Ref(_region, borrow_kind, place) => {
1178                let place = self.translate_place(span, place)?;
1179                let borrow_kind = self.translate_borrow_kind(span, *borrow_kind)?;
1180                Ok(Rvalue::Ref {
1181                    place,
1182                    kind: borrow_kind,
1183                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
1184                    ptr_metadata: Self::missing_ptr_metadata(),
1185                })
1186            }
1187            mir::Rvalue::RawPtr(mtbl, place) => {
1188                let mtbl = match mtbl {
1189                    mir::RawPtrKind::Mut => RefKind::Mut,
1190                    mir::RawPtrKind::Const => RefKind::Shared,
1191                    mir::RawPtrKind::FakeForPtrMetadata => RefKind::Shared,
1192                };
1193                let place = self.translate_place(span, place)?;
1194                Ok(Rvalue::RawPtr {
1195                    place,
1196                    kind: mtbl,
1197                    // Will be fixed by the cleanup pass `insert_ptr_metadata`.
1198                    ptr_metadata: Self::missing_ptr_metadata(),
1199                })
1200            }
1201            mir::Rvalue::Cast(cast_kind, mir_operand, rust_tgt_ty) => {
1202                let op_ty = mir_operand.ty(self.local_decls, self.tcx);
1203                let tgt_ty = self.translate_rustc_ty(span, rust_tgt_ty)?;
1204
1205                // Translate the operand
1206                let mut operand = self.translate_operand(span, mir_operand)?;
1207
1208                let mut cast_kind = match cast_kind {
1209                    mir::CastKind::IntToInt
1210                    | mir::CastKind::IntToFloat
1211                    | mir::CastKind::FloatToInt
1212                    | mir::CastKind::FloatToFloat => {
1213                        let tgt_ty = *tgt_ty.kind().as_scalar().unwrap();
1214                        CastKind::Scalar(tgt_ty)
1215                    }
1216                    mir::CastKind::PtrToPtr
1217                    | mir::CastKind::PointerCoercion(
1218                        ty::adjustment::PointerCoercion::MutToConstPointer,
1219                        ..,
1220                    )
1221                    | mir::CastKind::PointerCoercion(
1222                        ty::adjustment::PointerCoercion::ArrayToPointer,
1223                        ..,
1224                    )
1225                    | mir::CastKind::FnPtrToPtr => CastKind::RawPtr(tgt_ty.clone()),
1226
1227                    mir::CastKind::PointerExposeProvenance => {
1228                        let tgt_ty = *tgt_ty.kind().as_scalar().unwrap().as_integer().unwrap();
1229                        CastKind::PtrExposeProvenance(tgt_ty)
1230                    }
1231                    mir::CastKind::PointerWithExposedProvenance => {
1232                        CastKind::PtrWithExposedProvenance(tgt_ty.clone())
1233                    }
1234                    mir::CastKind::PointerCoercion(
1235                        ty::adjustment::PointerCoercion::ClosureFnPointer(_),
1236                        ..,
1237                    ) => {
1238                        let hax_op_ty: hax::Ty = self.catch_sinto(span, &op_ty)?;
1239                        // We model casts of closures to function pointers by generating a new
1240                        // function item without the closure's state, that calls the actual closure.
1241                        let hax::TyKind::Closure(closure) = hax_op_ty.kind() else {
1242                            unreachable!("Non-closure type in PointerCoercion::ClosureFnPointer");
1243                        };
1244                        let fn_ref: RegionBinder<FunDeclRef> =
1245                            self.translate_stateless_closure_as_fn_ref(span, closure)?;
1246                        let fn_ptr_bound: RegionBinder<FnPtr> = fn_ref.map(FunDeclRef::into);
1247                        let fn_ptr: FnPtr = self.erase_region_binder(fn_ptr_bound.clone());
1248                        let src_ty = TyKind::FnDef(fn_ptr_bound).into_ty();
1249                        operand = Operand::Const(ConstantExpr::new(
1250                            ConstantExprKind::FnDef(fn_ptr),
1251                            src_ty.clone(),
1252                        ));
1253                        CastKind::FnDefToFnPtr
1254                    }
1255                    mir::CastKind::PointerCoercion(
1256                        ty::adjustment::PointerCoercion::ReifyFnPointer(_),
1257                        ..,
1258                    ) => CastKind::FnDefToFnPtr,
1259                    mir::CastKind::PointerCoercion(
1260                        ty::adjustment::PointerCoercion::UnsafeFnPointer,
1261                        ..,
1262                    ) => CastKind::FnPtrToUnsafe,
1263                    mir::CastKind::Transmute => CastKind::Transmute(tgt_ty.clone()),
1264                    mir::CastKind::BoxDerefTransmute => CastKind::BoxDerefTransmute(tgt_ty.clone()),
1265                    mir::CastKind::Subtype => CastKind::Subtype(tgt_ty.clone()),
1266                    mir::CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, ..) => {
1267                        let (path, meta) =
1268                            hax::compute_unsizing_metadata(&self.hax_state, op_ty, *rust_tgt_ty);
1269                        let meta = self.translate_unsizing_metadata(span, &meta)?;
1270                        CastKind::Unsize(tgt_ty.clone(), meta, self.translate_metadata_path(&path))
1271                    }
1272                };
1273
1274                // We're more precise than rustc: we separate "cast to fn ptr" and "safety cast",
1275                // so we reconstruct the distinction here.
1276                if let CastKind::FnDefToFnPtr = cast_kind {
1277                    let rustc_sig = match op_ty.kind() {
1278                        ty::TyKind::FnDef(..) => op_ty.fn_sig(self.tcx),
1279                        ty::TyKind::Closure(_, args) => {
1280                            hax::closure_sig(self.tcx, args.as_closure())
1281                        }
1282                        _ => unreachable!("Expected a function definition or closure"),
1283                    };
1284                    let rustc_fn_ptr = ty::Ty::new_fn_ptr(self.tcx, rustc_sig);
1285                    let intermediate_ty = self.translate_rustc_ty(span, &rustc_fn_ptr)?;
1286                    let (TyKind::FnPtr(interm), TyKind::FnPtr(target)) =
1287                        (intermediate_ty.kind(), tgt_ty.kind())
1288                    else {
1289                        raise_error!(self, span, "Expected function pointers in fn pointer cast")
1290                    };
1291                    if interm.skip_binder.is_unsafe != target.skip_binder.is_unsafe {
1292                        let local = self.rval_to_place(
1293                            Rvalue::UnaryOp(UnOp::Cast(CastKind::FnDefToFnPtr), operand),
1294                            intermediate_ty.clone(),
1295                        );
1296                        operand = Operand::Move(local);
1297                        cast_kind = CastKind::FnPtrToUnsafe;
1298                    }
1299                }
1300
1301                Ok(Rvalue::UnaryOp(UnOp::Cast(cast_kind), operand))
1302            }
1303            // `ptr.offset(n)` becomes `&raw (*ptr).offset(n)`.
1304            mir::Rvalue::BinaryOp(mir::BinOp::Offset, (ptr, n)) => {
1305                let TyKind::RawPtr(pointee, kind) = tgt_ty.kind() else {
1306                    raise_error!(self, span, "`Offset` on a non-raw-pointer type")
1307                };
1308                let rust_pointee = ptr
1309                    .ty(self.local_decls, self.tcx)
1310                    .builtin_deref(true)
1311                    .unwrap();
1312                let pointee_is_sized = self.translate_sized_proof(span, rust_pointee)?;
1313                let ptr = match self.translate_operand(span, ptr)? {
1314                    Operand::Copy(p, _) | Operand::Read(p) | Operand::Move(p) => p,
1315                    op @ Operand::Const(_) => {
1316                        let ty = op.ty().clone();
1317                        self.rval_to_place(Rvalue::Use(op, WithRetag::No), ty)
1318                    }
1319                };
1320                let n = self.translate_operand(span, n)?;
1321                // MIR's `Offset` is UB if it goes out of bounds.
1322                let offset = self.offset_projection(
1323                    n,
1324                    Some(pointee),
1325                    true,
1326                    pointee.clone(),
1327                    pointee_is_sized,
1328                );
1329                let place = ptr.deref().project(offset, pointee.clone());
1330                Ok(Rvalue::RawPtr {
1331                    place,
1332                    kind: *kind,
1333                    ptr_metadata: Operand::mk_const_unit(),
1334                })
1335            }
1336            mir::Rvalue::BinaryOp(binop, (left, right)) => Ok(Rvalue::BinaryOp(
1337                self.translate_binaryop_kind(span, *binop)?,
1338                self.translate_operand(span, left)?,
1339                self.translate_operand(span, right)?,
1340            )),
1341            mir::Rvalue::UnaryOp(unop, operand) => {
1342                let operand_ty = operand.ty(self.local_decls, self.tcx);
1343                let operand = self.translate_operand(span, operand)?;
1344                let unop = match unop {
1345                    mir::UnOp::Not => UnOp::Not,
1346                    mir::UnOp::Neg => UnOp::Neg(OverflowMode::Wrap),
1347                    mir::UnOp::PtrMetadata => match operand {
1348                        Operand::Copy(p, _) | Operand::Read(p) | Operand::Move(p) => {
1349                            let metadata_ty = unop.ty(self.tcx, operand_ty);
1350                            let proof = hax::solve_copy(&self.hax_state, metadata_ty)
1351                                .expect("pointer metadata is always Copy");
1352                            let proof = self.translate_trait_proof(span, &proof)?.no_bound_vars();
1353                            return Ok(Rvalue::Use(
1354                                Operand::Copy(
1355                                    p.project(ProjectionElem::PtrMetadata, tgt_ty.clone()),
1356                                    proof,
1357                                ),
1358                                WithRetag::No,
1359                            ));
1360                        }
1361                        Operand::Const(_) => {
1362                            panic!("unexpected metadata operand")
1363                        }
1364                    },
1365                };
1366                Ok(Rvalue::UnaryOp(unop, operand))
1367            }
1368            mir::Rvalue::Discriminant(place) => {
1369                let place = self.translate_place(span, place)?;
1370                Ok(Rvalue::Discriminant(place))
1371            }
1372            mir::Rvalue::Aggregate(aggregate_kind, operands) => {
1373                // It seems this instruction is not present in certain passes:
1374                // for example, it seems it is not used in optimized MIR, where
1375                // ADT initialization is split into several instructions, for
1376                // instance:
1377                // ```
1378                // p = Pair { x:xv, y:yv };
1379                // ```
1380                // Might become:
1381                // ```
1382                // p.x = x;
1383                // p.y = yv;
1384                // ```
1385
1386                // First translate the operands
1387                let operands_t: Vec<Operand> = operands
1388                    .iter()
1389                    .map(|op| self.translate_operand(span, op))
1390                    .try_collect()?;
1391                match aggregate_kind {
1392                    mir::AggregateKind::Array(ty) => {
1393                        let t_ty = self.translate_rustc_ty(span, ty)?;
1394                        let len = ConstantExpr::mk_usize(operands_t.len() as u128);
1395                        let TyKind::Array(_, _, ty_is_sized) = tgt_ty.kind() else {
1396                            raise_error!(self, span, "array aggregate has non-array type")
1397                        };
1398                        if operands_t.len() >= 2 && operands_t.iter().all(Operand::is_const) {
1399                            let fields =
1400                                operands_t.iter().map(|operand| operand.as_const().unwrap());
1401                            if let Ok(field) = fields.dedup().exactly_one()
1402                                && let Some(copy_proof) = hax::solve_copy(&self.hax_state, *ty)
1403                            {
1404                                let ty_is_copy = self
1405                                    .translate_trait_proof(span, &copy_proof)?
1406                                    .no_bound_vars();
1407                                return Ok(Rvalue::Repeat {
1408                                    operand: Operand::Const(field.clone()),
1409                                    count: len,
1410                                    elem_is_sized: ty_is_sized.clone(),
1411                                    elem_is_copy: ty_is_copy,
1412                                });
1413                            }
1414                        }
1415                        Ok(Rvalue::Aggregate(
1416                            AggregateKind::Array(t_ty, len, ty_is_sized.clone()),
1417                            operands_t,
1418                        ))
1419                    }
1420                    mir::AggregateKind::Tuple => {
1421                        let tys = operands.iter().map(|op| op.ty(self.local_decls, self.tcx));
1422                        let ty = ty::Ty::new_tup_from_iter(self.tcx, tys);
1423                        let ty = self.translate_rustc_ty(span, &ty)?;
1424                        let tref = ty.as_adt().unwrap().clone();
1425                        Ok(Rvalue::Aggregate(
1426                            AggregateKind::Adt(tref, None, None),
1427                            operands_t,
1428                        ))
1429                    }
1430                    mir::AggregateKind::Adt(
1431                        def_id,
1432                        variant_idx,
1433                        generics,
1434                        user_ty,
1435                        field_index,
1436                    ) => {
1437                        use ty::AdtKind;
1438                        trace!("{:?}", rvalue);
1439
1440                        let adt_kind = self.tcx.adt_def(*def_id).adt_kind();
1441                        let tref = if let Some(user_ty) = *user_ty
1442                            && let Some(ty) =
1443                                self.user_type_annotations.translate_annotation(user_ty)
1444                        {
1445                            // Use the type annotation if there is one.
1446                            let TyKind::Adt(tref) = ty.kind() else {
1447                                raise_error!(self, span, "aggregate annotation has non-ADT type");
1448                            };
1449                            tref.clone()
1450                        } else {
1451                            let item = hax::translate_item_ref(&self.hax_state, *def_id, *generics);
1452                            self.translate_type_decl_ref(span, &item)?
1453                        };
1454                        let variant_id = match adt_kind {
1455                            AdtKind::Struct | AdtKind::Union => None,
1456                            AdtKind::Enum => Some(self.translate_variant_id(*variant_idx)),
1457                        };
1458                        let field_id = match adt_kind {
1459                            AdtKind::Struct | AdtKind::Enum => None,
1460                            AdtKind::Union => Some(self.translate_field_id(field_index.unwrap())),
1461                        };
1462
1463                        let akind = AggregateKind::Adt(tref, variant_id, field_id);
1464                        Ok(Rvalue::Aggregate(akind, operands_t))
1465                    }
1466                    mir::AggregateKind::Closure(def_id, generics) => {
1467                        let item = hax::translate_item_ref(&self.hax_state, *def_id, *generics);
1468                        let tref = self.translate_closure_type_ref(span, &item)?;
1469                        let akind = AggregateKind::Adt(tref, None, None);
1470                        Ok(Rvalue::Aggregate(akind, operands_t))
1471                    }
1472                    mir::AggregateKind::RawPtr(ty, mutability) => {
1473                        let t_ty = self.translate_rustc_ty(span, ty)?;
1474                        let mutability = if mutability.is_mut() {
1475                            RefKind::Mut
1476                        } else {
1477                            RefKind::Shared
1478                        };
1479
1480                        let akind = AggregateKind::RawPtr(t_ty, mutability);
1481
1482                        Ok(Rvalue::Aggregate(akind, operands_t))
1483                    }
1484                    mir::AggregateKind::Coroutine(..)
1485                    | mir::AggregateKind::CoroutineClosure(..) => {
1486                        raise_error!(self, span, "Coroutines are not supported");
1487                    }
1488                }
1489            }
1490            mir::Rvalue::ThreadLocalRef(def_id) => self.translate_thread_local_ref(span, *def_id),
1491            mir::Rvalue::WrapUnsafeBinder { .. } => {
1492                raise_error!(
1493                    self,
1494                    span,
1495                    "charon does not support unsafe lifetime binders"
1496                );
1497            }
1498            mir::Rvalue::Reborrow(..) => {
1499                raise_error!(
1500                    self,
1501                    span,
1502                    "charon does not support reborrow rvalues (for Reborrow traits)"
1503                );
1504            }
1505        }
1506    }
1507
1508    /// Translate a statement.
1509    fn translate_statement(
1510        &mut self,
1511        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
1512        statement: &mir::Statement<'tcx>,
1513    ) -> Result<(), Error> {
1514        trace!("About to translate statement (MIR) {:?}", statement);
1515        let span = self.translate_span_from_source_info(source_scopes, &statement.source_info);
1516
1517        self.span = span;
1518        let kind: Option<StatementKind> = match &statement.kind {
1519            mir::StatementKind::Assign((
1520                place,
1521                mir::Rvalue::BinaryOp(
1522                    binop @ (mir::BinOp::AddWithOverflow
1523                    | mir::BinOp::SubWithOverflow
1524                    | mir::BinOp::MulWithOverflow),
1525                    (left, right),
1526                ),
1527            )) => {
1528                // Translate these binops to intrinsic calls to make binops easier to typecheck:
1529                // their return type is a tuple, which we monomorphize hence it's hard to compute
1530                // ourselves.
1531                let name = match binop {
1532                    mir::BinOp::AddWithOverflow => sym::add_with_overflow,
1533                    mir::BinOp::SubWithOverflow => sym::sub_with_overflow,
1534                    mir::BinOp::MulWithOverflow => sym::mul_with_overflow,
1535                    _ => unreachable!(),
1536                };
1537                let ty = left.ty(self.local_decls, self.tcx);
1538                let generic_args = self.tcx.mk_args(&[ty.into()]);
1539                let dest = self.translate_place(span, place)?;
1540                let left = self.translate_operand(span, left)?;
1541                let right = self.translate_operand(span, right)?;
1542                self.translate_intrinsic_call(span, dest, name, generic_args, vec![left, right])?;
1543                None
1544            }
1545            mir::StatementKind::Assign((place, rvalue)) => {
1546                let t_place = self.translate_place(span, place)?;
1547                let t_rvalue = self.translate_mir_rvalue(span, rvalue, t_place.ty())?;
1548                Some(StatementKind::Assign(t_place, t_rvalue))
1549            }
1550            mir::StatementKind::SetDiscriminant {
1551                place,
1552                variant_index,
1553            } => {
1554                let t_place = self.translate_place(span, place)?;
1555                let variant_id = self.translate_variant_id(*variant_index);
1556                Some(StatementKind::SetDiscriminant(t_place, variant_id))
1557            }
1558            mir::StatementKind::StorageLive(local) => {
1559                let var_id = self.translate_local(local).unwrap();
1560                Some(StatementKind::StorageLive(var_id))
1561            }
1562            mir::StatementKind::StorageDead(local) => {
1563                let var_id = self.translate_local(local).unwrap();
1564                Some(StatementKind::StorageDead(var_id))
1565            }
1566            mir::StatementKind::Intrinsic(mir::NonDivergingIntrinsic::Assume(op)) => {
1567                let op = self.translate_operand(span, op)?;
1568                let dest = self.locals.new_var(None, Ty::mk_unit());
1569                self.translate_intrinsic_call(
1570                    span,
1571                    dest,
1572                    sym::assume,
1573                    ty::GenericArgs::empty(),
1574                    vec![op],
1575                )?;
1576                None
1577            }
1578            mir::StatementKind::Intrinsic(mir::NonDivergingIntrinsic::CopyNonOverlapping(
1579                mir::CopyNonOverlapping { src, dst, count },
1580            )) => {
1581                let pointee_ty = src
1582                    .ty(self.local_decls, self.tcx)
1583                    .builtin_deref(true)
1584                    .unwrap();
1585                let generic_args = self.tcx.mk_args(&[pointee_ty.into()]);
1586                let src = self.translate_operand(span, src)?;
1587                let dst = self.translate_operand(span, dst)?;
1588                let count = self.translate_operand(span, count)?;
1589                let dest = self.locals.new_var(None, Ty::mk_unit());
1590                self.translate_intrinsic_call(
1591                    span,
1592                    dest,
1593                    sym::copy_nonoverlapping,
1594                    generic_args,
1595                    vec![src, dst, count],
1596                )?;
1597                None
1598            }
1599            mir::StatementKind::PlaceMention(place) => {
1600                let place = self.translate_place(span, place)?;
1601                // We only translate this for places with projections, as
1602                // no UB can arise from simply mentioning a local variable.
1603                if place.is_local() {
1604                    None
1605                } else {
1606                    Some(StatementKind::PlaceMention(place))
1607                }
1608            }
1609            mir::StatementKind::FakeRead((_, place)) => {
1610                let place = self.translate_place(span, place)?;
1611                Some(StatementKind::Borrowck(BorrowckStatement::FakeRead(place)))
1612            }
1613            mir::StatementKind::AscribeUserType((place, user_ty), variance) => {
1614                let variance = match variance {
1615                    ty::Variance::Covariant => Variance::Covariant,
1616                    ty::Variance::Invariant => Variance::Invariant,
1617                    ty::Variance::Contravariant => Variance::Contravariant,
1618                    // Does nothing so we discard it.
1619                    ty::Variance::Bivariant => return Ok(()),
1620                };
1621                let place = self.translate_place(span, place)?;
1622                let ty = self
1623                    .user_type_annotations
1624                    .translate_projected_annotation(user_ty);
1625                // This is a statement for practical impl reasons, but semantically this constrains
1626                // the local throughout the body.
1627                let local_id = place.local_id().expect("MIR ascription without a local");
1628                self.locals[local_id]
1629                    .borrowck_constraints
1630                    .push(PlaceTypeConstraint {
1631                        place,
1632                        ty,
1633                        variance,
1634                    });
1635                None
1636            }
1637            // Used for coverage instrumentation.
1638            mir::StatementKind::Coverage(_) => None,
1639            // Used in the interpreter to check that const code doesn't run for too long or even
1640            // indefinitely.
1641            mir::StatementKind::ConstEvalCounter => None,
1642            // Semantically equivalent to `Nop`, used only for rustc lints.
1643            mir::StatementKind::BackwardIncompatibleDropHint { .. } => None,
1644            mir::StatementKind::Nop => None,
1645        };
1646
1647        let Some(kind) = kind else {
1648            return Ok(());
1649        };
1650        self.statements.push(Statement::new(span, kind));
1651        Ok(())
1652    }
1653
1654    /// Translate a call to a non-diverging intrinsic.
1655    fn translate_intrinsic_call(
1656        &mut self,
1657        span: Span,
1658        dest: Place,
1659        name: Symbol,
1660        generic_args: ty::GenericArgs<'tcx>,
1661        args: Vec<Operand>,
1662    ) -> Result<(), Error> {
1663        // Sadly rustc doesn't expose a Symbol -> DefId map for intrinsics.
1664        let def_id = match self.t_ctx.intrinsic_def_ids.get(&name) {
1665            Some(&def_id) => def_id,
1666            None => {
1667                let path = NamePattern::parse(&format!("core::intrinsics::{name}")).unwrap();
1668                let def_id = self.resolve_single_path(span, &path)?;
1669                self.t_ctx.intrinsic_def_ids.insert(name, def_id);
1670                def_id
1671            }
1672        };
1673        assert!(self.tcx.is_rustc_intrinsic(def_id, name));
1674        let item = hax::ItemRef::translate(self.hax_state_with_id(), def_id, generic_args);
1675        let func =
1676            FnOperand::Regular(self.translate_fn_ptr(span, &item, TransItemSourceKind::Fun)?);
1677        self.push_nounwind_call(
1678            span,
1679            dest,
1680            Call {
1681                func,
1682                args,
1683                safety: CallSafety::Inherit,
1684            },
1685        );
1686        Ok(())
1687    }
1688
1689    /// Translate a terminator
1690    fn translate_terminator(
1691        mut self,
1692        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
1693        terminator: &mir::Terminator<'tcx>,
1694    ) -> Result<(), Error> {
1695        trace!("About to translate terminator (MIR) {:?}", terminator);
1696        let span = self.translate_span_from_source_info(source_scopes, &terminator.source_info);
1697
1698        // Translate the terminator
1699        self.span = span;
1700        use mir::TerminatorKind;
1701        let kind: ullbc_ast::TerminatorKind = match &terminator.kind {
1702            TerminatorKind::Goto {
1703                target,
1704                loop_hint_attrs: _,
1705            } => {
1706                let target = self.translate_basic_block_id(*target);
1707                ullbc_ast::TerminatorKind::Goto { target }
1708            }
1709            TerminatorKind::SwitchInt { discr, targets, .. } => {
1710                let discr = self.translate_operand(span, discr)?;
1711                let (data, branches) = self.translate_switch_targets(span, discr, targets)?;
1712                ullbc_ast::TerminatorKind::Switch { data, branches }
1713            }
1714            TerminatorKind::UnwindResume => ullbc_ast::TerminatorKind::UnwindResume,
1715            TerminatorKind::UnwindTerminate(reason) => {
1716                self.translate_unwind_terminate(span, *reason)?
1717            }
1718            TerminatorKind::Return => ullbc_ast::TerminatorKind::Return,
1719            // A MIR `Unreachable` terminator indicates undefined behavior of the rust abstract
1720            // machine.
1721            TerminatorKind::Unreachable => ullbc_ast::TerminatorKind::UndefinedBehavior,
1722            TerminatorKind::Drop {
1723                place,
1724                target,
1725                unwind,
1726                ..
1727            } => self.translate_drop(span, place, target, unwind)?,
1728            TerminatorKind::Call {
1729                func,
1730                args,
1731                destination,
1732                target,
1733                unwind,
1734                ..
1735            } => self.translate_function_call(span, func, args, destination, target, unwind)?,
1736            TerminatorKind::Assert {
1737                cond,
1738                expected,
1739                msg,
1740                target,
1741                unwind,
1742            } => {
1743                let on_unwind = self.translate_unwind_action(span, unwind)?;
1744                let kind = self.translate_assert_kind(span, msg)?;
1745                let (lang_item, args) = match &kind {
1746                    BuiltinAssertKind::BoundsCheck { len, index } => {
1747                        (LangItem::PanicBoundsCheck, vec![index.clone(), len.clone()])
1748                    }
1749                    BuiltinAssertKind::MisalignedPointerDereference { required, found } => (
1750                        LangItem::PanicMisalignedPointerDereference,
1751                        vec![required.clone(), found.clone()],
1752                    ),
1753                    BuiltinAssertKind::InvalidEnumConstruction(source) => {
1754                        (msg.panic_function(), vec![source.clone()])
1755                    }
1756                    _ => (msg.panic_function(), vec![]),
1757                };
1758                let def_id = self
1759                    .tcx
1760                    .require_lang_item(lang_item, terminator.source_info.span);
1761                let item =
1762                    hax::translate_item_ref(&self.hax_state, def_id, ty::GenericArgs::empty());
1763                let func = self.translate_fn_ptr(span, &item, TransItemSourceKind::Fun)?;
1764                let assert = Assert {
1765                    cond: self.translate_operand(span, cond)?,
1766                    expected: *expected,
1767                    check_kind: Some(kind),
1768                    call: Box::new(Call {
1769                        func: FnOperand::Regular(func),
1770                        args,
1771                        safety: CallSafety::Inherit,
1772                    }),
1773                };
1774                let target = self.translate_basic_block_id(*target);
1775                ullbc_ast::TerminatorKind::Assert {
1776                    assert,
1777                    target,
1778                    on_unwind,
1779                }
1780            }
1781            TerminatorKind::FalseEdge {
1782                real_target,
1783                imaginary_target: _,
1784            } => {
1785                // False edges are used to make the borrow checker a bit conservative.
1786                // We translate them as Gotos.
1787                // Also note that they are used in some passes, and not in some others
1788                // (they are present in mir_promoted, but not mir_optimized).
1789                let target = self.translate_basic_block_id(*real_target);
1790                ullbc_ast::TerminatorKind::Goto { target }
1791            }
1792            TerminatorKind::FalseUnwind {
1793                real_target,
1794                unwind: _,
1795            } => {
1796                // We consider this to be a goto
1797                let target = self.translate_basic_block_id(*real_target);
1798                ullbc_ast::TerminatorKind::Goto { target }
1799            }
1800            TerminatorKind::InlineAsm {
1801                asm_macro,
1802                template,
1803                operands,
1804                options,
1805                targets,
1806                unwind,
1807                ..
1808            } => {
1809                use rustc_ast::ast::InlineAsmOptions as O;
1810                let kind = match asm_macro {
1811                    mir::InlineAsmMacro::Asm => AsmKind::Asm,
1812                    mir::InlineAsmMacro::NakedAsm => AsmKind::NakedAsm,
1813                };
1814                let options = AsmOptions {
1815                    pure: options.contains(O::PURE),
1816                    nomem: options.contains(O::NOMEM),
1817                    readonly: options.contains(O::READONLY),
1818                    preserves_flags: options.contains(O::PRESERVES_FLAGS),
1819                    noreturn: options.contains(O::NORETURN),
1820                    nostack: options.contains(O::NOSTACK),
1821                    att_syntax: options.contains(O::ATT_SYNTAX),
1822                    may_unwind: options.contains(O::MAY_UNWIND),
1823                };
1824                let template = template
1825                    .iter()
1826                    .map(|piece| match piece {
1827                        rustc_ast::ast::InlineAsmTemplatePiece::String(text) => {
1828                            AsmTemplatePiece::Text(text.to_string().into())
1829                        }
1830                        rustc_ast::ast::InlineAsmTemplatePiece::Placeholder {
1831                            operand_idx,
1832                            modifier,
1833                            span,
1834                        } => AsmTemplatePiece::Placeholder {
1835                            operand_id: AsmOperandId::from_usize(*operand_idx),
1836                            modifier: *modifier,
1837                            span: self.translate_span(span),
1838                        },
1839                    })
1840                    .collect();
1841                let has_fallthrough = matches!(kind, AsmKind::Asm) && !options.noreturn;
1842                let translate_reg = |reg: &rustc_target::asm::InlineAsmRegOrRegClass| match reg {
1843                    rustc_target::asm::InlineAsmRegOrRegClass::Reg(reg) => {
1844                        AsmRegister::Explicit(reg.name().to_string().into())
1845                    }
1846                    rustc_target::asm::InlineAsmRegOrRegClass::RegClass(class) => {
1847                        AsmRegister::Class(class.name().to_string().into())
1848                    }
1849                };
1850                let operands = operands
1851                    .iter()
1852                    .map(|operand| {
1853                        Ok(match operand {
1854                            mir::InlineAsmOperand::In { reg, value } => AsmOperand::In {
1855                                reg: translate_reg(reg),
1856                                value: self.translate_operand(span, value)?,
1857                            },
1858                            mir::InlineAsmOperand::Out { reg, late, place } => AsmOperand::Out {
1859                                reg: translate_reg(reg),
1860                                late: *late,
1861                                place: place
1862                                    .as_ref()
1863                                    .map(|place| self.translate_place(span, place))
1864                                    .transpose()?,
1865                            },
1866                            mir::InlineAsmOperand::InOut {
1867                                reg,
1868                                late,
1869                                in_value,
1870                                out_place,
1871                            } => AsmOperand::InOut {
1872                                reg: translate_reg(reg),
1873                                late: *late,
1874                                in_value: self.translate_operand(span, in_value)?,
1875                                out_place: out_place
1876                                    .as_ref()
1877                                    .map(|place| self.translate_place(span, place))
1878                                    .transpose()?,
1879                            },
1880                            mir::InlineAsmOperand::Const { value } => {
1881                                let Operand::Const(value) = self.translate_operand(
1882                                    span,
1883                                    &mir::Operand::Constant(value.clone()),
1884                                )?
1885                                else {
1886                                    unreachable!("inline asm const operand is not a constant")
1887                                };
1888                                AsmOperand::Const(value)
1889                            }
1890                            mir::InlineAsmOperand::SymFn { value } => {
1891                                let Operand::Const(value) = self.translate_operand(
1892                                    span,
1893                                    &mir::Operand::Constant(value.clone()),
1894                                )?
1895                                else {
1896                                    unreachable!("inline asm function symbol is not a constant")
1897                                };
1898                                let ConstantExprKind::FnDef(fn_ptr) = value.kind() else {
1899                                    unreachable!("inline asm function symbol is not a function")
1900                                };
1901                                AsmOperand::SymFn(fn_ptr.clone())
1902                            }
1903                            mir::InlineAsmOperand::SymStatic { def_id } => {
1904                                let item = hax::translate_item_ref(
1905                                    &self.hax_state,
1906                                    *def_id,
1907                                    ty::GenericArgs::empty(),
1908                                );
1909                                AsmOperand::SymStatic(self.translate_global_decl_ref(span, &item)?)
1910                            }
1911                            mir::InlineAsmOperand::Label { target_index } => AsmOperand::Label(
1912                                BranchId::from_usize(*target_index - usize::from(has_fallthrough)),
1913                            ),
1914                        })
1915                    })
1916                    .collect::<Result<IndexVec<AsmOperandId, _>, Error>>()?;
1917                let fallthrough =
1918                    has_fallthrough.then(|| self.translate_basic_block_id(targets[0]));
1919                let labels = targets
1920                    .iter()
1921                    .skip(usize::from(has_fallthrough))
1922                    .map(|target| self.translate_basic_block_id(*target))
1923                    .collect();
1924                let on_unwind = self.translate_unwind_action(span, unwind)?;
1925                let asm = Box::new(InlineAsm {
1926                    kind,
1927                    template,
1928                    operands,
1929                    options,
1930                });
1931                ullbc_ast::TerminatorKind::InlineAsm {
1932                    asm,
1933                    fallthrough,
1934                    labels,
1935                    on_unwind,
1936                }
1937            }
1938            TerminatorKind::CoroutineDrop
1939            | TerminatorKind::TailCall { .. }
1940            | TerminatorKind::Yield { .. } => {
1941                raise_error!(self, span, "Unsupported terminator: {:?}", terminator.kind);
1942            }
1943        };
1944
1945        self.finish_current_block(Terminator::new(span, kind));
1946        Ok(())
1947    }
1948
1949    /// Translate switch targets
1950    fn translate_switch_targets(
1951        &mut self,
1952        span: Span,
1953        discr: Operand,
1954        targets: &mir::SwitchTargets,
1955    ) -> Result<(SwitchData, IndexVec<BranchId, BlockId>), Error> {
1956        // Convert all the test values to the proper values.
1957        let otherwise = targets.otherwise();
1958        let switch_ty = discr.ty();
1959        let switch_scalar_ty = *switch_ty.as_scalar().unwrap();
1960        let mut branch_targets: IndexVec<BranchId, BlockId> = IndexVec::new();
1961        let mut target_to_branch: SeqHashMap<BlockId, BranchId> = SeqHashMap::default();
1962        let mut switch_branches = Vec::with_capacity(targets.iter().count());
1963
1964        // Keep the historical true-then-false traversal order for boolean switches.
1965        let bool_fallback = (switch_scalar_ty == ScalarTy::Bool).then(|| {
1966            let target = self.translate_basic_block_id(otherwise);
1967            *target_to_branch
1968                .entry(target)
1969                .or_insert_with(|| branch_targets.push(target))
1970        });
1971
1972        for (bits, target) in targets.iter() {
1973            let Some(kind) = ConstantExprKind::from_bits(&switch_scalar_ty, bits) else {
1974                raise_error!(self, span, "Can't match on type {switch_scalar_ty}")
1975            };
1976            let target = self.translate_basic_block_id(target);
1977            let branch_id = *target_to_branch
1978                .entry(target)
1979                .or_insert_with(|| branch_targets.push(target));
1980            let value = ConstantExpr::new(kind, switch_ty.clone());
1981            switch_branches.push((value, branch_id));
1982        }
1983
1984        let fallback = bool_fallback.unwrap_or_else(|| {
1985            let target = self.translate_basic_block_id(otherwise);
1986            *target_to_branch
1987                .entry(target)
1988                .or_insert_with(|| branch_targets.push(target))
1989        });
1990        let data = SwitchData {
1991            scrutinee: SwitchScrutinee::Value(discr),
1992            branches: switch_branches,
1993            fallback: Some(fallback),
1994        };
1995        Ok((data, branch_targets))
1996    }
1997
1998    /// Translate a function call statement.
1999    /// Note that `body` is the body of the function being translated, not of the
2000    /// function referenced in the function call: we need it in order to translate
2001    /// the blocks we go to after the function call returns.
2002    #[allow(clippy::too_many_arguments)]
2003    fn translate_function_call(
2004        &mut self,
2005        span: Span,
2006        func: &mir::Operand<'tcx>,
2007        args: &[hax::Spanned<mir::Operand<'tcx>>],
2008        destination: &mir::Place<'tcx>,
2009        target: &Option<mir::BasicBlock>,
2010        unwind: &mir::UnwindAction,
2011    ) -> Result<TerminatorKind, Error> {
2012        let tcx = self.tcx;
2013        let op_ty = func.ty(self.local_decls, tcx);
2014        // There are two cases, depending on whether this is a "regular"
2015        // call to a top-level function identified by its id, or if we
2016        // are using a local function pointer (i.e., the operand is a "move").
2017        let lval = self.translate_place(span, destination)?;
2018        let on_unwind = self.translate_unwind_action(span, unwind)?;
2019        // Translate the function operand.
2020        let op = self.translate_operand(span, func)?;
2021        let fn_operand = match op.ty().kind() {
2022            // The type of the value is one of the singleton types that corresponds to each
2023            // function, so we statically know which function is getting called.
2024            TyKind::FnDef(fn_ptr) => {
2025                let fn_ptr = self.erase_region_binder(fn_ptr.clone());
2026                FnOperand::Regular(fn_ptr)
2027            }
2028            // Otherwise, we're calling a function pointer.
2029            TyKind::FnPtr(sig) => {
2030                let regions = RegionArgs::new(
2031                    sig.regions
2032                        .map_ref_indexed(|_, _| self.translate_erased_region()),
2033                );
2034                FnOperand::Dynamic(Box::new(op), regions)
2035            }
2036            _ => raise_error!(
2037                self,
2038                span,
2039                "cannot call a value of type {}",
2040                op.ty().with_ctx(&self.into_fmt())
2041            ),
2042        };
2043        let args = self.translate_arguments(span, args)?;
2044
2045        let safety = match op_ty.kind() {
2046            ty::TyKind::FnDef(def_id, generics) => 'safety_fndef: {
2047                let sig_is_unsafe = tcx.fn_sig(*def_id).skip_binder().safety().is_unsafe();
2048
2049                // Safe `#[target_feature]` functions still get an unsafe signature, but calling them is safe if
2050                // the caller enables the same (or implying) features (safety.unsafe-target-feature-call).
2051                // We also get the inverse: `#[unsafe(force_target_feature)]` functions have a safe signature, but calling
2052                // them is unsafe if the caller does not enable the feature.
2053                let attrs = tcx.codegen_fn_attrs(*def_id);
2054                let caller = self.item_src.def_id().as_real_or_promoted();
2055                let caller_features = caller
2056                    .map(|caller| tcx.typeck_root_def_id(caller))
2057                    .filter(|caller| tcx.def_kind(*caller).has_codegen_attrs())
2058                    .map_or(&[][..], |caller| {
2059                        &tcx.codegen_fn_attrs(caller).target_features[..]
2060                    });
2061                let has_feature =
2062                    tcx.is_target_feature_call_safe(&attrs.target_features, caller_features);
2063                if sig_is_unsafe && attrs.safe_target_features && has_feature {
2064                    break 'safety_fndef CallSafety::Safe;
2065                } else if !has_feature {
2066                    break 'safety_fndef CallSafety::Unsafe;
2067                }
2068
2069                // Explicitly calling a `Drop` method is unsafe.
2070                if let Some(trait_id) = tcx.trait_of_assoc(*def_id)
2071                    && tcx.is_lang_item(trait_id, LangItem::Drop)
2072                {
2073                    break 'safety_fndef CallSafety::Unsafe;
2074                }
2075
2076                // FIXME(#856) In mono mode, trait decls have no methods, so we track the safety of the function here,
2077                // and `transform_dyn_trait_calls` moves it into the signature of the called function pointer.
2078                let mono_dyn_call = self.monomorphize()
2079                    && tcx.trait_of_assoc(*def_id).is_some()
2080                    && generics.skip_binder().type_at(0).is_trait();
2081                if mono_dyn_call {
2082                    break 'safety_fndef if sig_is_unsafe {
2083                        CallSafety::Unsafe
2084                    } else {
2085                        CallSafety::Safe
2086                    };
2087                }
2088
2089                CallSafety::Inherit
2090            }
2091            _ => CallSafety::Inherit,
2092        };
2093
2094        let call = Call {
2095            func: fn_operand,
2096            args,
2097            safety,
2098        };
2099
2100        let target = match target {
2101            Some(target) => self.translate_basic_block_id(*target),
2102            None => {
2103                let abort = Terminator::new(span, TerminatorKind::UndefinedBehavior);
2104                let kind = self.kind;
2105                self.blocks.push(abort.into_block(kind))
2106            }
2107        };
2108
2109        Ok(TerminatorKind::Call {
2110            call,
2111            dest: lval,
2112            target,
2113            on_unwind,
2114        })
2115    }
2116
2117    /// Translate a drop terminator
2118    #[allow(clippy::too_many_arguments)]
2119    fn translate_drop(
2120        &mut self,
2121        span: Span,
2122        place: &mir::Place<'tcx>,
2123        target: &mir::BasicBlock,
2124        unwind: &mir::UnwindAction,
2125    ) -> Result<TerminatorKind, Error> {
2126        let place_ty = place.ty(self.local_decls, self.tcx).ty;
2127        let fn_ptr = self.translate_drop_glue_method_call(span, place_ty)?;
2128        let place = self.translate_place(span, place)?;
2129        let target = self.translate_basic_block_id(*target);
2130        let on_unwind = self.translate_unwind_action(span, unwind)?;
2131
2132        Ok(TerminatorKind::Drop {
2133            kind: self.drop_kind,
2134            place,
2135            fn_ptr,
2136            target,
2137            on_unwind,
2138        })
2139    }
2140
2141    // construct unwind block for the terminators
2142    fn translate_unwind_action(
2143        &mut self,
2144        span: Span,
2145        unwind: &mir::UnwindAction,
2146    ) -> Result<BlockId, Error> {
2147        let unwind_kind = self.kind.further_unwind_kind();
2148        Ok(match unwind {
2149            mir::UnwindAction::Continue => {
2150                assert_eq!(unwind_kind, UnwindKind::Cleanup);
2151                let unwind_continue = Terminator::new(span, TerminatorKind::UnwindResume);
2152                self.blocks.push(unwind_continue.into_block(unwind_kind))
2153            }
2154            mir::UnwindAction::Unreachable => {
2155                let abort = Terminator::new(span, TerminatorKind::UndefinedBehavior);
2156                self.blocks.push(abort.into_block(unwind_kind))
2157            }
2158            mir::UnwindAction::Terminate(reason) => {
2159                let kind = self.translate_unwind_terminate(span, *reason)?;
2160                let abort = Terminator::new(span, kind);
2161                self.blocks.push(abort.into_block(unwind_kind))
2162            }
2163            mir::UnwindAction::Cleanup(bb) => self.translate_basic_block_id(*bb),
2164        })
2165    }
2166
2167    fn translate_assert_kind(
2168        &mut self,
2169        span: Span,
2170        kind: &mir::AssertKind<mir::Operand<'tcx>>,
2171    ) -> Result<BuiltinAssertKind, Error> {
2172        match kind {
2173            mir::AssertKind::BoundsCheck { len, index } => {
2174                let len = self.translate_operand(span, len)?;
2175                let index = self.translate_operand(span, index)?;
2176                Ok(BuiltinAssertKind::BoundsCheck { len, index })
2177            }
2178            mir::AssertKind::Overflow(binop, left, right) => {
2179                let binop = self.translate_binaryop_kind(span, *binop)?;
2180                let left = self.translate_operand(span, left)?;
2181                let right = self.translate_operand(span, right)?;
2182                Ok(BuiltinAssertKind::Overflow(binop, left, right))
2183            }
2184            mir::AssertKind::OverflowNeg(operand) => {
2185                let operand = self.translate_operand(span, operand)?;
2186                Ok(BuiltinAssertKind::OverflowNeg(operand))
2187            }
2188            mir::AssertKind::DivisionByZero(operand) => {
2189                let operand = self.translate_operand(span, operand)?;
2190                Ok(BuiltinAssertKind::DivisionByZero(operand))
2191            }
2192            mir::AssertKind::RemainderByZero(operand) => {
2193                let operand = self.translate_operand(span, operand)?;
2194                Ok(BuiltinAssertKind::RemainderByZero(operand))
2195            }
2196            mir::AssertKind::MisalignedPointerDereference { required, found } => {
2197                let required = self.translate_operand(span, required)?;
2198                let found = self.translate_operand(span, found)?;
2199                Ok(BuiltinAssertKind::MisalignedPointerDereference { required, found })
2200            }
2201            mir::AssertKind::NullPointerDereference => {
2202                Ok(BuiltinAssertKind::NullPointerDereference)
2203            }
2204            mir::AssertKind::NullReferenceConstructed => {
2205                Ok(BuiltinAssertKind::NullReferenceCreated)
2206            }
2207            mir::AssertKind::InvalidEnumConstruction(operand) => {
2208                let operand = self.translate_operand(span, operand)?;
2209                Ok(BuiltinAssertKind::InvalidEnumConstruction(operand))
2210            }
2211            mir::AssertKind::ResumedAfterDrop(..)
2212            | mir::AssertKind::ResumedAfterPanic(..)
2213            | mir::AssertKind::ResumedAfterReturn(..) => {
2214                raise_error!(self, span, "Coroutines are not supported");
2215            }
2216        }
2217    }
2218
2219    fn translate_unwind_terminate(
2220        &mut self,
2221        span: Span,
2222        reason: mir::UnwindTerminateReason,
2223    ) -> Result<TerminatorKind, Error> {
2224        let def_id = self
2225            .tcx
2226            .require_lang_item(reason.lang_item(), rustc_span::DUMMY_SP);
2227        let item = hax::translate_item_ref(&self.hax_state, def_id, ty::GenericArgs::empty());
2228        let fun_ref = self.translate_item(span, &item, TransItemSourceKind::Fun)?;
2229        let reason = match reason {
2230            mir::UnwindTerminateReason::Abi => UnwindTerminateReason::Abi,
2231            mir::UnwindTerminateReason::InCleanup => UnwindTerminateReason::InCleanup,
2232        };
2233        Ok(TerminatorKind::UnwindTerminate(reason, fun_ref))
2234    }
2235
2236    /// Evaluate function arguments in a context, and return the list of computed
2237    /// values.
2238    fn translate_arguments(
2239        &mut self,
2240        span: Span,
2241        args: &[hax::Spanned<mir::Operand<'tcx>>],
2242    ) -> Result<Vec<Operand>, Error> {
2243        let mut t_args: Vec<Operand> = Vec::new();
2244        for arg in args.iter().map(|x| &x.node) {
2245            // Translate
2246            let op = self.translate_operand(span, arg)?;
2247            t_args.push(op);
2248        }
2249        Ok(t_args)
2250    }
2251}
2252
2253impl<'a> IntoFormatter for &'a BodyTransCtx<'_, '_, '_> {
2254    type C = FmtCtx<'a>;
2255    fn into_fmt(self) -> Self::C {
2256        FmtCtx {
2257            local_names: Some(Cow::Owned(compute_local_names(&self.locals))),
2258            ..self.i_ctx.into_fmt()
2259        }
2260    }
2261}