Skip to main content

rustc_middle/mir/
statement.rs

1//! Functionality for statements, operands, places, and things that appear in them.
2
3use std::ops;
4
5use tracing::{debug, instrument};
6
7use super::interpret::GlobalAlloc;
8use super::*;
9use crate::ty::CoroutineArgsExt;
10
11///////////////////////////////////////////////////////////////////////////
12// Statements
13
14/// A statement in a basic block, including information about its source code.
15#[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_hasher::StableHash for
            Statement<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hasher::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::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)]
16#[non_exhaustive]
17pub struct Statement<'tcx> {
18    pub source_info: SourceInfo,
19    pub kind: StatementKind<'tcx>,
20    /// Some debuginfos appearing before the primary statement.
21    pub debuginfos: StmtDebugInfos<'tcx>,
22}
23
24impl<'tcx> Statement<'tcx> {
25    /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
26    /// invalidating statement indices in `Location`s.
27    pub fn make_nop(&mut self, drop_debuginfo: bool) {
28        if self.kind == StatementKind::Nop {
29            return;
30        }
31        let replaced_stmt = std::mem::replace(&mut self.kind, StatementKind::Nop);
32        if !drop_debuginfo {
33            let Some(debuginfo) = replaced_stmt.as_debuginfo() else {
34                crate::util::bug::bug_fmt(format_args!("debuginfo is not yet supported."))bug!("debuginfo is not yet supported.")
35            };
36            self.debuginfos.push(debuginfo);
37        }
38    }
39
40    pub fn new(source_info: SourceInfo, kind: StatementKind<'tcx>) -> Self {
41        Statement { source_info, kind, debuginfos: StmtDebugInfos::default() }
42    }
43}
44
45impl<'tcx> StatementKind<'tcx> {
46    /// Returns a simple string representation of a `StatementKind` variant, independent of any
47    /// values it might hold (e.g. `StatementKind::Assign` always returns `"Assign"`).
48    pub const fn name(&self) -> &'static str {
49        match self {
50            StatementKind::Assign(..) => "Assign",
51            StatementKind::FakeRead(..) => "FakeRead",
52            StatementKind::SetDiscriminant { .. } => "SetDiscriminant",
53            StatementKind::StorageLive(..) => "StorageLive",
54            StatementKind::StorageDead(..) => "StorageDead",
55            StatementKind::PlaceMention(..) => "PlaceMention",
56            StatementKind::AscribeUserType(..) => "AscribeUserType",
57            StatementKind::Coverage(..) => "Coverage",
58            StatementKind::Intrinsic(..) => "Intrinsic",
59            StatementKind::ConstEvalCounter => "ConstEvalCounter",
60            StatementKind::Nop => "Nop",
61            StatementKind::BackwardIncompatibleDropHint { .. } => "BackwardIncompatibleDropHint",
62        }
63    }
64    pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
65        match self {
66            StatementKind::Assign(x) => Some(x),
67            _ => None,
68        }
69    }
70
71    pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
72        match self {
73            StatementKind::Assign(x) => Some(x),
74            _ => None,
75        }
76    }
77
78    pub fn as_debuginfo(&self) -> Option<StmtDebugInfo<'tcx>> {
79        match self {
80            StatementKind::Assign(box (place, Rvalue::Ref(_, _, ref_place)))
81                if let Some(local) = place.as_local() =>
82            {
83                Some(StmtDebugInfo::AssignRef(local, *ref_place))
84            }
85            _ => None,
86        }
87    }
88}
89
90///////////////////////////////////////////////////////////////////////////
91// Places
92
93#[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)]
94pub struct PlaceTy<'tcx> {
95    pub ty: Ty<'tcx>,
96    /// Downcast to a particular variant of an enum or a coroutine, if included.
97    pub variant_index: Option<VariantIdx>,
98}
99
100// At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
101#[cfg(target_pointer_width = "64")]
102const _: [(); 16] = [(); ::std::mem::size_of::<PlaceTy<'_>>()];rustc_data_structures::static_assert_size!(PlaceTy<'_>, 16);
103
104impl<'tcx> PlaceTy<'tcx> {
105    #[inline]
106    pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
107        PlaceTy { ty, variant_index: None }
108    }
109
110    /// `place_ty.field_ty(tcx, f)` computes the type of a given field.
111    ///
112    /// Most clients of `PlaceTy` can instead just extract the relevant type
113    /// directly from their `PlaceElem`, but some instances of `ProjectionElem<V, T>`
114    /// do not carry a `Ty` for `T`.
115    ///
116    /// Note that the resulting type has not been normalized.
117    x;#[instrument(level = "debug", skip(tcx), ret)]
118    pub fn field_ty(
119        tcx: TyCtxt<'tcx>,
120        self_ty: Ty<'tcx>,
121        variant_idx: Option<VariantIdx>,
122        f: FieldIdx,
123    ) -> Ty<'tcx> {
124        if let Some(variant_index) = variant_idx {
125            match *self_ty.kind() {
126                ty::Adt(adt_def, args) if adt_def.is_enum() => {
127                    adt_def.variant(variant_index).fields[f].ty(tcx, args)
128                }
129                ty::Coroutine(def_id, args) => {
130                    let mut variants = args.as_coroutine().state_tys(def_id, tcx);
131                    let Some(mut variant) = variants.nth(variant_index.into()) else {
132                        bug!("variant {variant_index:?} of coroutine out of range: {self_ty:?}");
133                    };
134
135                    variant.nth(f.index()).unwrap_or_else(|| {
136                        bug!("field {f:?} out of range of variant: {self_ty:?} {variant_idx:?}")
137                    })
138                }
139                _ => bug!("can't downcast non-adt non-coroutine type: {self_ty:?}"),
140            }
141        } else {
142            match self_ty.kind() {
143                ty::Adt(adt_def, args) if !adt_def.is_enum() => {
144                    adt_def.non_enum_variant().fields[f].ty(tcx, args)
145                }
146                ty::Closure(_, args) => args
147                    .as_closure()
148                    .upvar_tys()
149                    .get(f.index())
150                    .copied()
151                    .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
152                ty::CoroutineClosure(_, args) => args
153                    .as_coroutine_closure()
154                    .upvar_tys()
155                    .get(f.index())
156                    .copied()
157                    .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
158                // Only prefix fields (upvars and current state) are
159                // accessible without a variant index.
160                ty::Coroutine(_, args) => {
161                    args.as_coroutine().prefix_tys().get(f.index()).copied().unwrap_or_else(|| {
162                        bug!("field {f:?} out of range of prefixes for {self_ty}")
163                    })
164                }
165                ty::Tuple(tys) => tys
166                    .get(f.index())
167                    .copied()
168                    .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
169                _ => bug!("can't project out of {self_ty:?}"),
170            }
171        }
172    }
173
174    pub fn multi_projection_ty(
175        self,
176        tcx: TyCtxt<'tcx>,
177        elems: &[PlaceElem<'tcx>],
178    ) -> PlaceTy<'tcx> {
179        elems.iter().fold(self, |place_ty, &elem| place_ty.projection_ty(tcx, elem))
180    }
181
182    /// Convenience wrapper around `projection_ty_core` for `PlaceElem`,
183    /// where we can just use the `Ty` that is already stored inline on
184    /// field projection elems.
185    pub fn projection_ty<V: ::std::fmt::Debug>(
186        self,
187        tcx: TyCtxt<'tcx>,
188        elem: ProjectionElem<V, Ty<'tcx>>,
189    ) -> PlaceTy<'tcx> {
190        self.projection_ty_core(tcx, &elem, |ty| ty, |_, _, _, ty| ty, |ty| ty)
191    }
192
193    /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
194    /// projects `place_ty` onto `elem`, returning the appropriate
195    /// `Ty` or downcast variant corresponding to that projection.
196    /// The `handle_field` callback must map a `FieldIdx` to its `Ty`,
197    /// (which should be trivial when `T` = `Ty`).
198    pub fn projection_ty_core<V, T>(
199        self,
200        tcx: TyCtxt<'tcx>,
201        elem: &ProjectionElem<V, T>,
202        mut structurally_normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
203        mut handle_field: impl FnMut(Ty<'tcx>, Option<VariantIdx>, FieldIdx, T) -> Ty<'tcx>,
204        mut handle_opaque_cast_and_subtype: impl FnMut(T) -> Ty<'tcx>,
205    ) -> PlaceTy<'tcx>
206    where
207        V: ::std::fmt::Debug,
208        T: ::std::fmt::Debug + Copy,
209    {
210        if self.variant_index.is_some() && !#[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::Field(..) => true,
    _ => false,
}matches!(elem, ProjectionElem::Field(..)) {
211            crate::util::bug::bug_fmt(format_args!("cannot use non field projection on downcasted place"))bug!("cannot use non field projection on downcasted place")
212        }
213        let answer = match *elem {
214            ProjectionElem::Deref => {
215                let ty = structurally_normalize(self.ty).builtin_deref(true).unwrap_or_else(|| {
216                    crate::util::bug::bug_fmt(format_args!("deref projection of non-dereferenceable ty {0:?}",
        self))bug!("deref projection of non-dereferenceable ty {:?}", self)
217                });
218                PlaceTy::from_ty(ty)
219            }
220            ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } => {
221                PlaceTy::from_ty(structurally_normalize(self.ty).builtin_index().unwrap())
222            }
223            ProjectionElem::Subslice { from, to, from_end } => {
224                PlaceTy::from_ty(match structurally_normalize(self.ty).kind() {
225                    ty::Slice(..) => self.ty,
226                    ty::Array(inner, _) if !from_end => Ty::new_array(tcx, *inner, to - from),
227                    ty::Array(inner, size) if from_end => {
228                        let size = size
229                            .try_to_target_usize(tcx)
230                            .expect("expected subslice projection on fixed-size array");
231                        let len = size - from - to;
232                        Ty::new_array(tcx, *inner, len)
233                    }
234                    _ => crate::util::bug::bug_fmt(format_args!("cannot subslice non-array type: `{0:?}`",
        self))bug!("cannot subslice non-array type: `{:?}`", self),
235                })
236            }
237            ProjectionElem::Downcast(_name, index) => {
238                PlaceTy { ty: self.ty, variant_index: Some(index) }
239            }
240            ProjectionElem::Field(f, fty) => PlaceTy::from_ty(handle_field(
241                structurally_normalize(self.ty),
242                self.variant_index,
243                f,
244                fty,
245            )),
246            ProjectionElem::OpaqueCast(ty) => PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty)),
247
248            // FIXME(unsafe_binders): Rename `handle_opaque_cast_and_subtype` to be more general.
249            ProjectionElem::UnwrapUnsafeBinder(ty) => {
250                PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty))
251            }
252        };
253        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/statement.rs:253",
                        "rustc_middle::mir::statement", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/statement.rs"),
                        ::tracing_core::__macro_support::Option::Some(253u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::statement"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("projection_ty self: {0:?} elem: {1:?} yields: {2:?}",
                                                    self, elem, answer) as &dyn Value))])
            });
    } else { ; }
};debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
254        answer
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>,
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);
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: impl IntoIterator<Item = GenericArg<'tcx>>,
619        span: Span,
620    ) -> Self {
621        let ty = Ty::new_fn_def(tcx, def_id, args);
622        Operand::Constant(Box::new(ConstOperand {
623            span,
624            user_ty: None,
625            const_: Const::Val(ConstValue::ZeroSized, ty),
626        }))
627    }
628
629    /// Convenience helper to make a constant that refers to the given `DefId` and args. Since this
630    /// is used to synthesize MIR, assumes `user_ty` is None.
631    pub fn unevaluated_constant(
632        tcx: TyCtxt<'tcx>,
633        def_id: DefId,
634        args: &[GenericArg<'tcx>],
635        span: Span,
636    ) -> Self {
637        let const_ = Const::from_unevaluated(tcx, def_id).instantiate(tcx, args).skip_norm_wip();
638        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
639    }
640
641    pub fn is_move(&self) -> bool {
642        #[allow(non_exhaustive_omitted_patterns)] match self {
    Operand::Move(..) => true,
    _ => false,
}matches!(self, Operand::Move(..))
643    }
644
645    /// Convenience helper to make a literal-like constant from a given scalar value.
646    /// Since this is used to synthesize MIR, assumes `user_ty` is None.
647    pub fn const_from_scalar(
648        tcx: TyCtxt<'tcx>,
649        ty: Ty<'tcx>,
650        val: Scalar,
651        span: Span,
652    ) -> Operand<'tcx> {
653        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!({
654            let typing_env = ty::TypingEnv::fully_monomorphized();
655            let type_size = tcx
656                .layout_of(typing_env.as_query_input(ty))
657                .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}"))
658                .size;
659            let scalar_size = match val {
660                Scalar::Int(int) => int.size(),
661                _ => panic!("Invalid scalar type {val:?}"),
662            };
663            scalar_size == type_size
664        });
665        Operand::Constant(Box::new(ConstOperand {
666            span,
667            user_ty: None,
668            const_: Const::Val(ConstValue::Scalar(val), ty),
669        }))
670    }
671
672    pub fn to_copy(&self) -> Self {
673        match *self {
674            Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => self.clone(),
675            Operand::Move(place) => Operand::Copy(place),
676        }
677    }
678
679    /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
680    /// constant.
681    pub fn place(&self) -> Option<Place<'tcx>> {
682        match self {
683            Operand::Copy(place) | Operand::Move(place) => Some(*place),
684            Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
685        }
686    }
687
688    /// Returns the `ConstOperand` that is the target of this `Operand`, or `None` if this `Operand` is a
689    /// place.
690    pub fn constant(&self) -> Option<&ConstOperand<'tcx>> {
691        match self {
692            Operand::Constant(x) => Some(&**x),
693            Operand::Copy(_) | Operand::Move(_) | Operand::RuntimeChecks(_) => None,
694        }
695    }
696
697    /// Gets the `ty::FnDef` from an operand if it's a constant function item.
698    ///
699    /// While this is unlikely in general, it's the normal case of what you'll
700    /// find as the `func` in a [`TerminatorKind::Call`].
701    pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> {
702        let const_ty = self.constant()?.const_.ty();
703        if let ty::FnDef(def_id, args) = *const_ty.kind() { Some((def_id, args)) } else { None }
704    }
705
706    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
707    where
708        D: ?Sized + HasLocalDecls<'tcx>,
709    {
710        match self {
711            &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
712            Operand::Constant(c) => c.const_.ty(),
713            Operand::RuntimeChecks(_) => tcx.types.bool,
714        }
715    }
716
717    pub fn span<D>(&self, local_decls: &D) -> Span
718    where
719        D: ?Sized + HasLocalDecls<'tcx>,
720    {
721        match self {
722            &Operand::Copy(ref l) | &Operand::Move(ref l) => {
723                local_decls.local_decls()[l.local].source_info.span
724            }
725            Operand::Constant(c) => c.span,
726            // User code should not contain this operand, so we should not need this span.
727            Operand::RuntimeChecks(_) => DUMMY_SP,
728        }
729    }
730}
731
732impl<'tcx> ConstOperand<'tcx> {
733    pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
734        match self.const_.try_to_scalar() {
735            Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance.alloc_id()) {
736                GlobalAlloc::Static(def_id) => {
737                    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));
738                    Some(def_id)
739                }
740                _ => None,
741            },
742            _ => None,
743        }
744    }
745
746    #[inline]
747    pub fn ty(&self) -> Ty<'tcx> {
748        self.const_.ty()
749    }
750}
751
752///////////////////////////////////////////////////////////////////////////
753// Rvalues
754
755impl<'tcx> Rvalue<'tcx> {
756    /// Returns true if rvalue can be safely removed when the result is unused.
757    #[inline]
758    pub fn is_safe_to_remove(&self) -> bool {
759        match self {
760            // Pointer to int casts may be side-effects due to exposing the provenance.
761            // While the model is undecided, we should be conservative. See
762            // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
763            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => false,
764
765            Rvalue::Use(_, _)
766            | Rvalue::CopyForDeref(_)
767            | Rvalue::Repeat(_, _)
768            | Rvalue::Ref(_, _, _)
769            | Rvalue::ThreadLocalRef(_)
770            | Rvalue::RawPtr(_, _)
771            | Rvalue::Cast(
772                CastKind::IntToInt
773                | CastKind::FloatToInt
774                | CastKind::FloatToFloat
775                | CastKind::IntToFloat
776                | CastKind::FnPtrToPtr
777                | CastKind::PtrToPtr
778                | CastKind::PointerCoercion(_, _)
779                | CastKind::PointerWithExposedProvenance
780                | CastKind::Transmute
781                | CastKind::Subtype,
782                _,
783                _,
784            )
785            | Rvalue::BinaryOp(_, _)
786            | Rvalue::UnaryOp(_, _)
787            | Rvalue::Discriminant(_)
788            | Rvalue::Aggregate(_, _)
789            | Rvalue::WrapUnsafeBinder(_, _) => true,
790        }
791    }
792
793    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
794    where
795        D: ?Sized + HasLocalDecls<'tcx>,
796    {
797        match *self {
798            Rvalue::Use(ref operand, _) => operand.ty(local_decls, tcx),
799            Rvalue::Repeat(ref operand, count) => {
800                Ty::new_array_with_const_len(tcx, operand.ty(local_decls, tcx), count)
801            }
802            Rvalue::ThreadLocalRef(did) => tcx.thread_local_ptr_ty(did),
803            Rvalue::Ref(reg, bk, ref place) => {
804                let place_ty = place.ty(local_decls, tcx).ty;
805                Ty::new_ref(tcx, reg, place_ty, bk.to_mutbl_lossy())
806            }
807            Rvalue::RawPtr(kind, ref place) => {
808                let place_ty = place.ty(local_decls, tcx).ty;
809                Ty::new_ptr(tcx, place_ty, kind.to_mutbl_lossy())
810            }
811            Rvalue::Cast(.., ty) => ty,
812            Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
813                let lhs_ty = lhs.ty(local_decls, tcx);
814                let rhs_ty = rhs.ty(local_decls, tcx);
815                op.ty(tcx, lhs_ty, rhs_ty)
816            }
817            Rvalue::UnaryOp(op, ref operand) => {
818                let arg_ty = operand.ty(local_decls, tcx);
819                op.ty(tcx, arg_ty)
820            }
821            Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
822            Rvalue::Aggregate(ref ak, ref ops) => match **ak {
823                AggregateKind::Array(ty) => Ty::new_array(tcx, ty, ops.len() as u64),
824                AggregateKind::Tuple => {
825                    Ty::new_tup_from_iter(tcx, ops.iter().map(|op| op.ty(local_decls, tcx)))
826                }
827                AggregateKind::Adt(did, _, args, _, _) => {
828                    tcx.type_of(did).instantiate(tcx, args).skip_norm_wip()
829                }
830                AggregateKind::Closure(did, args) => Ty::new_closure(tcx, did, args),
831                AggregateKind::Coroutine(did, args) => Ty::new_coroutine(tcx, did, args),
832                AggregateKind::CoroutineClosure(did, args) => {
833                    Ty::new_coroutine_closure(tcx, did, args)
834                }
835                AggregateKind::RawPtr(ty, mutability) => Ty::new_ptr(tcx, ty, mutability),
836            },
837            Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
838            Rvalue::WrapUnsafeBinder(_, ty) => ty,
839        }
840    }
841}
842
843impl BorrowKind {
844    pub fn mutability(&self) -> Mutability {
845        match *self {
846            BorrowKind::Shared | BorrowKind::Fake(_) => Mutability::Not,
847            BorrowKind::Mut { .. } => Mutability::Mut,
848        }
849    }
850
851    /// Returns whether borrows represented by this kind are allowed to be split into separate
852    /// Reservation and Activation phases.
853    pub fn is_two_phase_borrow(&self) -> bool {
854        match *self {
855            BorrowKind::Shared
856            | BorrowKind::Fake(_)
857            | BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::ClosureCapture } => {
858                false
859            }
860            BorrowKind::Mut { kind: MutBorrowKind::TwoPhaseBorrow } => true,
861        }
862    }
863
864    pub fn to_mutbl_lossy(self) -> hir::Mutability {
865        match self {
866            BorrowKind::Mut { .. } => hir::Mutability::Mut,
867            BorrowKind::Shared => hir::Mutability::Not,
868
869            // We have no type corresponding to a shallow borrow, so use
870            // `&` as an approximation.
871            BorrowKind::Fake(_) => hir::Mutability::Not,
872        }
873    }
874}
875
876impl<'tcx> UnOp {
877    pub fn ty(&self, tcx: TyCtxt<'tcx>, arg_ty: Ty<'tcx>) -> Ty<'tcx> {
878        match self {
879            UnOp::Not | UnOp::Neg => arg_ty,
880            UnOp::PtrMetadata => arg_ty.pointee_metadata_ty_or_projection(tcx),
881        }
882    }
883}
884
885impl<'tcx> BinOp {
886    pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
887        // FIXME: handle SIMD correctly
888        match self {
889            &BinOp::Add
890            | &BinOp::AddUnchecked
891            | &BinOp::Sub
892            | &BinOp::SubUnchecked
893            | &BinOp::Mul
894            | &BinOp::MulUnchecked
895            | &BinOp::Div
896            | &BinOp::Rem
897            | &BinOp::BitXor
898            | &BinOp::BitAnd
899            | &BinOp::BitOr => {
900                // these should be integers or floats of the same size.
901                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);
902                lhs_ty
903            }
904            &BinOp::AddWithOverflow | &BinOp::SubWithOverflow | &BinOp::MulWithOverflow => {
905                // these should be integers of the same size.
906                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);
907                Ty::new_tup(tcx, &[lhs_ty, tcx.types.bool])
908            }
909            &BinOp::Shl
910            | &BinOp::ShlUnchecked
911            | &BinOp::Shr
912            | &BinOp::ShrUnchecked
913            | &BinOp::Offset => {
914                lhs_ty // lhs_ty can be != rhs_ty
915            }
916            &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
917                tcx.types.bool
918            }
919            &BinOp::Cmp => {
920                // these should be integer-like types of the same size.
921                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);
922                tcx.ty_ordering_enum(DUMMY_SP)
923            }
924        }
925    }
926    pub(crate) fn to_hir_binop(self) -> hir::BinOpKind {
927        match self {
928            // HIR `+`/`-`/`*` can map to either of these MIR BinOp, depending
929            // on whether overflow checks are enabled or not.
930            BinOp::Add | BinOp::AddWithOverflow => hir::BinOpKind::Add,
931            BinOp::Sub | BinOp::SubWithOverflow => hir::BinOpKind::Sub,
932            BinOp::Mul | BinOp::MulWithOverflow => hir::BinOpKind::Mul,
933            BinOp::Div => hir::BinOpKind::Div,
934            BinOp::Rem => hir::BinOpKind::Rem,
935            BinOp::BitXor => hir::BinOpKind::BitXor,
936            BinOp::BitAnd => hir::BinOpKind::BitAnd,
937            BinOp::BitOr => hir::BinOpKind::BitOr,
938            BinOp::Shl => hir::BinOpKind::Shl,
939            BinOp::Shr => hir::BinOpKind::Shr,
940            BinOp::Eq => hir::BinOpKind::Eq,
941            BinOp::Ne => hir::BinOpKind::Ne,
942            BinOp::Lt => hir::BinOpKind::Lt,
943            BinOp::Gt => hir::BinOpKind::Gt,
944            BinOp::Le => hir::BinOpKind::Le,
945            BinOp::Ge => hir::BinOpKind::Ge,
946            // We don't have HIR syntax for these.
947            BinOp::Cmp
948            | BinOp::AddUnchecked
949            | BinOp::SubUnchecked
950            | BinOp::MulUnchecked
951            | BinOp::ShlUnchecked
952            | BinOp::ShrUnchecked
953            | BinOp::Offset => {
954                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
955            }
956        }
957    }
958
959    /// If this is a `FooWithOverflow`, return `Some(Foo)`.
960    pub fn overflowing_to_wrapping(self) -> Option<BinOp> {
961        Some(match self {
962            BinOp::AddWithOverflow => BinOp::Add,
963            BinOp::SubWithOverflow => BinOp::Sub,
964            BinOp::MulWithOverflow => BinOp::Mul,
965            _ => return None,
966        })
967    }
968
969    /// Returns whether this is a `FooWithOverflow`
970    pub fn is_overflowing(self) -> bool {
971        self.overflowing_to_wrapping().is_some()
972    }
973
974    /// If this is a `Foo`, return `Some(FooWithOverflow)`.
975    pub fn wrapping_to_overflowing(self) -> Option<BinOp> {
976        Some(match self {
977            BinOp::Add => BinOp::AddWithOverflow,
978            BinOp::Sub => BinOp::SubWithOverflow,
979            BinOp::Mul => BinOp::MulWithOverflow,
980            _ => return None,
981        })
982    }
983}
984
985impl From<Mutability> for RawPtrKind {
986    fn from(other: Mutability) -> Self {
987        match other {
988            Mutability::Mut => RawPtrKind::Mut,
989            Mutability::Not => RawPtrKind::Const,
990        }
991    }
992}
993
994impl RawPtrKind {
995    pub fn is_fake(self) -> bool {
996        match self {
997            RawPtrKind::Mut | RawPtrKind::Const => false,
998            RawPtrKind::FakeForPtrMetadata => true,
999        }
1000    }
1001
1002    pub fn to_mutbl_lossy(self) -> Mutability {
1003        match self {
1004            RawPtrKind::Mut => Mutability::Mut,
1005            RawPtrKind::Const => Mutability::Not,
1006
1007            // We have no type corresponding to a fake borrow, so use
1008            // `*const` as an approximation.
1009            RawPtrKind::FakeForPtrMetadata => Mutability::Not,
1010        }
1011    }
1012
1013    pub fn ptr_str(self) -> &'static str {
1014        match self {
1015            RawPtrKind::Mut => "mut",
1016            RawPtrKind::Const => "const",
1017            RawPtrKind::FakeForPtrMetadata => "const (fake)",
1018        }
1019    }
1020}
1021
1022#[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_hasher::StableHash for
            StmtDebugInfos<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hasher::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::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)]
