Skip to main content

rustc_middle/mir/
statement.rs

1//! Functionality for statements, operands, places, and things that appear in them.
2
3use std::fmt::Debug;
4use std::ops;
5
6use rustc_data_structures::outline;
7use thin_vec::ThinVec;
8use tracing::instrument;
9
10use super::interpret::GlobalAlloc;
11use super::*;
12use crate::ty::{CoroutineArgsExt, Unnormalized};
13
14///////////////////////////////////////////////////////////////////////////
15// Statements
16
17/// A statement in a basic block, including information about its source code.
18#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Statement<'tcx> {
    #[inline]
    fn clone(&self) -> Statement<'tcx> {
        Statement {
            source_info: ::core::clone::Clone::clone(&self.source_info),
            kind: ::core::clone::Clone::clone(&self.kind),
            debuginfos: ::core::clone::Clone::clone(&self.debuginfos),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for Statement<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Statement {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        debuginfos: ref __binding_2 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for Statement<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                Statement {
                    source_info: ::rustc_serialize::Decodable::decode(__decoder),
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                    debuginfos: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            Statement<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Statement {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        debuginfos: ref __binding_2 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Statement<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        Statement {
                            source_info: __binding_0,
                            kind: __binding_1,
                            debuginfos: __binding_2 } => {
                            Statement {
                                source_info: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                kind: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                debuginfos: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    Statement {
                        source_info: __binding_0,
                        kind: __binding_1,
                        debuginfos: __binding_2 } => {
                        Statement {
                            source_info: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            kind: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            debuginfos: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Statement<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    Statement {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        debuginfos: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
19#[non_exhaustive]
20pub struct Statement<'tcx> {
21    pub source_info: SourceInfo,
22    pub kind: StatementKind<'tcx>,
23    /// Some debuginfos appearing before the primary statement.
24    pub debuginfos: StmtDebugInfos<'tcx>,
25}
26
27impl<'tcx> Statement<'tcx> {
28    /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
29    /// invalidating statement indices in `Location`s.
30    pub fn make_nop(&mut self, drop_debuginfo: bool) {
31        if self.kind == StatementKind::Nop {
32            return;
33        }
34        let replaced_stmt = std::mem::replace(&mut self.kind, StatementKind::Nop);
35        if !drop_debuginfo {
36            let Some(debuginfo) = replaced_stmt.as_debuginfo() else {
37                crate::util::bug::bug_fmt(format_args!("debuginfo is not yet supported."))bug!("debuginfo is not yet supported.")
38            };
39            self.debuginfos.push(debuginfo);
40        }
41    }
42
43    pub fn new(source_info: SourceInfo, kind: StatementKind<'tcx>) -> Self {
44        Statement { source_info, kind, debuginfos: StmtDebugInfos::default() }
45    }
46}
47
48impl<'tcx> StatementKind<'tcx> {
49    /// Returns a simple string representation of a `StatementKind` variant, independent of any
50    /// values it might hold (e.g. `StatementKind::Assign` always returns `"Assign"`).
51    pub const fn name(&self) -> &'static str {
52        match self {
53            StatementKind::Assign(..) => "Assign",
54            StatementKind::FakeRead(..) => "FakeRead",
55            StatementKind::SetDiscriminant { .. } => "SetDiscriminant",
56            StatementKind::StorageLive(..) => "StorageLive",
57            StatementKind::StorageDead(..) => "StorageDead",
58            StatementKind::PlaceMention(..) => "PlaceMention",
59            StatementKind::AscribeUserType(..) => "AscribeUserType",
60            StatementKind::Coverage(..) => "Coverage",
61            StatementKind::Intrinsic(..) => "Intrinsic",
62            StatementKind::ConstEvalCounter => "ConstEvalCounter",
63            StatementKind::Nop => "Nop",
64            StatementKind::BackwardIncompatibleDropHint { .. } => "BackwardIncompatibleDropHint",
65        }
66    }
67    pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
68        match self {
69            StatementKind::Assign(x) => Some(x),
70            _ => None,
71        }
72    }
73
74    pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
75        match self {
76            StatementKind::Assign(x) => Some(x),
77            _ => None,
78        }
79    }
80
81    pub fn as_debuginfo(&self) -> Option<StmtDebugInfo<'tcx>> {
82        match self {
83            StatementKind::Assign((place, Rvalue::Ref(_, _, ref_place)))
84                if let Some(local) = place.as_local() =>
85            {
86                Some(StmtDebugInfo::AssignRef(local, *ref_place))
87            }
88            _ => None,
89        }
90    }
91}
92
93///////////////////////////////////////////////////////////////////////////
94// Places
95
96#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for PlaceTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for PlaceTy<'tcx> {
    #[inline]
    fn clone(&self) -> PlaceTy<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Option<VariantIdx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PlaceTy<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "PlaceTy", "ty",
            &self.ty, "variant_index", &&self.variant_index)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PlaceTy<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        PlaceTy { ty: __binding_0, variant_index: __binding_1 } => {
                            PlaceTy {
                                ty: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                variant_index: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    PlaceTy { ty: __binding_0, variant_index: __binding_1 } => {
                        PlaceTy {
                            ty: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            variant_index: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PlaceTy<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    PlaceTy {
                        ty: ref __binding_0, variant_index: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
97pub struct PlaceTy<'tcx> {
98    pub ty: Ty<'tcx>,
99    /// Downcast to a particular variant of an enum or a coroutine, if included.
100    pub variant_index: Option<VariantIdx>,
101}
102
103// At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
104#[cfg(target_pointer_width = "64")]
105const _: [(); 16] = [(); ::std::mem::size_of::<PlaceTy<'_>>()];rustc_data_structures::static_assert_size!(PlaceTy<'_>, 16);
106
107impl<'tcx> PlaceTy<'tcx> {
108    #[inline]
109    pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
110        PlaceTy { ty, variant_index: None }
111    }
112
113    /// `place_ty.field_ty(tcx, f)` computes the type of a given field.
114    ///
115    /// Most clients of `PlaceTy` can instead just extract the relevant type
116    /// directly from their `PlaceElem`, but some instances of `ProjectionElem<V, T>`
117    /// do not carry a `Ty` for `T`.
118    ///
119    /// Note that the resulting type has not been normalized.
120    x;#[instrument(level = "debug", skip(tcx), ret)]
121    pub fn field_ty(
122        tcx: TyCtxt<'tcx>,
123        self_ty: Ty<'tcx>,
124        variant_idx: Option<VariantIdx>,
125        f: FieldIdx,
126    ) -> Unnormalized<'tcx, Ty<'tcx>> {
127        if let Some(variant_index) = variant_idx {
128            match *self_ty.kind() {
129                ty::Adt(adt_def, args) if adt_def.is_enum() => {
130                    adt_def.variant(variant_index).fields[f].ty(tcx, args)
131                }
132                ty::Coroutine(def_id, args) => {
133                    let mut variants = args.as_coroutine().state_tys(def_id, tcx);
134                    let Some(mut variant) = variants.nth(variant_index.into()) else {
135                        bug!("variant {variant_index:?} of coroutine out of range: {self_ty:?}");
136                    };
137
138                    Unnormalized::new_wip(variant.nth(f.index()).unwrap_or_else(|| {
139                        bug!("field {f:?} out of range of variant: {self_ty:?} {variant_idx:?}")
140                    }))
141                }
142                _ => bug!("can't downcast non-adt non-coroutine type: {self_ty:?}"),
143            }
144        } else {
145            match self_ty.kind() {
146                ty::Adt(adt_def, args) if !adt_def.is_enum() => {
147                    adt_def.non_enum_variant().fields[f].ty(tcx, args)
148                }
149                ty::Closure(_, args) => Unnormalized::dummy(
150                    args.as_closure()
151                        .upvar_tys()
152                        .get(f.index())
153                        .copied()
154                        .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
155                ),
156                ty::CoroutineClosure(_, args) => Unnormalized::dummy(
157                    args.as_coroutine_closure()
158                        .upvar_tys()
159                        .get(f.index())
160                        .copied()
161                        .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
162                ),
163                // Only upvars are accessible without a variant index.
164                ty::Coroutine(_, args) => Unnormalized::dummy(
165                    args.as_coroutine().upvar_tys().get(f.index()).copied().unwrap_or_else(|| {
166                        bug!("field {f:?} out of range of prefixes for {self_ty}")
167                    }),
168                ),
169                ty::Tuple(tys) => Unnormalized::dummy(
170                    tys.get(f.index())
171                        .copied()
172                        .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
173                ),
174                _ => bug!("can't project out of {self_ty:?}"),
175            }
176        }
177    }
178
179    pub fn multi_projection_ty(
180        self,
181        tcx: TyCtxt<'tcx>,
182        elems: &[PlaceElem<'tcx>],
183    ) -> PlaceTy<'tcx> {
184        elems.iter().fold(self, |place_ty, &elem| place_ty.projection_ty(tcx, elem))
185    }
186
187    /// Convenience wrapper around `projection_ty_core` for `PlaceElem`,
188    /// where we can just use the `Ty` that is already stored inline on
189    /// field projection elems.
190    pub fn projection_ty<V: Debug>(
191        self,
192        tcx: TyCtxt<'tcx>,
193        elem: ProjectionElem<V, Ty<'tcx>>,
194    ) -> PlaceTy<'tcx> {
195        self.projection_ty_core(tcx, &elem, |_, _, _, ty| ty, |ty| ty)
196    }
197
198    /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
199    /// projects `place_ty` onto `elem`, returning the appropriate
200    /// `Ty` or downcast variant corresponding to that projection.
201    /// The `handle_field` callback must map a `FieldIdx` to its `Ty`,
202    /// (which should be trivial when `T` = `Ty`).
203    x;#[instrument(level = "debug", skip(tcx, handle_field, handle_opaque_cast_and_subtype), ret)]
204    pub fn projection_ty_core<V, T>(
205        self,
206        tcx: TyCtxt<'tcx>,
207        elem: &ProjectionElem<V, T>,
208        mut handle_field: impl FnMut(Ty<'tcx>, Option<VariantIdx>, FieldIdx, T) -> Ty<'tcx>,
209        mut handle_opaque_cast_and_subtype: impl FnMut(T) -> Ty<'tcx>,
210    ) -> PlaceTy<'tcx>
211    where
212        V: Debug,
213        T: Debug + Copy,
214    {
215        if self.variant_index.is_some() && !matches!(elem, ProjectionElem::Field(..)) {
216            bug!("cannot use non field projection on downcasted place")
217        }
218        match *elem {
219            ProjectionElem::Deref => {
220                let ty = self.ty.builtin_deref(true).unwrap_or_else(|| {
221                    bug!("deref projection of non-dereferenceable ty {:?}", self)
222                });
223                PlaceTy::from_ty(ty)
224            }
225            ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } => {
226                PlaceTy::from_ty(self.ty.builtin_index().unwrap())
227            }
228            ProjectionElem::Subslice { from, to, from_end } => {
229                PlaceTy::from_ty(match self.ty.kind() {
230                    ty::Slice(..) => self.ty,
231                    ty::Array(inner, _) if !from_end => Ty::new_array(tcx, *inner, to - from),
232                    ty::Array(inner, size) if from_end => {
233                        let size = size
234                            .try_to_target_usize(tcx)
235                            .expect("expected subslice projection on fixed-size array");
236                        let len = size - from - to;
237                        Ty::new_array(tcx, *inner, len)
238                    }
239                    _ => bug!("cannot subslice non-array type: `{:?}`", self),
240                })
241            }
242            ProjectionElem::Downcast(_name, index) => {
243                PlaceTy { ty: self.ty, variant_index: Some(index) }
244            }
245            ProjectionElem::Field(f, fty) => {
246                PlaceTy::from_ty(handle_field(self.ty, self.variant_index, f, fty))
247            }
248            ProjectionElem::OpaqueCast(ty) => PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty)),
249
250            // FIXME(unsafe_binders): Rename `handle_opaque_cast_and_subtype` to be more general.
251            ProjectionElem::UnwrapUnsafeBinder(ty) => {
252                PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty))
253            }
254        }
255    }
256}
257
258impl<V, T> ProjectionElem<V, T> {
259    /// Returns `true` if the target of this projection may refer to a different region of memory
260    /// than the base.
261    pub fn is_indirect(&self) -> bool {
262        match self {
263            Self::Deref => true,
264
265            Self::Field(_, _)
266            | Self::Index(_)
267            | Self::OpaqueCast(_)
268            | Self::ConstantIndex { .. }
269            | Self::Subslice { .. }
270            | Self::Downcast(_, _)
271            | Self::UnwrapUnsafeBinder(..) => false,
272        }
273    }
274
275    /// Returns `true` if the target of this projection always refers to the same memory region
276    /// whatever the state of the program.
277    pub fn is_stable_offset(&self) -> bool {
278        match self {
279            Self::Deref | Self::Index(_) => false,
280            Self::Field(_, _)
281            | Self::OpaqueCast(_)
282            | Self::ConstantIndex { .. }
283            | Self::Subslice { .. }
284            | Self::Downcast(_, _)
285            | Self::UnwrapUnsafeBinder(..) => true,
286        }
287    }
288
289    /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
290    pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
291        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::Downcast(_, x) if x == v => true,
    _ => false,
}matches!(*self, Self::Downcast(_, x) if x == v)
292    }
293
294    /// Returns `true` if this is a `Field` projection with the given index.
295    pub fn is_field_to(&self, f: FieldIdx) -> bool {
296        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::Field(x, _) if x == f => true,
    _ => false,
}matches!(*self, Self::Field(x, _) if x == f)
297    }
298
299    /// Returns `true` if this is accepted inside `VarDebugInfoContents::Place`.
300    pub fn can_use_in_debuginfo(&self) -> bool {
301        match self {
302            Self::ConstantIndex { from_end: false, .. }
303            | Self::Deref
304            | Self::Downcast(_, _)
305            | Self::Field(_, _) => true,
306            Self::ConstantIndex { from_end: true, .. }
307            | Self::Index(_)
308            | Self::OpaqueCast(_)
309            | Self::Subslice { .. } => false,
310
311            // FIXME(unsafe_binders): Figure this out.
312            Self::UnwrapUnsafeBinder(..) => false,
313        }
314    }
315
316    /// Returns the `ProjectionKind` associated to this projection.
317    pub fn kind(self) -> ProjectionKind {
318        self.try_map(|_| Some(()), |_| ()).unwrap()
319    }
320
321    /// Apply functions to types and values in this projection and return the result.
322    pub fn try_map<V2, T2>(
323        self,
324        v: impl FnOnce(V) -> Option<V2>,
325        t: impl FnOnce(T) -> T2,
326    ) -> Option<ProjectionElem<V2, T2>> {
327        Some(match self {
328            ProjectionElem::Deref => ProjectionElem::Deref,
329            ProjectionElem::Downcast(name, read_variant) => {
330                ProjectionElem::Downcast(name, read_variant)
331            }
332            ProjectionElem::Field(f, ty) => ProjectionElem::Field(f, t(ty)),
333            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
334                ProjectionElem::ConstantIndex { offset, min_length, from_end }
335            }
336            ProjectionElem::Subslice { from, to, from_end } => {
337                ProjectionElem::Subslice { from, to, from_end }
338            }
339            ProjectionElem::OpaqueCast(ty) => ProjectionElem::OpaqueCast(t(ty)),
340            ProjectionElem::UnwrapUnsafeBinder(ty) => ProjectionElem::UnwrapUnsafeBinder(t(ty)),
341            ProjectionElem::Index(val) => ProjectionElem::Index(v(val)?),
342        })
343    }
344}
345
346/// Alias for projections as they appear in `UserTypeProjection`, where we
347/// need neither the `V` parameter for `Index` nor the `T` for `Field`.
348pub type ProjectionKind = ProjectionElem<(), ()>;
349
350#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PlaceRef<'tcx> {
    #[inline]
    fn clone(&self) -> PlaceRef<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Local>;
        let _: ::core::clone::AssertParamIsClone<&'tcx [PlaceElem<'tcx>]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for PlaceRef<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for PlaceRef<'tcx> {
    #[inline]
    fn eq(&self, other: &PlaceRef<'tcx>) -> bool {
        self.local == other.local && self.projection == other.projection
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for PlaceRef<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Local>;
        let _: ::core::cmp::AssertParamIsEq<&'tcx [PlaceElem<'tcx>]>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for PlaceRef<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.local, state);
        ::core::hash::Hash::hash(&self.projection, state)
    }
}Hash)]
351pub struct PlaceRef<'tcx> {
352    pub local: Local,
353    pub projection: &'tcx [PlaceElem<'tcx>],
354}
355
356// Once we stop implementing `Ord` for `DefId`,
357// this impl will be unnecessary. Until then, we'll
358// leave this impl in place to prevent re-adding a
359// dependency on the `Ord` impl for `DefId`
360impl<'tcx> !PartialOrd for PlaceRef<'tcx> {}
361
362impl<'tcx> Place<'tcx> {
363    // FIXME change this to a const fn by also making List::empty a const fn.
364    pub fn return_place() -> Place<'tcx> {
365        Place { local: RETURN_PLACE, projection: List::empty() }
366    }
367
368    /// Returns `true` if this `Place` contains a `Deref` projection.
369    ///
370    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
371    /// same region of memory as its base.
372    pub fn is_indirect(&self) -> bool {
373        self.projection.iter().any(|elem| elem.is_indirect())
374    }
375
376    /// Returns `true` if the `Place` always refers to the same memory region
377    /// whatever the state of the program.
378    pub fn is_stable_offset(&self) -> bool {
379        self.projection.iter().all(|elem| elem.is_stable_offset())
380    }
381
382    /// Returns `true` if this `Place`'s first projection is `Deref`.
383    ///
384    /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later,
385    /// `Deref` projections can only occur as the first projection. In that case this method
386    /// is equivalent to `is_indirect`, but faster.
387    pub fn is_indirect_first_projection(&self) -> bool {
388        self.as_ref().is_indirect_first_projection()
389    }
390
391    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
392    /// a single deref of a local.
393    #[inline(always)]
394    pub fn local_or_deref_local(&self) -> Option<Local> {
395        self.as_ref().local_or_deref_local()
396    }
397
398    /// If this place represents a local variable like `_X` with no
399    /// projections, return `Some(_X)`.
400    #[inline(always)]
401    pub fn as_local(&self) -> Option<Local> {
402        self.as_ref().as_local()
403    }
404
405    #[inline]
406    pub fn as_ref(&self) -> PlaceRef<'tcx> {
407        PlaceRef { local: self.local, projection: self.projection }
408    }
409
410    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
411    /// its projection and then subsequently more projections are added.
412    /// As a concrete example, given the place a.b.c, this would yield:
413    /// - (a, .b)
414    /// - (a.b, .c)
415    ///
416    /// Given a place without projections, the iterator is empty.
417    #[inline]
418    pub fn iter_projections(
419        self,
420    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
421        self.as_ref().iter_projections()
422    }
423
424    /// Generates a new place by appending `more_projections` to the existing ones
425    /// and interning the result.
426    pub fn project_deeper(self, more_projections: &[PlaceElem<'tcx>], tcx: TyCtxt<'tcx>) -> Self {
427        if more_projections.is_empty() {
428            return self;
429        }
430
431        self.as_ref().project_deeper(more_projections, tcx)
432    }
433
434    /// Return a place that projects to a field of the current place.
435    ///
436    /// The type of the current place must be an ADT.
437    pub fn project_to_field(
438        self,
439        idx: FieldIdx,
440        local_decls: &(impl HasLocalDecls<'tcx> + ?Sized),
441        tcx: TyCtxt<'tcx>,
442    ) -> Self {
443        let ty = self.ty(local_decls, tcx).ty;
444        let ty::Adt(adt, args) = ty.kind() else { {
    ::core::panicking::panic_fmt(format_args!("projecting to field of non-ADT {0}",
            ty));
}panic!("projecting to field of non-ADT {ty}") };
445        let field = &adt.non_enum_variant().fields[idx];
446        let field_ty = field.ty(tcx, args).skip_norm_wip();
447        self.project_deeper(&[ProjectionElem::Field(idx, field_ty)], tcx)
448    }
449
450    pub fn ty_from<D>(
451        local: Local,
452        projection: &[PlaceElem<'tcx>],
453        local_decls: &D,
454        tcx: TyCtxt<'tcx>,
455    ) -> PlaceTy<'tcx>
456    where
457        D: ?Sized + HasLocalDecls<'tcx>,
458    {
459        // If there's a field projection element in `projection`, we *could* skip everything
460        // before that, but on 2026-01-31 a perf experiment showed no benefit from doing so.
461        PlaceTy::from_ty(local_decls.local_decls()[local].ty).multi_projection_ty(tcx, projection)
462    }
463
464    pub fn ty<D: ?Sized>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
465    where
466        D: HasLocalDecls<'tcx>,
467    {
468        Place::ty_from(self.local, self.projection, local_decls, tcx)
469    }
470}
471
472impl From<Local> for Place<'_> {
473    #[inline]
474    fn from(local: Local) -> Self {
475        Place { local, projection: List::empty() }
476    }
477}
478
479impl<'tcx> PlaceRef<'tcx> {
480    pub fn is_prefix_of(&self, other: PlaceRef<'tcx>) -> bool {
481        self.local == other.local
482            && self.projection.len() <= other.projection.len()
483            && self.projection == &other.projection[..self.projection.len()]
484    }
485
486    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
487    /// a single deref of a local.
488    pub fn local_or_deref_local(&self) -> Option<Local> {
489        match *self {
490            PlaceRef { local, projection: [] }
491            | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
492            _ => None,
493        }
494    }
495
496    /// Returns `true` if this `Place` contains a `Deref` projection.
497    ///
498    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
499    /// same region of memory as its base.
500    pub fn is_indirect(&self) -> bool {
501        self.projection.iter().any(|elem| elem.is_indirect())
502    }
503
504    /// Returns `true` if this `Place`'s first projection is `Deref`.
505    ///
506    /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later,
507    /// `Deref` projections can only occur as the first projection. In that case this method
508    /// is equivalent to `is_indirect`, but faster.
509    pub fn is_indirect_first_projection(&self) -> bool {
510        // To make sure this is not accidentally used in wrong mir phase
511        if true {
    if !(self.projection.is_empty() ||
                !self.projection[1..].contains(&PlaceElem::Deref)) {
        ::core::panicking::panic("assertion failed: self.projection.is_empty() ||\n    !self.projection[1..].contains(&PlaceElem::Deref)")
    };
};debug_assert!(
512            self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
513        );
514        self.projection.first() == Some(&PlaceElem::Deref)
515    }
516
517    /// If this place represents a local variable like `_X` with no
518    /// projections, return `Some(_X)`.
519    #[inline]
520    pub fn as_local(&self) -> Option<Local> {
521        match *self {
522            PlaceRef { local, projection: [] } => Some(local),
523            _ => None,
524        }
525    }
526
527    #[inline]
528    pub fn to_place(&self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
529        Place { local: self.local, projection: tcx.mk_place_elems(self.projection) }
530    }
531
532    #[inline]
533    pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
534        if let &[ref proj_base @ .., elem] = self.projection {
535            Some((PlaceRef { local: self.local, projection: proj_base }, elem))
536        } else {
537            None
538        }
539    }
540
541    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
542    /// its projection and then subsequently more projections are added.
543    /// As a concrete example, given the place a.b.c, this would yield:
544    /// - (a, .b)
545    /// - (a.b, .c)
546    ///
547    /// Given a place without projections, the iterator is empty.
548    #[inline]
549    pub fn iter_projections(
550        self,
551    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
552        self.projection.iter().enumerate().map(move |(i, proj)| {
553            let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
554            (base, *proj)
555        })
556    }
557
558    /// Return the place accessed locals that include the base local.
559    pub fn accessed_locals(self) -> impl Iterator<Item = Local> {
560        std::iter::once(self.local).chain(self.projection.iter().filter_map(|proj| match proj {
561            ProjectionElem::Index(local) => Some(*local),
562            ProjectionElem::Deref
563            | ProjectionElem::Field(_, _)
564            | ProjectionElem::ConstantIndex { .. }
565            | ProjectionElem::Subslice { .. }
566            | ProjectionElem::Downcast(_, _)
567            | ProjectionElem::OpaqueCast(_)
568            | ProjectionElem::UnwrapUnsafeBinder(_) => None,
569        }))
570    }
571
572    /// Generates a new place by appending `more_projections` to the existing ones
573    /// and interning the result.
574    pub fn project_deeper(
575        self,
576        more_projections: &[PlaceElem<'tcx>],
577        tcx: TyCtxt<'tcx>,
578    ) -> Place<'tcx> {
579        let mut v: Vec<PlaceElem<'tcx>>;
580
581        let new_projections = if self.projection.is_empty() {
582            more_projections
583        } else {
584            v = Vec::with_capacity(self.projection.len() + more_projections.len());
585            v.extend(self.projection);
586            v.extend(more_projections);
587            &v
588        };
589
590        Place { local: self.local, projection: tcx.mk_place_elems(new_projections) }
591    }
592
593    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
594    where
595        D: ?Sized + HasLocalDecls<'tcx>,
596    {
597        Place::ty_from(self.local, self.projection, local_decls, tcx)
598    }
599}
600
601impl From<Local> for PlaceRef<'_> {
602    #[inline]
603    fn from(local: Local) -> Self {
604        PlaceRef { local, projection: &[] }
605    }
606}
607
608///////////////////////////////////////////////////////////////////////////
609// Operands
610
611impl<'tcx> Operand<'tcx> {
612    /// Convenience helper to make a constant that refers to the fn
613    /// with given `DefId` and args. Since this is used to synthesize
614    /// MIR, assumes `user_ty` is None.
615    pub fn function_handle(
616        tcx: TyCtxt<'tcx>,
617        def_id: DefId,
618        args: &[GenericArg<'tcx>],
619        span: Span,
620    ) -> Self {
621        Operand::zero_sized_constant(
622            tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip(),
623            span,
624        )
625    }
626
627    /// Convenience helper to make a constant that refers to the given `DefId` and args. Since this
628    /// is used to synthesize MIR, assumes `user_ty` is None.
629    pub fn unevaluated_constant(
630        tcx: TyCtxt<'tcx>,
631        def_id: DefId,
632        args: &[GenericArg<'tcx>],
633        span: Span,
634    ) -> Self {
635        let const_ = Const::from_unevaluated(tcx, def_id).instantiate(tcx, args).skip_norm_wip();
636        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
637    }
638
639    /// Convenience helper to make a constant that refers to a zero-sized type.
640    pub fn zero_sized_constant(ty: Ty<'tcx>, span: Span) -> Self {
641        let const_ = Const::Val(ConstValue::ZeroSized, ty);
642        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
643    }
644
645    pub fn is_move(&self) -> bool {
646        #[allow(non_exhaustive_omitted_patterns)] match self {
    Operand::Move(..) => true,
    _ => false,
}matches!(self, Operand::Move(..))
647    }
648
649    /// Convenience helper to make a literal-like constant from a given scalar value.
650    /// Since this is used to synthesize MIR, assumes `user_ty` is None.
651    pub fn const_from_scalar(
652        tcx: TyCtxt<'tcx>,
653        ty: Ty<'tcx>,
654        val: Scalar,
655        span: Span,
656    ) -> Operand<'tcx> {
657        if true {
    if !{
                let typing_env = ty::TypingEnv::fully_monomorphized();
                let type_size =
                    tcx.layout_of(typing_env.as_query_input(ty)).unwrap_or_else(|e|
                                {
                                    ::core::panicking::panic_fmt(format_args!("could not compute layout for {0:?}: {1:?}",
                                            ty, e));
                                }).size;
                let scalar_size =
                    match val {
                        Scalar::Int(int) => int.size(),
                        _ => {
                            ::core::panicking::panic_fmt(format_args!("Invalid scalar type {0:?}",
                                    val));
                        }
                    };
                scalar_size == type_size
            } {
        ::core::panicking::panic("assertion failed: {\n    let typing_env = ty::TypingEnv::fully_monomorphized();\n    let type_size =\n        tcx.layout_of(typing_env.as_query_input(ty)).unwrap_or_else(|e|\n                    panic!(\"could not compute layout for {ty:?}: {e:?}\")).size;\n    let scalar_size =\n        match val {\n            Scalar::Int(int) => int.size(),\n            _ => panic!(\"Invalid scalar type {val:?}\"),\n        };\n    scalar_size == type_size\n}")
    };
};debug_assert!({
658            let typing_env = ty::TypingEnv::fully_monomorphized();
659            let type_size = tcx
660                .layout_of(typing_env.as_query_input(ty))
661                .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}"))
662                .size;
663            let scalar_size = match val {
664                Scalar::Int(int) => int.size(),
665                _ => panic!("Invalid scalar type {val:?}"),
666            };
667            scalar_size == type_size
668        });
669        Operand::Constant(Box::new(ConstOperand {
670            span,
671            user_ty: None,
672            const_: Const::Val(ConstValue::Scalar(val), ty),
673        }))
674    }
675
676    pub fn to_copy(&self) -> Self {
677        match *self {
678            Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => self.clone(),
679            Operand::Move(place) => Operand::Copy(place),
680        }
681    }
682
683    /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
684    /// constant.
685    pub fn place(&self) -> Option<Place<'tcx>> {
686        match self {
687            Operand::Copy(place) | Operand::Move(place) => Some(*place),
688            Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
689        }
690    }
691
692    /// Returns the `ConstOperand` that is the target of this `Operand`, or `None` if this `Operand` is a
693    /// place.
694    pub fn constant(&self) -> Option<&ConstOperand<'tcx>> {
695        match self {
696            Operand::Constant(x) => Some(&**x),
697            Operand::Copy(_) | Operand::Move(_) | Operand::RuntimeChecks(_) => None,
698        }
699    }
700
701    /// Gets the `ty::FnDef` from an operand if it's a constant function item.
702    ///
703    /// While this is unlikely in general, it's the normal case of what you'll
704    /// find as the `func` in a [`TerminatorKind::Call`].
705    pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> {
706        let const_ty = self.constant()?.const_.ty();
707        if let ty::FnDef(def_id, args) = *const_ty.kind() {
708            Some((def_id, args.no_bound_vars().unwrap()))
709        } else {
710            None
711        }
712    }
713
714    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
715    where
716        D: ?Sized + HasLocalDecls<'tcx>,
717    {
718        match self {
719            &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
720            Operand::Constant(c) => c.const_.ty(),
721            Operand::RuntimeChecks(_) => tcx.types.bool,
722        }
723    }
724
725    pub fn span<D>(&self, local_decls: &D) -> Span
726    where
727        D: ?Sized + HasLocalDecls<'tcx>,
728    {
729        match self {
730            &Operand::Copy(ref l) | &Operand::Move(ref l) => {
731                local_decls.local_decls()[l.local].source_info.span
732            }
733            Operand::Constant(c) => c.span,
734            // User code should not contain this operand, so we should not need this span.
735            Operand::RuntimeChecks(_) => DUMMY_SP,
736        }
737    }
738}
739
740impl<'tcx> ConstOperand<'tcx> {
741    pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
742        match self.const_.try_to_scalar() {
743            Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance.alloc_id()) {
744                GlobalAlloc::Static(def_id) => {
745                    if !!tcx.is_thread_local_static(def_id) {
    ::core::panicking::panic("assertion failed: !tcx.is_thread_local_static(def_id)")
};assert!(!tcx.is_thread_local_static(def_id));
746                    Some(def_id)
747                }
748                _ => None,
749            },
750            _ => None,
751        }
752    }
753
754    #[inline]
755    pub fn ty(&self) -> Ty<'tcx> {
756        self.const_.ty()
757    }
758}
759
760///////////////////////////////////////////////////////////////////////////
761// Rvalues
762
763impl<'tcx> Rvalue<'tcx> {
764    /// Returns true if rvalue can be safely removed when the result is unused.
765    #[inline]
766    pub fn is_safe_to_remove(&self) -> bool {
767        match self {
768            // Pointer to int casts may be side-effects due to exposing the provenance.
769            // While the model is undecided, we should be conservative. See
770            // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
771            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => false,
772
773            Rvalue::Use(_, _)
774            | Rvalue::CopyForDeref(_)
775            | Rvalue::Repeat(_, _)
776            | Rvalue::Ref(_, _, _)
777            | Rvalue::Reborrow(_, _, _)
778            | Rvalue::ThreadLocalRef(_)
779            | Rvalue::RawPtr(_, _)
780            | Rvalue::Cast(
781                CastKind::IntToInt
782                | CastKind::FloatToInt
783                | CastKind::FloatToFloat
784                | CastKind::IntToFloat
785                | CastKind::FnPtrToPtr
786                | CastKind::PtrToPtr
787                | CastKind::PointerCoercion(_, _)
788                | CastKind::PointerWithExposedProvenance
789                | CastKind::Transmute
790                | CastKind::BoxDerefTransmute
791                | CastKind::Subtype,
792                _,
793                _,
794            )
795            | Rvalue::BinaryOp(_, _)
796            | Rvalue::UnaryOp(_, _)
797            | Rvalue::Discriminant(_)
798            | Rvalue::Aggregate(_, _)
799            | Rvalue::WrapUnsafeBinder(_, _) => true,
800        }
801    }
802
803    /// Returns true if rvalue is a generic Reborrow coercion (usage of Reborrow or CoerceShared
804    /// trait).
805    pub fn is_generic_reborrow(&self) -> bool {
806        #[allow(non_exhaustive_omitted_patterns)] match self {
    Self::Reborrow(..) => true,
    _ => false,
}matches!(self, Self::Reborrow(..))
807    }
808
809    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
810    where
811        D: ?Sized + HasLocalDecls<'tcx>,
812    {
813        match *self {
814            Rvalue::Use(ref operand, _) => operand.ty(local_decls, tcx),
815            Rvalue::Repeat(ref operand, count) => {
816                Ty::new_array_with_const_len(tcx, operand.ty(local_decls, tcx), count)
817            }
818            Rvalue::ThreadLocalRef(did) => tcx.thread_local_ptr_ty(did),
819            Rvalue::Ref(reg, bk, ref place) => {
820                let place_ty = place.ty(local_decls, tcx).ty;
821                Ty::new_ref(tcx, reg, place_ty, bk.to_mutbl_lossy())
822            }
823            Rvalue::Reborrow(target, _, _) => target,
824            Rvalue::RawPtr(kind, ref place) => {
825                let place_ty = place.ty(local_decls, tcx).ty;
826                Ty::new_ptr(tcx, place_ty, kind.to_mutbl_lossy())
827            }
828            Rvalue::Cast(.., ty) => ty,
829            Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
830                let lhs_ty = lhs.ty(local_decls, tcx);
831                let rhs_ty = rhs.ty(local_decls, tcx);
832                op.ty(tcx, lhs_ty, rhs_ty)
833            }
834            Rvalue::UnaryOp(op, ref operand) => {
835                let arg_ty = operand.ty(local_decls, tcx);
836                op.ty(tcx, arg_ty)
837            }
838            Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
839            Rvalue::Aggregate(ref ak, ref ops) => match **ak {
840                AggregateKind::Array(ty) => Ty::new_array(tcx, ty, ops.len() as u64),
841                AggregateKind::Tuple => {
842                    Ty::new_tup_from_iter(tcx, ops.iter().map(|op| op.ty(local_decls, tcx)))
843                }
844                AggregateKind::Adt(did, _, args, _, _) => {
845                    tcx.type_of(did).instantiate(tcx, args).skip_norm_wip()
846                }
847                AggregateKind::Closure(did, args) => Ty::new_closure(tcx, did, args),
848                AggregateKind::Coroutine(did, args) => Ty::new_coroutine(tcx, did, args),
849                AggregateKind::CoroutineClosure(did, args) => {
850                    Ty::new_coroutine_closure(tcx, did, args)
851                }
852                AggregateKind::RawPtr(ty, mutability) => Ty::new_ptr(tcx, ty, mutability),
853            },
854            Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
855            Rvalue::WrapUnsafeBinder(_, ty) => ty,
856        }
857    }
858}
859
860impl BorrowKind {
861    pub fn mutability(&self) -> Mutability {
862        match *self {
863            BorrowKind::Shared | BorrowKind::Fake(_) => Mutability::Not,
864            BorrowKind::Mut { .. } => Mutability::Mut,
865        }
866    }
867
868    /// Returns whether borrows represented by this kind are allowed to be split into separate
869    /// Reservation and Activation phases.
870    pub fn is_two_phase_borrow(&self) -> bool {
871        match *self {
872            BorrowKind::Shared
873            | BorrowKind::Fake(_)
874            | BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::ClosureCapture } => {
875                false
876            }
877            BorrowKind::Mut { kind: MutBorrowKind::TwoPhaseBorrow } => true,
878        }
879    }
880
881    pub fn to_mutbl_lossy(self) -> hir::Mutability {
882        match self {
883            BorrowKind::Mut { .. } => hir::Mutability::Mut,
884            BorrowKind::Shared => hir::Mutability::Not,
885
886            // We have no type corresponding to a shallow borrow, so use
887            // `&` as an approximation.
888            BorrowKind::Fake(_) => hir::Mutability::Not,
889        }
890    }
891}
892
893impl<'tcx> UnOp {
894    pub fn ty(&self, tcx: TyCtxt<'tcx>, arg_ty: Ty<'tcx>) -> Ty<'tcx> {
895        match self {
896            UnOp::Not | UnOp::Neg => arg_ty,
897            UnOp::PtrMetadata => arg_ty.pointee_metadata_ty_or_projection(tcx),
898        }
899    }
900}
901
902impl<'tcx> BinOp {
903    pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
904        // FIXME: handle SIMD correctly
905        match self {
906            &BinOp::Add
907            | &BinOp::AddUnchecked
908            | &BinOp::Sub
909            | &BinOp::SubUnchecked
910            | &BinOp::Mul
911            | &BinOp::MulUnchecked
912            | &BinOp::Div
913            | &BinOp::Rem
914            | &BinOp::BitXor
915            | &BinOp::BitAnd
916            | &BinOp::BitOr => {
917                // these should be integers or floats of the same size.
918                {
    match (&lhs_ty, &rhs_ty) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(lhs_ty, rhs_ty);
919                lhs_ty
920            }
921            &BinOp::AddWithOverflow | &BinOp::SubWithOverflow | &BinOp::MulWithOverflow => {
922                // these should be integers of the same size.
923                {
    match (&lhs_ty, &rhs_ty) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(lhs_ty, rhs_ty);
924                Ty::new_tup(tcx, &[lhs_ty, tcx.types.bool])
925            }
926            &BinOp::Shl
927            | &BinOp::ShlUnchecked
928            | &BinOp::Shr
929            | &BinOp::ShrUnchecked
930            | &BinOp::Offset => {
931                lhs_ty // lhs_ty can be != rhs_ty
932            }
933            &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
934                tcx.types.bool
935            }
936            &BinOp::Cmp => {
937                // these should be integer-like types of the same size.
938                {
    match (&lhs_ty, &rhs_ty) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(lhs_ty, rhs_ty);
939                tcx.ty_ordering_enum(DUMMY_SP)
940            }
941        }
942    }
943    pub(crate) fn to_hir_binop(self) -> hir::BinOpKind {
944        match self {
945            // HIR `+`/`-`/`*` can map to either of these MIR BinOp, depending
946            // on whether overflow checks are enabled or not.
947            BinOp::Add | BinOp::AddWithOverflow => hir::BinOpKind::Add,
948            BinOp::Sub | BinOp::SubWithOverflow => hir::BinOpKind::Sub,
949            BinOp::Mul | BinOp::MulWithOverflow => hir::BinOpKind::Mul,
950            BinOp::Div => hir::BinOpKind::Div,
951            BinOp::Rem => hir::BinOpKind::Rem,
952            BinOp::BitXor => hir::BinOpKind::BitXor,
953            BinOp::BitAnd => hir::BinOpKind::BitAnd,
954            BinOp::BitOr => hir::BinOpKind::BitOr,
955            BinOp::Shl => hir::BinOpKind::Shl,
956            BinOp::Shr => hir::BinOpKind::Shr,
957            BinOp::Eq => hir::BinOpKind::Eq,
958            BinOp::Ne => hir::BinOpKind::Ne,
959            BinOp::Lt => hir::BinOpKind::Lt,
960            BinOp::Gt => hir::BinOpKind::Gt,
961            BinOp::Le => hir::BinOpKind::Le,
962            BinOp::Ge => hir::BinOpKind::Ge,
963            // We don't have HIR syntax for these.
964            BinOp::Cmp
965            | BinOp::AddUnchecked
966            | BinOp::SubUnchecked
967            | BinOp::MulUnchecked
968            | BinOp::ShlUnchecked
969            | BinOp::ShrUnchecked
970            | BinOp::Offset => {
971                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
972            }
973        }
974    }
975
976    /// If this is a `FooWithOverflow`, return `Some(Foo)`.
977    pub fn overflowing_to_wrapping(self) -> Option<BinOp> {
978        Some(match self {
979            BinOp::AddWithOverflow => BinOp::Add,
980            BinOp::SubWithOverflow => BinOp::Sub,
981            BinOp::MulWithOverflow => BinOp::Mul,
982            _ => return None,
983        })
984    }
985
986    /// Returns whether this is a `FooWithOverflow`
987    pub fn is_overflowing(self) -> bool {
988        self.overflowing_to_wrapping().is_some()
989    }
990
991    /// If this is a `Foo`, return `Some(FooWithOverflow)`.
992    pub fn wrapping_to_overflowing(self) -> Option<BinOp> {
993        Some(match self {
994            BinOp::Add => BinOp::AddWithOverflow,
995            BinOp::Sub => BinOp::SubWithOverflow,
996            BinOp::Mul => BinOp::MulWithOverflow,
997            _ => return None,
998        })
999    }
1000}
1001
1002impl From<Mutability> for RawPtrKind {
1003    fn from(other: Mutability) -> Self {
1004        match other {
1005            Mutability::Mut => RawPtrKind::Mut,
1006            Mutability::Not => RawPtrKind::Const,
1007        }
1008    }
1009}
1010
1011impl RawPtrKind {
1012    pub fn is_fake(self) -> bool {
1013        match self {
1014            RawPtrKind::Mut | RawPtrKind::Const => false,
1015            RawPtrKind::FakeForPtrMetadata => true,
1016        }
1017    }
1018
1019    pub fn to_mutbl_lossy(self) -> Mutability {
1020        match self {
1021            RawPtrKind::Mut => Mutability::Mut,
1022            RawPtrKind::Const => Mutability::Not,
1023
1024            // We have no type corresponding to a fake borrow, so use
1025            // `*const` as an approximation.
1026            RawPtrKind::FakeForPtrMetadata => Mutability::Not,
1027        }
1028    }
1029
1030    pub fn ptr_str(self) -> &'static str {
1031        match self {
1032            RawPtrKind::Mut => "mut",
1033            RawPtrKind::Const => "const",
1034            RawPtrKind::FakeForPtrMetadata => "const (fake)",
1035        }
1036    }
1037}
1038
1039// This collection is almost always empty, so we
1040// use thin representation and optimize all methods
1041// for that by inlining the empty check
1042// and outlining the rest. Note that Option is
1043// technically not needed, because empty ThinVec
1044// points to a static singleton, this version performed
1045// better in our benchmarks
1046#[derive(#[automatically_derived]
impl<'tcx> ::core::default::Default for StmtDebugInfos<'tcx> {
    #[inline]
    fn default() -> StmtDebugInfos<'tcx> {
        StmtDebugInfos(::core::default::Default::default())
    }
}Default, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for StmtDebugInfos<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "StmtDebugInfos",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for StmtDebugInfos<'tcx> {
    #[inline]
    fn clone(&self) -> StmtDebugInfos<'tcx> {
        StmtDebugInfos(::core::clone::Clone::clone(&self.0))
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for StmtDebugInfos<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    StmtDebugInfos(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for StmtDebugInfos<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                StmtDebugInfos(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            StmtDebugInfos<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    StmtDebugInfos(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfos<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        StmtDebugInfos(__binding_0) => {
                            StmtDebugInfos(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    StmtDebugInfos(__binding_0) => {
                        StmtDebugInfos(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfos<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    StmtDebugInfos(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
1047pub struct StmtDebugInfos<'tcx>(Option<ThinVec<StmtDebugInfo<'tcx>>>);
1048
1049impl<'tcx> StmtDebugInfos<'tcx> {
1050    pub fn push(&mut self, debuginfo: StmtDebugInfo<'tcx>) {
1051        self.0.get_or_insert_default().push(debuginfo);
1052    }
1053    #[inline]
1054    pub fn drop_debuginfo(&mut self) {
1055        match &mut self.0 {
1056            None => (),
1057            Some(v) => outline(move || v.clear()),
1058        }
1059    }
1060
1061    #[inline]
1062    pub fn is_empty(&self) -> bool {
1063        match &self.0 {
1064            None => true,
1065            Some(v) => outline(move || v.is_empty()),
1066        }
1067    }
1068    #[inline]
1069    pub fn prepend(&mut self, debuginfos: &mut Self) {
1070        if debuginfos.is_empty() {
1071            return;
1072        };
1073        outline(move || {
1074            debuginfos.append(self);
1075            std::mem::swap(debuginfos, self);
1076        })
1077    }
1078    #[inline]
1079    pub fn append(&mut self, debuginfos: &mut Self) {
1080        if debuginfos.is_empty() {
1081            return;
1082        };
1083        outline(move || self.0.get_or_insert_default().append(debuginfos.0.as_mut().unwrap()));
1084    }
1085    #[inline]
1086    pub fn extend(&mut self, debuginfos: &Self) {
1087        if debuginfos.is_empty() {
1088            return;
1089        };
1090        outline(move || self.0.get_or_insert_default().extend_from_slice(debuginfos.as_slice()))
1091    }
1092
1093    #[inline]
1094    pub fn as_slice(&self) -> &[StmtDebugInfo<'tcx>] {
1095        match &self.0 {
1096            None => &[],
1097            Some(items) => outline(move || items.as_slice()),
1098        }
1099    }
1100
1101    #[inline]
1102    pub fn as_mut_slice(&mut self) -> &mut [StmtDebugInfo<'tcx>] {
1103        match &mut self.0 {
1104            None => &mut [],
1105            Some(items) => outline(move || items.as_mut_slice()),
1106        }
1107    }
1108    #[inline]
1109    pub fn retain_locals(&mut self, locals: &DenseBitSet<Local>) {
1110        match &mut self.0 {
1111            None => (),
1112            Some(items) => outline(move || {
1113                items.retain(|debuginfo| match debuginfo {
1114                    StmtDebugInfo::AssignRef(local, _) | StmtDebugInfo::InvalidAssign(local) => {
1115                        locals.contains(*local)
1116                    }
1117                })
1118            }),
1119        }
1120    }
1121}
1122
1123impl<'tcx> ops::Deref for StmtDebugInfos<'tcx> {
1124    type Target = [StmtDebugInfo<'tcx>];
1125
1126    #[inline]
1127    fn deref(&self) -> &Self::Target {
1128        self.as_slice()
1129    }
1130}
1131
1132impl<'tcx> ops::DerefMut for StmtDebugInfos<'tcx> {
1133    #[inline]
1134    fn deref_mut(&mut self) -> &mut Self::Target {
1135        self.as_mut_slice()
1136    }
1137}
1138
1139#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for StmtDebugInfo<'tcx> {
    #[inline]
    fn clone(&self) -> StmtDebugInfo<'tcx> {
        match self {
            StmtDebugInfo::AssignRef(__self_0, __self_1) =>
                StmtDebugInfo::AssignRef(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            StmtDebugInfo::InvalidAssign(__self_0) =>
                StmtDebugInfo::InvalidAssign(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for StmtDebugInfo<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                            => {
                            0usize
                        }
                        StmtDebugInfo::InvalidAssign(ref __binding_0) => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    StmtDebugInfo::InvalidAssign(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for StmtDebugInfo<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        StmtDebugInfo::AssignRef(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        StmtDebugInfo::InvalidAssign(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `StmtDebugInfo`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
            StmtDebugInfo<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                        => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    StmtDebugInfo::InvalidAssign(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfo<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        StmtDebugInfo::AssignRef(__binding_0, __binding_1) => {
                            StmtDebugInfo::AssignRef(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        StmtDebugInfo::InvalidAssign(__binding_0) => {
                            StmtDebugInfo::InvalidAssign(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    StmtDebugInfo::AssignRef(__binding_0, __binding_1) => {
                        StmtDebugInfo::AssignRef(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    StmtDebugInfo::InvalidAssign(__binding_0) => {
                        StmtDebugInfo::InvalidAssign(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfo<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                        => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    StmtDebugInfo::InvalidAssign(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
1140pub enum StmtDebugInfo<'tcx> {
1141    AssignRef(Local, Place<'tcx>),
1142    InvalidAssign(Local),
1143}