rustc_public/unstable/convert/stable/
mir.rs

1//! Conversion of internal Rust compiler `mir` items to stable ones.
2
3use rustc_middle::mir::mono::MonoItem;
4use rustc_middle::{bug, mir};
5use rustc_public_bridge::context::CompilerCtxt;
6use rustc_public_bridge::{Tables, bridge};
7
8use crate::compiler_interface::BridgeTys;
9use crate::mir::alloc::GlobalAlloc;
10use crate::mir::{ConstOperand, Statement, UserTypeProjection, VarDebugInfoFragment};
11use crate::ty::{Allocation, ConstantKind, MirConst};
12use crate::unstable::Stable;
13use crate::{Error, alloc, opaque};
14
15impl<'tcx> Stable<'tcx> for mir::Body<'tcx> {
16    type T = crate::mir::Body;
17
18    fn stable<'cx>(
19        &self,
20        tables: &mut Tables<'cx, BridgeTys>,
21        cx: &CompilerCtxt<'cx, BridgeTys>,
22    ) -> Self::T {
23        crate::mir::Body::new(
24            self.basic_blocks
25                .iter()
26                .map(|block| crate::mir::BasicBlock {
27                    terminator: block.terminator().stable(tables, cx),
28                    statements: block
29                        .statements
30                        .iter()
31                        .map(|statement| statement.stable(tables, cx))
32                        .collect(),
33                })
34                .collect(),
35            self.local_decls
36                .iter()
37                .map(|decl| crate::mir::LocalDecl {
38                    ty: decl.ty.stable(tables, cx),
39                    span: decl.source_info.span.stable(tables, cx),
40                    mutability: decl.mutability.stable(tables, cx),
41                })
42                .collect(),
43            self.arg_count,
44            self.var_debug_info.iter().map(|info| info.stable(tables, cx)).collect(),
45            self.spread_arg.stable(tables, cx),
46            self.span.stable(tables, cx),
47        )
48    }
49}
50
51impl<'tcx> Stable<'tcx> for mir::VarDebugInfo<'tcx> {
52    type T = crate::mir::VarDebugInfo;
53    fn stable<'cx>(
54        &self,
55        tables: &mut Tables<'cx, BridgeTys>,
56        cx: &CompilerCtxt<'cx, BridgeTys>,
57    ) -> Self::T {
58        crate::mir::VarDebugInfo {
59            name: self.name.to_string(),
60            source_info: self.source_info.stable(tables, cx),
61            composite: self.composite.as_ref().map(|composite| composite.stable(tables, cx)),
62            value: self.value.stable(tables, cx),
63            argument_index: self.argument_index,
64        }
65    }
66}
67
68impl<'tcx> Stable<'tcx> for mir::Statement<'tcx> {
69    type T = crate::mir::Statement;
70    fn stable<'cx>(
71        &self,
72        tables: &mut Tables<'cx, BridgeTys>,
73        cx: &CompilerCtxt<'cx, BridgeTys>,
74    ) -> Self::T {
75        Statement {
76            kind: self.kind.stable(tables, cx),
77            span: self.source_info.span.stable(tables, cx),
78        }
79    }
80}
81
82impl<'tcx> Stable<'tcx> for mir::SourceInfo {
83    type T = crate::mir::SourceInfo;
84    fn stable<'cx>(
85        &self,
86        tables: &mut Tables<'cx, BridgeTys>,
87        cx: &CompilerCtxt<'cx, BridgeTys>,
88    ) -> Self::T {
89        crate::mir::SourceInfo { span: self.span.stable(tables, cx), scope: self.scope.into() }
90    }
91}
92
93impl<'tcx> Stable<'tcx> for mir::VarDebugInfoFragment<'tcx> {
94    type T = crate::mir::VarDebugInfoFragment;
95    fn stable<'cx>(
96        &self,
97        tables: &mut Tables<'cx, BridgeTys>,
98        cx: &CompilerCtxt<'cx, BridgeTys>,
99    ) -> Self::T {
100        VarDebugInfoFragment {
101            ty: self.ty.stable(tables, cx),
102            projection: self.projection.iter().map(|e| e.stable(tables, cx)).collect(),
103        }
104    }
105}
106
107impl<'tcx> Stable<'tcx> for mir::VarDebugInfoContents<'tcx> {
108    type T = crate::mir::VarDebugInfoContents;
109    fn stable<'cx>(
110        &self,
111        tables: &mut Tables<'cx, BridgeTys>,
112        cx: &CompilerCtxt<'cx, BridgeTys>,
113    ) -> Self::T {
114        match self {
115            mir::VarDebugInfoContents::Place(place) => {
116                crate::mir::VarDebugInfoContents::Place(place.stable(tables, cx))
117            }
118            mir::VarDebugInfoContents::Const(const_operand) => {
119                let op = ConstOperand {
120                    span: const_operand.span.stable(tables, cx),
121                    user_ty: const_operand.user_ty.map(|index| index.as_usize()),
122                    const_: const_operand.const_.stable(tables, cx),
123                };
124                crate::mir::VarDebugInfoContents::Const(op)
125            }
126        }
127    }
128}
129
130impl<'tcx> Stable<'tcx> for mir::StatementKind<'tcx> {
131    type T = crate::mir::StatementKind;
132    fn stable<'cx>(
133        &self,
134        tables: &mut Tables<'cx, BridgeTys>,
135        cx: &CompilerCtxt<'cx, BridgeTys>,
136    ) -> Self::T {
137        match self {
138            mir::StatementKind::Assign(assign) => crate::mir::StatementKind::Assign(
139                assign.0.stable(tables, cx),
140                assign.1.stable(tables, cx),
141            ),
142            mir::StatementKind::FakeRead(fake_read_place) => crate::mir::StatementKind::FakeRead(
143                fake_read_place.0.stable(tables, cx),
144                fake_read_place.1.stable(tables, cx),
145            ),
146            mir::StatementKind::SetDiscriminant { place, variant_index } => {
147                crate::mir::StatementKind::SetDiscriminant {
148                    place: place.as_ref().stable(tables, cx),
149                    variant_index: variant_index.stable(tables, cx),
150                }
151            }
152
153            mir::StatementKind::StorageLive(place) => {
154                crate::mir::StatementKind::StorageLive(place.stable(tables, cx))
155            }
156
157            mir::StatementKind::StorageDead(place) => {
158                crate::mir::StatementKind::StorageDead(place.stable(tables, cx))
159            }
160            mir::StatementKind::Retag(retag, place) => {
161                crate::mir::StatementKind::Retag(retag.stable(tables, cx), place.stable(tables, cx))
162            }
163            mir::StatementKind::PlaceMention(place) => {
164                crate::mir::StatementKind::PlaceMention(place.stable(tables, cx))
165            }
166            mir::StatementKind::AscribeUserType(place_projection, variance) => {
167                crate::mir::StatementKind::AscribeUserType {
168                    place: place_projection.as_ref().0.stable(tables, cx),
169                    projections: place_projection.as_ref().1.stable(tables, cx),
170                    variance: variance.stable(tables, cx),
171                }
172            }
173            mir::StatementKind::Coverage(coverage) => {
174                crate::mir::StatementKind::Coverage(opaque(coverage))
175            }
176            mir::StatementKind::Intrinsic(intrinstic) => {
177                crate::mir::StatementKind::Intrinsic(intrinstic.stable(tables, cx))
178            }
179            mir::StatementKind::ConstEvalCounter => crate::mir::StatementKind::ConstEvalCounter,
180            // BackwardIncompatibleDropHint has no semantics, so it is translated to Nop.
181            mir::StatementKind::BackwardIncompatibleDropHint { .. } => {
182                crate::mir::StatementKind::Nop
183            }
184            mir::StatementKind::Nop => crate::mir::StatementKind::Nop,
185        }
186    }
187}
188
189impl<'tcx> Stable<'tcx> for mir::Rvalue<'tcx> {
190    type T = crate::mir::Rvalue;
191    fn stable<'cx>(
192        &self,
193        tables: &mut Tables<'cx, BridgeTys>,
194        cx: &CompilerCtxt<'cx, BridgeTys>,
195    ) -> Self::T {
196        use rustc_middle::mir::Rvalue::*;
197        match self {
198            Use(op) => crate::mir::Rvalue::Use(op.stable(tables, cx)),
199            Repeat(op, len) => {
200                let len = len.stable(tables, cx);
201                crate::mir::Rvalue::Repeat(op.stable(tables, cx), len)
202            }
203            Ref(region, kind, place) => crate::mir::Rvalue::Ref(
204                region.stable(tables, cx),
205                kind.stable(tables, cx),
206                place.stable(tables, cx),
207            ),
208            ThreadLocalRef(def_id) => {
209                crate::mir::Rvalue::ThreadLocalRef(tables.crate_item(*def_id))
210            }
211            RawPtr(mutability, place) => crate::mir::Rvalue::AddressOf(
212                mutability.stable(tables, cx),
213                place.stable(tables, cx),
214            ),
215            Cast(cast_kind, op, ty) => crate::mir::Rvalue::Cast(
216                cast_kind.stable(tables, cx),
217                op.stable(tables, cx),
218                ty.stable(tables, cx),
219            ),
220            BinaryOp(bin_op, ops) => {
221                if let Some(bin_op) = bin_op.overflowing_to_wrapping() {
222                    crate::mir::Rvalue::CheckedBinaryOp(
223                        bin_op.stable(tables, cx),
224                        ops.0.stable(tables, cx),
225                        ops.1.stable(tables, cx),
226                    )
227                } else {
228                    crate::mir::Rvalue::BinaryOp(
229                        bin_op.stable(tables, cx),
230                        ops.0.stable(tables, cx),
231                        ops.1.stable(tables, cx),
232                    )
233                }
234            }
235            UnaryOp(un_op, op) => {
236                crate::mir::Rvalue::UnaryOp(un_op.stable(tables, cx), op.stable(tables, cx))
237            }
238            Discriminant(place) => crate::mir::Rvalue::Discriminant(place.stable(tables, cx)),
239            Aggregate(agg_kind, operands) => {
240                let operands = operands.iter().map(|op| op.stable(tables, cx)).collect();
241                crate::mir::Rvalue::Aggregate(agg_kind.stable(tables, cx), operands)
242            }
243            ShallowInitBox(op, ty) => {
244                crate::mir::Rvalue::ShallowInitBox(op.stable(tables, cx), ty.stable(tables, cx))
245            }
246            CopyForDeref(place) => crate::mir::Rvalue::CopyForDeref(place.stable(tables, cx)),
247            WrapUnsafeBinder(..) => todo!("FIXME(unsafe_binders):"),
248        }
249    }
250}
251
252impl<'tcx> Stable<'tcx> for mir::Mutability {
253    type T = crate::mir::Mutability;
254    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
255        use rustc_hir::Mutability::*;
256        match *self {
257            Not => crate::mir::Mutability::Not,
258            Mut => crate::mir::Mutability::Mut,
259        }
260    }
261}
262
263impl<'tcx> Stable<'tcx> for mir::RawPtrKind {
264    type T = crate::mir::RawPtrKind;
265    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
266        use mir::RawPtrKind::*;
267        match *self {
268            Const => crate::mir::RawPtrKind::Const,
269            Mut => crate::mir::RawPtrKind::Mut,
270            FakeForPtrMetadata => crate::mir::RawPtrKind::FakeForPtrMetadata,
271        }
272    }
273}
274
275impl<'tcx> Stable<'tcx> for mir::BorrowKind {
276    type T = crate::mir::BorrowKind;
277    fn stable<'cx>(
278        &self,
279        tables: &mut Tables<'cx, BridgeTys>,
280        cx: &CompilerCtxt<'cx, BridgeTys>,
281    ) -> Self::T {
282        use rustc_middle::mir::BorrowKind::*;
283        match *self {
284            Shared => crate::mir::BorrowKind::Shared,
285            Fake(kind) => crate::mir::BorrowKind::Fake(kind.stable(tables, cx)),
286            Mut { kind } => crate::mir::BorrowKind::Mut { kind: kind.stable(tables, cx) },
287        }
288    }
289}
290
291impl<'tcx> Stable<'tcx> for mir::MutBorrowKind {
292    type T = crate::mir::MutBorrowKind;
293    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
294        use rustc_middle::mir::MutBorrowKind::*;
295        match *self {
296            Default => crate::mir::MutBorrowKind::Default,
297            TwoPhaseBorrow => crate::mir::MutBorrowKind::TwoPhaseBorrow,
298            ClosureCapture => crate::mir::MutBorrowKind::ClosureCapture,
299        }
300    }
301}
302
303impl<'tcx> Stable<'tcx> for mir::FakeBorrowKind {
304    type T = crate::mir::FakeBorrowKind;
305    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
306        use rustc_middle::mir::FakeBorrowKind::*;
307        match *self {
308            Deep => crate::mir::FakeBorrowKind::Deep,
309            Shallow => crate::mir::FakeBorrowKind::Shallow,
310        }
311    }
312}
313
314impl<'tcx> Stable<'tcx> for mir::RuntimeChecks {
315    type T = crate::mir::RuntimeChecks;
316    fn stable<'cx>(
317        &self,
318        _: &mut Tables<'cx, BridgeTys>,
319        _: &CompilerCtxt<'cx, BridgeTys>,
320    ) -> Self::T {
321        use rustc_middle::mir::RuntimeChecks::*;
322        match self {
323            UbChecks => crate::mir::RuntimeChecks::UbChecks,
324            ContractChecks => crate::mir::RuntimeChecks::ContractChecks,
325            OverflowChecks => crate::mir::RuntimeChecks::OverflowChecks,
326        }
327    }
328}
329
330impl<'tcx> Stable<'tcx> for mir::CastKind {
331    type T = crate::mir::CastKind;
332    fn stable<'cx>(
333        &self,
334        tables: &mut Tables<'cx, BridgeTys>,
335        cx: &CompilerCtxt<'cx, BridgeTys>,
336    ) -> Self::T {
337        use rustc_middle::mir::CastKind::*;
338        match self {
339            PointerExposeProvenance => crate::mir::CastKind::PointerExposeAddress,
340            PointerWithExposedProvenance => crate::mir::CastKind::PointerWithExposedProvenance,
341            PointerCoercion(c, _) => crate::mir::CastKind::PointerCoercion(c.stable(tables, cx)),
342            IntToInt => crate::mir::CastKind::IntToInt,
343            FloatToInt => crate::mir::CastKind::FloatToInt,
344            FloatToFloat => crate::mir::CastKind::FloatToFloat,
345            IntToFloat => crate::mir::CastKind::IntToFloat,
346            PtrToPtr => crate::mir::CastKind::PtrToPtr,
347            FnPtrToPtr => crate::mir::CastKind::FnPtrToPtr,
348            Transmute => crate::mir::CastKind::Transmute,
349            Subtype => crate::mir::CastKind::Subtype,
350        }
351    }
352}
353
354impl<'tcx> Stable<'tcx> for mir::FakeReadCause {
355    type T = crate::mir::FakeReadCause;
356    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
357        use rustc_middle::mir::FakeReadCause::*;
358        match self {
359            ForMatchGuard => crate::mir::FakeReadCause::ForMatchGuard,
360            ForMatchedPlace(local_def_id) => {
361                crate::mir::FakeReadCause::ForMatchedPlace(opaque(local_def_id))
362            }
363            ForGuardBinding => crate::mir::FakeReadCause::ForGuardBinding,
364            ForLet(local_def_id) => crate::mir::FakeReadCause::ForLet(opaque(local_def_id)),
365            ForIndex => crate::mir::FakeReadCause::ForIndex,
366        }
367    }
368}
369
370impl<'tcx> Stable<'tcx> for mir::Operand<'tcx> {
371    type T = crate::mir::Operand;
372    fn stable<'cx>(
373        &self,
374        tables: &mut Tables<'cx, BridgeTys>,
375        cx: &CompilerCtxt<'cx, BridgeTys>,
376    ) -> Self::T {
377        use rustc_middle::mir::Operand::*;
378        match self {
379            Copy(place) => crate::mir::Operand::Copy(place.stable(tables, cx)),
380            Move(place) => crate::mir::Operand::Move(place.stable(tables, cx)),
381            Constant(c) => crate::mir::Operand::Constant(c.stable(tables, cx)),
382            RuntimeChecks(c) => crate::mir::Operand::RuntimeChecks(c.stable(tables, cx)),
383        }
384    }
385}
386
387impl<'tcx> Stable<'tcx> for mir::ConstOperand<'tcx> {
388    type T = crate::mir::ConstOperand;
389
390    fn stable<'cx>(
391        &self,
392        tables: &mut Tables<'cx, BridgeTys>,
393        cx: &CompilerCtxt<'cx, BridgeTys>,
394    ) -> Self::T {
395        crate::mir::ConstOperand {
396            span: self.span.stable(tables, cx),
397            user_ty: self.user_ty.map(|u| u.as_usize()).or(None),
398            const_: self.const_.stable(tables, cx),
399        }
400    }
401}
402
403impl<'tcx> Stable<'tcx> for mir::Place<'tcx> {
404    type T = crate::mir::Place;
405    fn stable<'cx>(
406        &self,
407        tables: &mut Tables<'cx, BridgeTys>,
408        cx: &CompilerCtxt<'cx, BridgeTys>,
409    ) -> Self::T {
410        crate::mir::Place {
411            local: self.local.as_usize(),
412            projection: self.projection.iter().map(|e| e.stable(tables, cx)).collect(),
413        }
414    }
415}
416
417impl<'tcx> Stable<'tcx> for mir::PlaceElem<'tcx> {
418    type T = crate::mir::ProjectionElem;
419    fn stable<'cx>(
420        &self,
421        tables: &mut Tables<'cx, BridgeTys>,
422        cx: &CompilerCtxt<'cx, BridgeTys>,
423    ) -> Self::T {
424        use rustc_middle::mir::ProjectionElem::*;
425        match self {
426            Deref => crate::mir::ProjectionElem::Deref,
427            Field(idx, ty) => {
428                crate::mir::ProjectionElem::Field(idx.stable(tables, cx), ty.stable(tables, cx))
429            }
430            Index(local) => crate::mir::ProjectionElem::Index(local.stable(tables, cx)),
431            ConstantIndex { offset, min_length, from_end } => {
432                crate::mir::ProjectionElem::ConstantIndex {
433                    offset: *offset,
434                    min_length: *min_length,
435                    from_end: *from_end,
436                }
437            }
438            Subslice { from, to, from_end } => {
439                crate::mir::ProjectionElem::Subslice { from: *from, to: *to, from_end: *from_end }
440            }
441            // MIR includes an `Option<Symbol>` argument for `Downcast` that is the name of the
442            // variant, used for printing MIR. However this information should also be accessible
443            // via a lookup using the `VariantIdx`. The `Option<Symbol>` argument is therefore
444            // dropped when converting to Stable MIR. A brief justification for this decision can be
445            // found at https://github.com/rust-lang/rust/pull/117517#issuecomment-1811683486
446            Downcast(_, idx) => crate::mir::ProjectionElem::Downcast(idx.stable(tables, cx)),
447            OpaqueCast(ty) => crate::mir::ProjectionElem::OpaqueCast(ty.stable(tables, cx)),
448            UnwrapUnsafeBinder(..) => todo!("FIXME(unsafe_binders):"),
449        }
450    }
451}
452
453impl<'tcx> Stable<'tcx> for mir::UserTypeProjection {
454    type T = crate::mir::UserTypeProjection;
455
456    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
457        UserTypeProjection { base: self.base.as_usize(), projection: opaque(&self.projs) }
458    }
459}
460
461impl<'tcx> Stable<'tcx> for mir::Local {
462    type T = crate::mir::Local;
463    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
464        self.as_usize()
465    }
466}
467
468impl<'tcx> Stable<'tcx> for mir::RetagKind {
469    type T = crate::mir::RetagKind;
470    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
471        use rustc_middle::mir::RetagKind;
472        match self {
473            RetagKind::FnEntry => crate::mir::RetagKind::FnEntry,
474            RetagKind::TwoPhase => crate::mir::RetagKind::TwoPhase,
475            RetagKind::Raw => crate::mir::RetagKind::Raw,
476            RetagKind::Default => crate::mir::RetagKind::Default,
477        }
478    }
479}
480
481impl<'tcx> Stable<'tcx> for mir::UnwindAction {
482    type T = crate::mir::UnwindAction;
483    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
484        use rustc_middle::mir::UnwindAction;
485        match self {
486            UnwindAction::Continue => crate::mir::UnwindAction::Continue,
487            UnwindAction::Unreachable => crate::mir::UnwindAction::Unreachable,
488            UnwindAction::Terminate(_) => crate::mir::UnwindAction::Terminate,
489            UnwindAction::Cleanup(bb) => crate::mir::UnwindAction::Cleanup(bb.as_usize()),
490        }
491    }
492}
493
494impl<'tcx> Stable<'tcx> for mir::NonDivergingIntrinsic<'tcx> {
495    type T = crate::mir::NonDivergingIntrinsic;
496
497    fn stable<'cx>(
498        &self,
499        tables: &mut Tables<'cx, BridgeTys>,
500        cx: &CompilerCtxt<'cx, BridgeTys>,
501    ) -> Self::T {
502        use rustc_middle::mir::NonDivergingIntrinsic;
503
504        use crate::mir::CopyNonOverlapping;
505        match self {
506            NonDivergingIntrinsic::Assume(op) => {
507                crate::mir::NonDivergingIntrinsic::Assume(op.stable(tables, cx))
508            }
509            NonDivergingIntrinsic::CopyNonOverlapping(copy_non_overlapping) => {
510                crate::mir::NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
511                    src: copy_non_overlapping.src.stable(tables, cx),
512                    dst: copy_non_overlapping.dst.stable(tables, cx),
513                    count: copy_non_overlapping.count.stable(tables, cx),
514                })
515            }
516        }
517    }
518}
519
520impl<'tcx> Stable<'tcx> for mir::AssertMessage<'tcx> {
521    type T = crate::mir::AssertMessage;
522    fn stable<'cx>(
523        &self,
524        tables: &mut Tables<'cx, BridgeTys>,
525        cx: &CompilerCtxt<'cx, BridgeTys>,
526    ) -> Self::T {
527        use rustc_middle::mir::AssertKind;
528        match self {
529            AssertKind::BoundsCheck { len, index } => crate::mir::AssertMessage::BoundsCheck {
530                len: len.stable(tables, cx),
531                index: index.stable(tables, cx),
532            },
533            AssertKind::Overflow(bin_op, op1, op2) => crate::mir::AssertMessage::Overflow(
534                bin_op.stable(tables, cx),
535                op1.stable(tables, cx),
536                op2.stable(tables, cx),
537            ),
538            AssertKind::OverflowNeg(op) => {
539                crate::mir::AssertMessage::OverflowNeg(op.stable(tables, cx))
540            }
541            AssertKind::DivisionByZero(op) => {
542                crate::mir::AssertMessage::DivisionByZero(op.stable(tables, cx))
543            }
544            AssertKind::RemainderByZero(op) => {
545                crate::mir::AssertMessage::RemainderByZero(op.stable(tables, cx))
546            }
547            AssertKind::ResumedAfterReturn(coroutine) => {
548                crate::mir::AssertMessage::ResumedAfterReturn(coroutine.stable(tables, cx))
549            }
550            AssertKind::ResumedAfterPanic(coroutine) => {
551                crate::mir::AssertMessage::ResumedAfterPanic(coroutine.stable(tables, cx))
552            }
553            AssertKind::ResumedAfterDrop(coroutine) => {
554                crate::mir::AssertMessage::ResumedAfterDrop(coroutine.stable(tables, cx))
555            }
556            AssertKind::MisalignedPointerDereference { required, found } => {
557                crate::mir::AssertMessage::MisalignedPointerDereference {
558                    required: required.stable(tables, cx),
559                    found: found.stable(tables, cx),
560                }
561            }
562            AssertKind::NullPointerDereference => crate::mir::AssertMessage::NullPointerDereference,
563            AssertKind::InvalidEnumConstruction(source) => {
564                crate::mir::AssertMessage::InvalidEnumConstruction(source.stable(tables, cx))
565            }
566        }
567    }
568}
569
570impl<'tcx> Stable<'tcx> for mir::BinOp {
571    type T = crate::mir::BinOp;
572    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
573        use rustc_middle::mir::BinOp;
574        match self {
575            BinOp::Add => crate::mir::BinOp::Add,
576            BinOp::AddUnchecked => crate::mir::BinOp::AddUnchecked,
577            BinOp::AddWithOverflow => bug!("AddWithOverflow should have been translated already"),
578            BinOp::Sub => crate::mir::BinOp::Sub,
579            BinOp::SubUnchecked => crate::mir::BinOp::SubUnchecked,
580            BinOp::SubWithOverflow => bug!("AddWithOverflow should have been translated already"),
581            BinOp::Mul => crate::mir::BinOp::Mul,
582            BinOp::MulUnchecked => crate::mir::BinOp::MulUnchecked,
583            BinOp::MulWithOverflow => bug!("AddWithOverflow should have been translated already"),
584            BinOp::Div => crate::mir::BinOp::Div,
585            BinOp::Rem => crate::mir::BinOp::Rem,
586            BinOp::BitXor => crate::mir::BinOp::BitXor,
587            BinOp::BitAnd => crate::mir::BinOp::BitAnd,
588            BinOp::BitOr => crate::mir::BinOp::BitOr,
589            BinOp::Shl => crate::mir::BinOp::Shl,
590            BinOp::ShlUnchecked => crate::mir::BinOp::ShlUnchecked,
591            BinOp::Shr => crate::mir::BinOp::Shr,
592            BinOp::ShrUnchecked => crate::mir::BinOp::ShrUnchecked,
593            BinOp::Eq => crate::mir::BinOp::Eq,
594            BinOp::Lt => crate::mir::BinOp::Lt,
595            BinOp::Le => crate::mir::BinOp::Le,
596            BinOp::Ne => crate::mir::BinOp::Ne,
597            BinOp::Ge => crate::mir::BinOp::Ge,
598            BinOp::Gt => crate::mir::BinOp::Gt,
599            BinOp::Cmp => crate::mir::BinOp::Cmp,
600            BinOp::Offset => crate::mir::BinOp::Offset,
601        }
602    }
603}
604
605impl<'tcx> Stable<'tcx> for mir::UnOp {
606    type T = crate::mir::UnOp;
607    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
608        use rustc_middle::mir::UnOp;
609        match self {
610            UnOp::Not => crate::mir::UnOp::Not,
611            UnOp::Neg => crate::mir::UnOp::Neg,
612            UnOp::PtrMetadata => crate::mir::UnOp::PtrMetadata,
613        }
614    }
615}
616
617impl<'tcx> Stable<'tcx> for mir::AggregateKind<'tcx> {
618    type T = crate::mir::AggregateKind;
619    fn stable<'cx>(
620        &self,
621        tables: &mut Tables<'cx, BridgeTys>,
622        cx: &CompilerCtxt<'cx, BridgeTys>,
623    ) -> Self::T {
624        match self {
625            mir::AggregateKind::Array(ty) => {
626                crate::mir::AggregateKind::Array(ty.stable(tables, cx))
627            }
628            mir::AggregateKind::Tuple => crate::mir::AggregateKind::Tuple,
629            mir::AggregateKind::Adt(def_id, var_idx, generic_arg, user_ty_index, field_idx) => {
630                crate::mir::AggregateKind::Adt(
631                    tables.adt_def(*def_id),
632                    var_idx.stable(tables, cx),
633                    generic_arg.stable(tables, cx),
634                    user_ty_index.map(|idx| idx.index()),
635                    field_idx.map(|idx| idx.index()),
636                )
637            }
638            mir::AggregateKind::Closure(def_id, generic_arg) => crate::mir::AggregateKind::Closure(
639                tables.closure_def(*def_id),
640                generic_arg.stable(tables, cx),
641            ),
642            mir::AggregateKind::Coroutine(def_id, generic_arg) => {
643                crate::mir::AggregateKind::Coroutine(
644                    tables.coroutine_def(*def_id),
645                    generic_arg.stable(tables, cx),
646                )
647            }
648            mir::AggregateKind::CoroutineClosure(def_id, generic_args) => {
649                crate::mir::AggregateKind::CoroutineClosure(
650                    tables.coroutine_closure_def(*def_id),
651                    generic_args.stable(tables, cx),
652                )
653            }
654            mir::AggregateKind::RawPtr(ty, mutability) => crate::mir::AggregateKind::RawPtr(
655                ty.stable(tables, cx),
656                mutability.stable(tables, cx),
657            ),
658        }
659    }
660}
661
662impl<'tcx> Stable<'tcx> for mir::InlineAsmOperand<'tcx> {
663    type T = crate::mir::InlineAsmOperand;
664    fn stable<'cx>(
665        &self,
666        tables: &mut Tables<'cx, BridgeTys>,
667        cx: &CompilerCtxt<'cx, BridgeTys>,
668    ) -> Self::T {
669        use rustc_middle::mir::InlineAsmOperand;
670
671        let (in_value, out_place) = match self {
672            InlineAsmOperand::In { value, .. } => (Some(value.stable(tables, cx)), None),
673            InlineAsmOperand::Out { place, .. } => {
674                (None, place.map(|place| place.stable(tables, cx)))
675            }
676            InlineAsmOperand::InOut { in_value, out_place, .. } => {
677                (Some(in_value.stable(tables, cx)), out_place.map(|place| place.stable(tables, cx)))
678            }
679            InlineAsmOperand::Const { .. }
680            | InlineAsmOperand::SymFn { .. }
681            | InlineAsmOperand::SymStatic { .. }
682            | InlineAsmOperand::Label { .. } => (None, None),
683        };
684
685        crate::mir::InlineAsmOperand { in_value, out_place, raw_rpr: format!("{self:?}") }
686    }
687}
688
689impl<'tcx> Stable<'tcx> for mir::Terminator<'tcx> {
690    type T = crate::mir::Terminator;
691    fn stable<'cx>(
692        &self,
693        tables: &mut Tables<'cx, BridgeTys>,
694        cx: &CompilerCtxt<'cx, BridgeTys>,
695    ) -> Self::T {
696        use crate::mir::Terminator;
697        Terminator {
698            kind: self.kind.stable(tables, cx),
699            span: self.source_info.span.stable(tables, cx),
700        }
701    }
702}
703
704impl<'tcx> Stable<'tcx> for mir::TerminatorKind<'tcx> {
705    type T = crate::mir::TerminatorKind;
706    fn stable<'cx>(
707        &self,
708        tables: &mut Tables<'cx, BridgeTys>,
709        cx: &CompilerCtxt<'cx, BridgeTys>,
710    ) -> Self::T {
711        use crate::mir::TerminatorKind;
712        match self {
713            mir::TerminatorKind::Goto { target } => {
714                TerminatorKind::Goto { target: target.as_usize() }
715            }
716            mir::TerminatorKind::SwitchInt { discr, targets } => TerminatorKind::SwitchInt {
717                discr: discr.stable(tables, cx),
718                targets: {
719                    let branches = targets.iter().map(|(val, target)| (val, target.as_usize()));
720                    crate::mir::SwitchTargets::new(
721                        branches.collect(),
722                        targets.otherwise().as_usize(),
723                    )
724                },
725            },
726            mir::TerminatorKind::UnwindResume => TerminatorKind::Resume,
727            mir::TerminatorKind::UnwindTerminate(_) => TerminatorKind::Abort,
728            mir::TerminatorKind::Return => TerminatorKind::Return,
729            mir::TerminatorKind::Unreachable => TerminatorKind::Unreachable,
730            mir::TerminatorKind::Drop {
731                place,
732                target,
733                unwind,
734                replace: _,
735                drop: _,
736                async_fut: _,
737            } => TerminatorKind::Drop {
738                place: place.stable(tables, cx),
739                target: target.as_usize(),
740                unwind: unwind.stable(tables, cx),
741            },
742            mir::TerminatorKind::Call {
743                func,
744                args,
745                destination,
746                target,
747                unwind,
748                call_source: _,
749                fn_span: _,
750            } => TerminatorKind::Call {
751                func: func.stable(tables, cx),
752                args: args.iter().map(|arg| arg.node.stable(tables, cx)).collect(),
753                destination: destination.stable(tables, cx),
754                target: target.map(|t| t.as_usize()),
755                unwind: unwind.stable(tables, cx),
756            },
757            mir::TerminatorKind::TailCall { func: _, args: _, fn_span: _ } => todo!(),
758            mir::TerminatorKind::Assert { cond, expected, msg, target, unwind } => {
759                TerminatorKind::Assert {
760                    cond: cond.stable(tables, cx),
761                    expected: *expected,
762                    msg: msg.stable(tables, cx),
763                    target: target.as_usize(),
764                    unwind: unwind.stable(tables, cx),
765                }
766            }
767            mir::TerminatorKind::InlineAsm {
768                asm_macro: _,
769                template,
770                operands,
771                options,
772                line_spans,
773                targets,
774                unwind,
775            } => TerminatorKind::InlineAsm {
776                template: format!("{template:?}"),
777                operands: operands.iter().map(|operand| operand.stable(tables, cx)).collect(),
778                options: format!("{options:?}"),
779                line_spans: format!("{line_spans:?}"),
780                // FIXME: Figure out how to do labels in SMIR
781                destination: targets.first().map(|d| d.as_usize()),
782                unwind: unwind.stable(tables, cx),
783            },
784            mir::TerminatorKind::Yield { .. }
785            | mir::TerminatorKind::CoroutineDrop
786            | mir::TerminatorKind::FalseEdge { .. }
787            | mir::TerminatorKind::FalseUnwind { .. } => unreachable!(),
788        }
789    }
790}
791
792impl<'tcx> Stable<'tcx> for mir::interpret::ConstAllocation<'tcx> {
793    type T = Allocation;
794
795    fn stable<'cx>(
796        &self,
797        tables: &mut Tables<'cx, BridgeTys>,
798        cx: &CompilerCtxt<'cx, BridgeTys>,
799    ) -> Self::T {
800        self.inner().stable(tables, cx)
801    }
802}
803
804impl<'tcx> Stable<'tcx> for mir::interpret::Allocation {
805    type T = crate::ty::Allocation;
806
807    fn stable<'cx>(
808        &self,
809        tables: &mut Tables<'cx, BridgeTys>,
810        cx: &CompilerCtxt<'cx, BridgeTys>,
811    ) -> Self::T {
812        use rustc_public_bridge::context::AllocRangeHelpers;
813        alloc::allocation_filter(
814            self,
815            cx.alloc_range(rustc_abi::Size::ZERO, self.size()),
816            tables,
817            cx,
818        )
819    }
820}
821
822impl<'tcx> Stable<'tcx> for mir::interpret::AllocId {
823    type T = crate::mir::alloc::AllocId;
824    fn stable<'cx>(
825        &self,
826        tables: &mut Tables<'cx, BridgeTys>,
827        _: &CompilerCtxt<'cx, BridgeTys>,
828    ) -> Self::T {
829        tables.create_alloc_id(*self)
830    }
831}
832
833impl<'tcx> Stable<'tcx> for mir::interpret::GlobalAlloc<'tcx> {
834    type T = GlobalAlloc;
835
836    fn stable<'cx>(
837        &self,
838        tables: &mut Tables<'cx, BridgeTys>,
839        cx: &CompilerCtxt<'cx, BridgeTys>,
840    ) -> Self::T {
841        match self {
842            mir::interpret::GlobalAlloc::Function { instance, .. } => {
843                GlobalAlloc::Function(instance.stable(tables, cx))
844            }
845            mir::interpret::GlobalAlloc::VTable(ty, dyn_ty) => {
846                // FIXME: Should we record the whole vtable?
847                GlobalAlloc::VTable(ty.stable(tables, cx), dyn_ty.principal().stable(tables, cx))
848            }
849            mir::interpret::GlobalAlloc::Static(def) => {
850                GlobalAlloc::Static(tables.static_def(*def))
851            }
852            mir::interpret::GlobalAlloc::Memory(alloc) => {
853                GlobalAlloc::Memory(alloc.stable(tables, cx))
854            }
855            mir::interpret::GlobalAlloc::TypeId { ty } => {
856                GlobalAlloc::TypeId { ty: ty.stable(tables, cx) }
857            }
858        }
859    }
860}
861
862impl<'tcx> Stable<'tcx> for rustc_middle::mir::Const<'tcx> {
863    type T = crate::ty::MirConst;
864
865    fn stable<'cx>(
866        &self,
867        tables: &mut Tables<'cx, BridgeTys>,
868        cx: &CompilerCtxt<'cx, BridgeTys>,
869    ) -> Self::T {
870        let id = tables.intern_mir_const(cx.lift(*self).unwrap());
871        match *self {
872            mir::Const::Ty(ty, c) => MirConst::new(
873                crate::ty::ConstantKind::Ty(c.stable(tables, cx)),
874                ty.stable(tables, cx),
875                id,
876            ),
877            mir::Const::Unevaluated(unev_const, ty) => {
878                let kind = crate::ty::ConstantKind::Unevaluated(crate::ty::UnevaluatedConst {
879                    def: tables.const_def(unev_const.def),
880                    args: unev_const.args.stable(tables, cx),
881                    promoted: unev_const.promoted.map(|u| u.as_u32()),
882                });
883                let ty = ty.stable(tables, cx);
884                MirConst::new(kind, ty, id)
885            }
886            mir::Const::Val(mir::ConstValue::ZeroSized, ty) => {
887                let ty = ty.stable(tables, cx);
888                MirConst::new(ConstantKind::ZeroSized, ty, id)
889            }
890            mir::Const::Val(val, ty) => {
891                let ty = cx.lift(ty).unwrap();
892                let val = cx.lift(val).unwrap();
893                let kind = ConstantKind::Allocated(alloc::new_allocation(ty, val, tables, cx));
894                let ty = ty.stable(tables, cx);
895                MirConst::new(kind, ty, id)
896            }
897        }
898    }
899}
900
901impl<'tcx> Stable<'tcx> for mir::interpret::ErrorHandled {
902    type T = Error;
903
904    fn stable(&self, _: &mut Tables<'_, BridgeTys>, _: &CompilerCtxt<'_, BridgeTys>) -> Self::T {
905        bridge::Error::new(format!("{self:?}"))
906    }
907}
908
909impl<'tcx> Stable<'tcx> for MonoItem<'tcx> {
910    type T = crate::mir::mono::MonoItem;
911
912    fn stable<'cx>(
913        &self,
914        tables: &mut Tables<'cx, BridgeTys>,
915        cx: &CompilerCtxt<'cx, BridgeTys>,
916    ) -> Self::T {
917        use crate::mir::mono::MonoItem as StableMonoItem;
918        match self {
919            MonoItem::Fn(instance) => StableMonoItem::Fn(instance.stable(tables, cx)),
920            MonoItem::Static(def_id) => StableMonoItem::Static(tables.static_def(*def_id)),
921            MonoItem::GlobalAsm(item_id) => StableMonoItem::GlobalAsm(opaque(item_id)),
922        }
923    }
924}