1023pub struct StmtDebugInfos<'tcx>(Vec<StmtDebugInfo<'tcx>>);
1024
1025impl<'tcx> StmtDebugInfos<'tcx> {
1026    pub fn push(&mut self, debuginfo: StmtDebugInfo<'tcx>) {
1027        self.0.push(debuginfo);
1028    }
1029
1030    pub fn drop_debuginfo(&mut self) {
1031        self.0.clear();
1032    }
1033
1034    pub fn is_empty(&self) -> bool {
1035        self.0.is_empty()
1036    }
1037
1038    pub fn prepend(&mut self, debuginfos: &mut Self) {
1039        if debuginfos.is_empty() {
1040            return;
1041        };
1042        debuginfos.0.append(self);
1043        std::mem::swap(debuginfos, self);
1044    }
1045
1046    pub fn append(&mut self, debuginfos: &mut Self) {
1047        if debuginfos.is_empty() {
1048            return;
1049        };
1050        self.0.append(debuginfos);
1051    }
1052
1053    pub fn extend(&mut self, debuginfos: &Self) {
1054        if debuginfos.is_empty() {
1055            return;
1056        };
1057        self.0.extend_from_slice(debuginfos);
1058    }
1059
1060    pub fn retain_locals(&mut self, locals: &DenseBitSet<Local>) {
1061        self.retain(|debuginfo| match debuginfo {
1062            StmtDebugInfo::AssignRef(local, _) | StmtDebugInfo::InvalidAssign(local) => {
1063                locals.contains(*local)
1064            }
1065        });
1066    }
1067}
1068
1069impl<'tcx> ops::Deref for StmtDebugInfos<'tcx> {
1070    type Target = Vec<StmtDebugInfo<'tcx>>;
1071
1072    #[inline]
1073    fn deref(&self) -> &Vec<StmtDebugInfo<'tcx>> {
1074        &self.0
1075    }
1076}
1077
1078impl<'tcx> ops::DerefMut for StmtDebugInfos<'tcx> {
1079    #[inline]
1080    fn deref_mut(&mut self) -> &mut Vec<StmtDebugInfo<'tcx>> {
1081        &mut self.0
1082    }
1083}
1084
1085#[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_hasher::StableHash for
            StmtDebugInfo<'tcx> {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hasher::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::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)]
1086pub enum StmtDebugInfo<'tcx> {
1087    AssignRef(Local, Place<'tcx>),
1088    InvalidAssign(Local),
1089}