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 rustc_span::bug;
8use thin_vec::ThinVec;
9use tracing::instrument;
10
11use super::interpret::GlobalAlloc;
12use super::*;
13use crate::ty::{CoroutineArgsExt, Unnormalized};
14
15///////////////////////////////////////////////////////////////////////////
16// Statements
17
18/// A statement in a basic block, including information about its source code.
19#[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) {
                let Statement {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        debuginfos: ref __binding_2 } = *self;
                ::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)]
20#[non_exhaustive]
21pub struct Statement<'tcx> {
22    pub source_info: SourceInfo,
23    pub kind: StatementKind<'tcx>,
24    /// Some debuginfos appearing before the primary statement.
25    pub debuginfos: StmtDebugInfos<'tcx>,
26}
27
28impl<'tcx> Statement<'tcx> {
29    /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
30    /// invalidating statement indices in `Location`s.
31    pub fn make_nop(&mut self, drop_debuginfo: bool) {
32        if self.kind == StatementKind::Nop {
33            return;
34        }
35        let replaced_stmt = std::mem::replace(&mut self.kind, StatementKind::Nop);
36        if !drop_debuginfo {
37            let Some(debuginfo) = replaced_stmt.as_debuginfo() else {
38                bug_impl(None, format_args!("debuginfo is not yet supported."),
    Location::caller())bug!("debuginfo is not yet supported.")
39            };
40            self.debuginfos.push(debuginfo);
41        }
42    }
43
44    pub fn new(source_info: SourceInfo, kind: StatementKind<'tcx>) -> Self {
45        Statement { source_info, kind, debuginfos: StmtDebugInfos::default() }
46    }
47}
48
49impl<'tcx> StatementKind<'tcx> {
50    /// Returns a simple string representation of a `StatementKind` variant, independent of any
51    /// values it might hold (e.g. `StatementKind::Assign` always returns `"Assign"`).
52    pub const fn name(&self) -> &'static str {
53        match self {
54            StatementKind::Assign(..) => "Assign",
55            StatementKind::FakeRead(..) => "FakeRead",
56            StatementKind::SetDiscriminant { .. } => "SetDiscriminant",
57            StatementKind::StorageLive(..) => "StorageLive",
58            StatementKind::StorageDead(..) => "StorageDead",
59            StatementKind::PlaceMention(..) => "PlaceMention",
60            StatementKind::AscribeUserType(..) => "AscribeUserType",
61            StatementKind::Coverage(..) => "Coverage",
62            StatementKind::Intrinsic(..) => "Intrinsic",
63            StatementKind::ConstEvalCounter => "ConstEvalCounter",
64            StatementKind::Nop => "Nop",
65            StatementKind::BackwardIncompatibleDropHint { .. } => "BackwardIncompatibleDropHint",
66        }
67    }
68    pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
69        match self {
70            StatementKind::Assign(x) => Some(x),
71            _ => None,
72        }
73    }
74
75    pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
76        match self {
77            StatementKind::Assign(x) => Some(x),
78            _ => None,
79        }
80    }
81
82    pub fn as_debuginfo(&self) -> Option<StmtDebugInfo<'tcx>> {
83        match self {
84            StatementKind::Assign((place, Rvalue::Ref(_, _, ref_place)))
85                if let Some(local) = place.as_local() =>
86            {
87                Some(StmtDebugInfo::AssignRef(local, *ref_place))
88            }
89            _ => None,
90        }
91    }
92}
93
94///////////////////////////////////////////////////////////////////////////
95// Places
96
97#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for PlaceTy<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for PlaceTy<'tcx> { }
#[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)]
98pub struct PlaceTy<'tcx> {
99    pub ty: Ty<'tcx>,
100    /// Downcast to a particular variant of an enum or a coroutine, if included.
101    pub variant_index: Option<VariantIdx>,
102}
103
104// At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
105#[cfg(target_pointer_width = "64")]
106const _: [(); 16] = [(); ::std::mem::size_of::<PlaceTy<'_>>()];rustc_data_structures::static_assert_size!(PlaceTy<'_>, 16);
107
108impl<'tcx> PlaceTy<'tcx> {
109    #[inline]
110    pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
111        PlaceTy { ty, variant_index: None }
112    }
113
114    /// `place_ty.field_ty(tcx, f)` computes the type of a given field.
115    ///
116    /// Most clients of `PlaceTy` can instead just extract the relevant type
117    /// directly from their `PlaceElem`, but some instances of `ProjectionElem<V, T>`
118    /// do not carry a `Ty` for `T`.
119    ///
120    /// Note that the resulting type has not been normalized.
121    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("field_ty",
                                "rustc_middle::mir::statement", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/mir/statement.rs"),
                                ::tracing_core::__macro_support::Option::Some(121u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::statement"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("self_ty")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("self_ty");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("variant_idx")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("variant_idx");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("f")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("f");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&variant_idx)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&f)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return:
                                Unnormalized<'tcx, Ty<'tcx>> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if let Some(variant_index) = variant_idx {
                            match *self_ty.kind() {
                                ty::Adt(adt_def, args) if adt_def.is_enum() => {
                                    adt_def.variant(variant_index).fields[f].ty(tcx, args)
                                }
                                ty::Coroutine(def_id, args) => {
                                    let mut variants =
                                        args.as_coroutine().state_tys(def_id, tcx);
                                    let Some(mut variant) =
                                        variants.nth(variant_index.into()) else {
                                            bug_impl(None,
                                                format_args!("variant {0:?} of coroutine out of range: {1:?}",
                                                    variant_index, self_ty), Location::caller());
                                        };
                                    Unnormalized::new_wip(variant.nth(f.index()).unwrap_or_else(||
                                                {
                                                    bug_impl(None,
                                                        format_args!("field {0:?} out of range of variant: {1:?} {2:?}",
                                                            f, self_ty, variant_idx), Location::caller())
                                                }))
                                }
                                _ =>
                                    bug_impl(None,
                                        format_args!("can\'t downcast non-adt non-coroutine type: {0:?}",
                                            self_ty), Location::caller()),
                            }
                        } else {
                            match self_ty.kind() {
                                ty::Adt(adt_def, args) if !adt_def.is_enum() => {
                                    adt_def.non_enum_variant().fields[f].ty(tcx, args)
                                }
                                ty::Closure(_, args) =>
                                    Unnormalized::dummy(args.as_closure().upvar_tys().get(f.index()).copied().unwrap_or_else(||
                                                bug_impl(None,
                                                    format_args!("field {0:?} out of range: {1:?}", f, self_ty),
                                                    Location::caller()))),
                                ty::CoroutineClosure(_, args) =>
                                    Unnormalized::dummy(args.as_coroutine_closure().upvar_tys().get(f.index()).copied().unwrap_or_else(||
                                                bug_impl(None,
                                                    format_args!("field {0:?} out of range: {1:?}", f, self_ty),
                                                    Location::caller()))),
                                ty::Coroutine(_, args) =>
                                    Unnormalized::dummy(args.as_coroutine().upvar_tys().get(f.index()).copied().unwrap_or_else(||
                                                {
                                                    bug_impl(None,
                                                        format_args!("field {0:?} out of range of prefixes for {1}",
                                                            f, self_ty), Location::caller())
                                                })),
                                ty::Tuple(tys) =>
                                    Unnormalized::dummy(tys.get(f.index()).copied().unwrap_or_else(||
                                                bug_impl(None,
                                                    format_args!("field {0:?} out of range: {1:?}", f, self_ty),
                                                    Location::caller()))),
                                _ =>
                                    bug_impl(None,
                                        format_args!("can\'t project out of {0:?}", self_ty),
                                        Location::caller()),
                            }
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/mir/statement.rs:121",
                        "rustc_middle::mir::statement", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/mir/statement.rs"),
                        ::tracing_core::__macro_support::Option::Some(121u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::statement"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
122    pub fn field_ty(
123        tcx: TyCtxt<'tcx>,
124        self_ty: Ty<'tcx>,
125        variant_idx: Option<VariantIdx>,
126        f: FieldIdx,
127    ) -> Unnormalized<'tcx, Ty<'tcx>> {
128        if let Some(variant_index) = variant_idx {
129            match *self_ty.kind() {
130                ty::Adt(adt_def, args) if adt_def.is_enum() => {
131                    adt_def.variant(variant_index).fields[f].ty(tcx, args)
132                }
133                ty::Coroutine(def_id, args) => {
134                    let mut variants = args.as_coroutine().state_tys(def_id, tcx);
135                    let Some(mut variant) = variants.nth(variant_index.into()) else {
136                        bug!("variant {variant_index:?} of coroutine out of range: {self_ty:?}");
137                    };
138
139                    Unnormalized::new_wip(variant.nth(f.index()).unwrap_or_else(|| {
140                        bug!("field {f:?} out of range of variant: {self_ty:?} {variant_idx:?}")
141                    }))
142                }
143                _ => bug!("can't downcast non-adt non-coroutine type: {self_ty:?}"),
144            }
145        } else {
146            match self_ty.kind() {
147                ty::Adt(adt_def, args) if !adt_def.is_enum() => {
148                    adt_def.non_enum_variant().fields[f].ty(tcx, args)
149                }
150                ty::Closure(_, args) => Unnormalized::dummy(
151                    args.as_closure()
152                        .upvar_tys()
153                        .get(f.index())
154                        .copied()
155                        .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
156                ),
157                ty::CoroutineClosure(_, args) => Unnormalized::dummy(
158                    args.as_coroutine_closure()
159                        .upvar_tys()
160                        .get(f.index())
161                        .copied()
162                        .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
163                ),
164                // Only upvars are accessible without a variant index.
165                ty::Coroutine(_, args) => Unnormalized::dummy(
166                    args.as_coroutine().upvar_tys().get(f.index()).copied().unwrap_or_else(|| {
167                        bug!("field {f:?} out of range of prefixes for {self_ty}")
168                    }),
169                ),
170                ty::Tuple(tys) => Unnormalized::dummy(
171                    tys.get(f.index())
172                        .copied()
173                        .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
174                ),
175                _ => bug!("can't project out of {self_ty:?}"),
176            }
177        }
178    }
179
180    pub fn multi_projection_ty(
181        self,
182        tcx: TyCtxt<'tcx>,
183        elems: &[PlaceElem<'tcx>],
184    ) -> PlaceTy<'tcx> {
185        elems.iter().fold(self, |place_ty, &elem| place_ty.projection_ty(tcx, elem))
186    }
187
188    /// Convenience wrapper around `projection_ty_core` for `PlaceElem`,
189    /// where we can just use the `Ty` that is already stored inline on
190    /// field projection elems.
191    pub fn projection_ty<V: Debug>(
192        self,
193        tcx: TyCtxt<'tcx>,
194        elem: ProjectionElem<V, Ty<'tcx>>,
195    ) -> PlaceTy<'tcx> {
196        self.projection_ty_core(tcx, &elem, |_, _, _, ty| ty, |ty| ty)
197    }
198
199    /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
200    /// projects `place_ty` onto `elem`, returning the appropriate
201    /// `Ty` or downcast variant corresponding to that projection.
202    /// The `handle_field` callback must map a `FieldIdx` to its `Ty`,
203    /// (which should be trivial when `T` = `Ty`).
204    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("projection_ty_core",
                                "rustc_middle::mir::statement", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/mir/statement.rs"),
                                ::tracing_core::__macro_support::Option::Some(204u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::statement"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("self")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("self");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("elem")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("elem");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&elem)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: PlaceTy<'tcx> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        if self.variant_index.is_some() &&
                                !#[allow(non_exhaustive_omitted_patterns)] match elem {
                                        ProjectionElem::Field(..) => true,
                                        _ => false,
                                    } {
                            bug_impl(None,
                                format_args!("cannot use non field projection on downcasted place"),
                                Location::caller())
                        }
                        match *elem {
                            ProjectionElem::Deref => {
                                let ty =
                                    self.ty.builtin_deref(true).unwrap_or_else(||
                                            {
                                                bug_impl(None,
                                                    format_args!("deref projection of non-dereferenceable ty {0:?}",
                                                        self), Location::caller())
                                            });
                                PlaceTy::from_ty(ty)
                            }
                            ProjectionElem::PhantomDeref => PlaceTy::from_ty(self.ty),
                            ProjectionElem::Index(_) | ProjectionElem::ConstantIndex {
                                .. } => {
                                PlaceTy::from_ty(self.ty.builtin_index().unwrap())
                            }
                            ProjectionElem::Subslice { from, to, from_end } => {
                                PlaceTy::from_ty(match self.ty.kind() {
                                        ty::Slice(..) => self.ty,
                                        ty::Array(inner, _) if !from_end =>
                                            Ty::new_array(tcx, *inner, to - from),
                                        ty::Array(inner, size) if from_end => {
                                            let size =
                                                size.try_to_target_usize(tcx).expect("expected subslice projection on fixed-size array");
                                            let len = size - from - to;
                                            Ty::new_array(tcx, *inner, len)
                                        }
                                        _ =>
                                            bug_impl(None,
                                                format_args!("cannot subslice non-array type: `{0:?}`",
                                                    self), Location::caller()),
                                    })
                            }
                            ProjectionElem::Downcast(_name, index) => {
                                PlaceTy { ty: self.ty, variant_index: Some(index) }
                            }
                            ProjectionElem::Field(f, fty) => {
                                PlaceTy::from_ty(handle_field(self.ty, self.variant_index,
                                        f, fty))
                            }
                            ProjectionElem::OpaqueCast(ty) =>
                                PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty)),
                            ProjectionElem::UnwrapUnsafeBinder(ty) => {
                                PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty))
                            }
                        }
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/mir/statement.rs:204",
                        "rustc_middle::mir::statement", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_middle/src/mir/statement.rs"),
                        ::tracing_core::__macro_support::Option::Some(204u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::statement"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(tcx, handle_field, handle_opaque_cast_and_subtype), ret)]
205    pub fn projection_ty_core<V, T>(
206        self,
207        tcx: TyCtxt<'tcx>,
208        elem: &ProjectionElem<V, T>,
209        mut handle_field: impl FnMut(Ty<'tcx>, Option<VariantIdx>, FieldIdx, T) -> Ty<'tcx>,
210        mut handle_opaque_cast_and_subtype: impl FnMut(T) -> Ty<'tcx>,
211    ) -> PlaceTy<'tcx>
212    where
213        V: Debug,
214        T: Debug + Copy,
215    {
216        if self.variant_index.is_some() && !matches!(elem, ProjectionElem::Field(..)) {
217            bug!("cannot use non field projection on downcasted place")
218        }
219        match *elem {
220            ProjectionElem::Deref => {
221                let ty = self.ty.builtin_deref(true).unwrap_or_else(|| {
222                    bug!("deref projection of non-dereferenceable ty {:?}", self)
223                });
224                PlaceTy::from_ty(ty)
225            }
226            ProjectionElem::PhantomDeref => PlaceTy::from_ty(self.ty),
227            ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } => {
228                PlaceTy::from_ty(self.ty.builtin_index().unwrap())
229            }
230            ProjectionElem::Subslice { from, to, from_end } => {
231                PlaceTy::from_ty(match self.ty.kind() {
232                    ty::Slice(..) => self.ty,
233                    ty::Array(inner, _) if !from_end => Ty::new_array(tcx, *inner, to - from),
234                    ty::Array(inner, size) if from_end => {
235                        let size = size
236                            .try_to_target_usize(tcx)
237                            .expect("expected subslice projection on fixed-size array");
238                        let len = size - from - to;
239                        Ty::new_array(tcx, *inner, len)
240                    }
241                    _ => bug!("cannot subslice non-array type: `{:?}`", self),
242                })
243            }
244            ProjectionElem::Downcast(_name, index) => {
245                PlaceTy { ty: self.ty, variant_index: Some(index) }
246            }
247            ProjectionElem::Field(f, fty) => {
248                PlaceTy::from_ty(handle_field(self.ty, self.variant_index, f, fty))
249            }
250            ProjectionElem::OpaqueCast(ty) => PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty)),
251
252            // FIXME(unsafe_binders): Rename `handle_opaque_cast_and_subtype` to be more general.
253            ProjectionElem::UnwrapUnsafeBinder(ty) => {
254                PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty))
255            }
256        }
257    }
258}
259
260impl<V, T> ProjectionElem<V, T> {
261    /// Returns `true` if the target of this projection may refer to a different region of memory
262    /// than the base.
263    pub fn is_indirect(&self) -> bool {
264        match self {
265            Self::Deref | Self::PhantomDeref => true,
266
267            Self::Field(_, _)
268            | Self::Index(_)
269            | Self::OpaqueCast(_)
270            | Self::ConstantIndex { .. }
271            | Self::Subslice { .. }
272            | Self::Downcast(_, _)
273            | Self::UnwrapUnsafeBinder(..) => false,
274        }
275    }
276
277    /// Returns `true` if the target of this projection always refers to the same memory region
278    /// whatever the state of the program.
279    pub fn is_stable_offset(&self) -> bool {
280        match self {
281            Self::Deref | Self::Index(_) => false,
282            Self::Field(_, _)
283            | Self::OpaqueCast(_)
284            | Self::ConstantIndex { .. }
285            | Self::Subslice { .. }
286            | Self::Downcast(_, _)
287            | Self::UnwrapUnsafeBinder(..)
288            | Self::PhantomDeref => true,
289        }
290    }
291
292    /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
293    pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
294        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::Downcast(_, x) if x == v => true,
    _ => false,
}matches!(*self, Self::Downcast(_, x) if x == v)
295    }
296
297    /// Returns `true` if this is a `Field` projection with the given index.
298    pub fn is_field_to(&self, f: FieldIdx) -> bool {
299        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::Field(x, _) if x == f => true,
    _ => false,
}matches!(*self, Self::Field(x, _) if x == f)
300    }
301
302    /// Returns `true` if this is accepted inside `VarDebugInfoContents::Place`.
303    pub fn can_use_in_debuginfo(&self) -> bool {
304        match self {
305            Self::ConstantIndex { from_end: false, .. }
306            | Self::Deref
307            | Self::Downcast(_, _)
308            | Self::Field(_, _) => true,
309            Self::ConstantIndex { from_end: true, .. }
310            | Self::Index(_)
311            | Self::OpaqueCast(_)
312            | Self::Subslice { .. }
313            | Self::PhantomDeref => false,
314
315            // FIXME(unsafe_binders): Figure this out.
316            Self::UnwrapUnsafeBinder(..) => false,
317        }
318    }
319
320    /// Returns the `ProjectionKind` associated to this projection.
321    pub fn kind(self) -> ProjectionKind {
322        self.try_map(|_| Some(()), |_| ()).unwrap()
323    }
324
325    /// Apply functions to types and values in this projection and return the result.
326    pub fn try_map<V2, T2>(
327        self,
328        v: impl FnOnce(V) -> Option<V2>,
329        t: impl FnOnce(T) -> T2,
330    ) -> Option<ProjectionElem<V2, T2>> {
331        Some(match self {
332            ProjectionElem::Deref => ProjectionElem::Deref,
333            ProjectionElem::PhantomDeref => bug_impl(None, format_args!("PhantomDeref shouldn\'t hopefully come here"),
    Location::caller())bug!("PhantomDeref shouldn't hopefully come here"),
334            ProjectionElem::Downcast(name, read_variant) => {
335                ProjectionElem::Downcast(name, read_variant)
336            }
337            ProjectionElem::Field(f, ty) => ProjectionElem::Field(f, t(ty)),
338            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
339                ProjectionElem::ConstantIndex { offset, min_length, from_end }
340            }
341            ProjectionElem::Subslice { from, to, from_end } => {
342                ProjectionElem::Subslice { from, to, from_end }
343            }
344            ProjectionElem::OpaqueCast(ty) => ProjectionElem::OpaqueCast(t(ty)),
345            ProjectionElem::UnwrapUnsafeBinder(ty) => ProjectionElem::UnwrapUnsafeBinder(t(ty)),
346            ProjectionElem::Index(val) => ProjectionElem::Index(v(val)?),
347        })
348    }
349}
350
351/// Alias for projections as they appear in `UserTypeProjection`, where we
352/// need neither the `V` parameter for `Index` nor the `T` for `Field`.
353pub type ProjectionKind = ProjectionElem<(), ()>;
354
355#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for PlaceRef<'tcx> { }
#[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::marker::StructuralPartialEq for PlaceRef<'tcx> { }
#[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)]
356pub struct PlaceRef<'tcx> {
357    pub local: Local,
358    pub projection: &'tcx [PlaceElem<'tcx>],
359}
360
361// Once we stop implementing `Ord` for `DefId`,
362// this impl will be unnecessary. Until then, we'll
363// leave this impl in place to prevent re-adding a
364// dependency on the `Ord` impl for `DefId`
365impl<'tcx> !PartialOrd for PlaceRef<'tcx> {}
366
367impl<'tcx> Place<'tcx> {
368    // FIXME change this to a const fn by also making List::empty a const fn.
369    pub fn return_place() -> Place<'tcx> {
370        Place { local: RETURN_PLACE, projection: List::empty() }
371    }
372
373    /// Returns `true` if this `Place` contains a `Deref` projection.
374    ///
375    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
376    /// same region of memory as its base.
377    pub fn is_indirect(&self) -> bool {
378        self.projection.iter().any(|elem| elem.is_indirect())
379    }
380
381    /// Returns `true` if the `Place` always refers to the same memory region
382    /// whatever the state of the program.
383    pub fn is_stable_offset(&self) -> bool {
384        self.projection.iter().all(|elem| elem.is_stable_offset())
385    }
386
387    /// Returns `true` if this `Place`'s first projection is `Deref`.
388    ///
389    /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later,
390    /// `Deref` projections can only occur as the first projection. In that case this method
391    /// is equivalent to `is_indirect`, but faster.
392    pub fn is_indirect_first_projection(&self) -> bool {
393        self.as_ref().is_indirect_first_projection()
394    }
395
396    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
397    /// a single deref of a local.
398    #[inline(always)]
399    pub fn local_or_deref_local(&self) -> Option<Local> {
400        self.as_ref().local_or_deref_local()
401    }
402
403    /// If this place represents a local variable like `_X` with no
404    /// projections, return `Some(_X)`.
405    #[inline(always)]
406    pub fn as_local(&self) -> Option<Local> {
407        self.as_ref().as_local()
408    }
409
410    #[inline]
411    pub fn as_ref(&self) -> PlaceRef<'tcx> {
412        PlaceRef { local: self.local, projection: self.projection }
413    }
414
415    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
416    /// its projection and then subsequently more projections are added.
417    /// As a concrete example, given the place a.b.c, this would yield:
418    /// - (a, .b)
419    /// - (a.b, .c)
420    ///
421    /// Given a place without projections, the iterator is empty.
422    #[inline]
423    pub fn iter_projections(
424        self,
425    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
426        self.as_ref().iter_projections()
427    }
428
429    /// Generates a new place by appending `more_projections` to the existing ones
430    /// and interning the result.
431    pub fn project_deeper(self, more_projections: &[PlaceElem<'tcx>], tcx: TyCtxt<'tcx>) -> Self {
432        if more_projections.is_empty() {
433            return self;
434        }
435
436        self.as_ref().project_deeper(more_projections, tcx)
437    }
438
439    /// Return a place that projects to a field of the current place.
440    ///
441    /// The type of the current place must be an ADT.
442    pub fn project_to_field(
443        self,
444        idx: FieldIdx,
445        local_decls: &(impl HasLocalDecls<'tcx> + ?Sized),
446        tcx: TyCtxt<'tcx>,
447    ) -> Self {
448        let ty = self.ty(local_decls, tcx).ty;
449        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}") };
450        let field = &adt.non_enum_variant().fields[idx];
451        let field_ty = field.ty(tcx, args).skip_norm_wip();
452        self.project_deeper(&[ProjectionElem::Field(idx, field_ty)], tcx)
453    }
454
455    pub fn ty_from<D>(
456        local: Local,
457        projection: &[PlaceElem<'tcx>],
458        local_decls: &D,
459        tcx: TyCtxt<'tcx>,
460    ) -> PlaceTy<'tcx>
461    where
462        D: ?Sized + HasLocalDecls<'tcx>,
463    {
464        // If there's a field projection element in `projection`, we *could* skip everything
465        // before that, but on 2026-01-31 a perf experiment showed no benefit from doing so.
466        PlaceTy::from_ty(local_decls.local_decls()[local].ty).multi_projection_ty(tcx, projection)
467    }
468
469    pub fn ty<D: ?Sized>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
470    where
471        D: HasLocalDecls<'tcx>,
472    {
473        Place::ty_from(self.local, self.projection, local_decls, tcx)
474    }
475}
476
477impl From<Local> for Place<'_> {
478    #[inline]
479    fn from(local: Local) -> Self {
480        Place { local, projection: List::empty() }
481    }
482}
483
484impl<'tcx> PlaceRef<'tcx> {
485    pub fn is_prefix_of(&self, other: PlaceRef<'tcx>) -> bool {
486        self.local == other.local
487            && self.projection.len() <= other.projection.len()
488            && self.projection == &other.projection[..self.projection.len()]
489    }
490
491    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
492    /// a single deref of a local.
493    pub fn local_or_deref_local(&self) -> Option<Local> {
494        match *self {
495            PlaceRef { local, projection: [] }
496            | PlaceRef {
497                local,
498                projection: [ProjectionElem::Deref | ProjectionElem::PhantomDeref],
499            } => Some(local),
500            _ => None,
501        }
502    }
503
504    /// Returns `true` if this `Place` contains a `Deref` projection.
505    ///
506    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
507    /// same region of memory as its base.
508    pub fn is_indirect(&self) -> bool {
509        self.projection.iter().any(|elem| elem.is_indirect())
510    }
511
512    /// Returns `true` if this `Place`'s first projection is `Deref`.
513    ///
514    /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later,
515    /// `Deref` projections can only occur as the first projection. In that case this method
516    /// is equivalent to `is_indirect`, but faster.
517    pub fn is_indirect_first_projection(&self) -> bool {
518        // To make sure this is not accidentally used in wrong mir phase
519        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!(
520            self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
521        );
522        self.projection.first() == Some(&PlaceElem::Deref)
523    }
524
525    /// If this place represents a local variable like `_X` with no
526    /// projections, return `Some(_X)`.
527    #[inline]
528    pub fn as_local(&self) -> Option<Local> {
529        match *self {
530            PlaceRef { local, projection: [] } => Some(local),
531            _ => None,
532        }
533    }
534
535    #[inline]
536    pub fn to_place(&self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
537        Place { local: self.local, projection: tcx.mk_place_elems(self.projection) }
538    }
539
540    #[inline]
541    pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
542        if let &[ref proj_base @ .., elem] = self.projection {
543            Some((PlaceRef { local: self.local, projection: proj_base }, elem))
544        } else {
545            None
546        }
547    }
548
549    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
550    /// its projection and then subsequently more projections are added.
551    /// As a concrete example, given the place a.b.c, this would yield:
552    /// - (a, .b)
553    /// - (a.b, .c)
554    ///
555    /// Given a place without projections, the iterator is empty.
556    #[inline]
557    pub fn iter_projections(
558        self,
559    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
560        self.projection.iter().enumerate().map(move |(i, proj)| {
561            let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
562            (base, *proj)
563        })
564    }
565
566    /// Return the place accessed locals that include the base local.
567    pub fn accessed_locals(self) -> impl Iterator<Item = Local> {
568        std::iter::once(self.local).chain(self.projection.iter().filter_map(|proj| match proj {
569            ProjectionElem::Index(local) => Some(*local),
570            ProjectionElem::Deref
571            | ProjectionElem::PhantomDeref
572            | ProjectionElem::Field(_, _)
573            | ProjectionElem::ConstantIndex { .. }
574            | ProjectionElem::Subslice { .. }
575            | ProjectionElem::Downcast(_, _)
576            | ProjectionElem::OpaqueCast(_)
577            | ProjectionElem::UnwrapUnsafeBinder(_) => None,
578        }))
579    }
580
581    /// Generates a new place by appending `more_projections` to the existing ones
582    /// and interning the result.
583    pub fn project_deeper(
584        self,
585        more_projections: &[PlaceElem<'tcx>],
586        tcx: TyCtxt<'tcx>,
587    ) -> Place<'tcx> {
588        let mut v: Vec<PlaceElem<'tcx>>;
589
590        let new_projections = if self.projection.is_empty() {
591            more_projections
592        } else {
593            v = Vec::with_capacity(self.projection.len() + more_projections.len());
594            v.extend(self.projection);
595            v.extend(more_projections);
596            &v
597        };
598
599        Place { local: self.local, projection: tcx.mk_place_elems(new_projections) }
600    }
601
602    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
603    where
604        D: ?Sized + HasLocalDecls<'tcx>,
605    {
606        Place::ty_from(self.local, self.projection, local_decls, tcx)
607    }
608}
609
610impl From<Local> for PlaceRef<'_> {
611    #[inline]
612    fn from(local: Local) -> Self {
613        PlaceRef { local, projection: &[] }
614    }
615}
616
617///////////////////////////////////////////////////////////////////////////
618// Operands
619
620impl<'tcx> Operand<'tcx> {
621    /// Convenience helper to make a constant that refers to the fn
622    /// with given `DefId` and args. Since this is used to synthesize
623    /// MIR, assumes `user_ty` is None.
624    pub fn function_handle(
625        tcx: TyCtxt<'tcx>,
626        def_id: DefId,
627        args: &[GenericArg<'tcx>],
628        span: Span,
629    ) -> Self {
630        Operand::zero_sized_constant(
631            tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip(),
632            span,
633        )
634    }
635
636    /// Convenience helper to make a constant that refers to the given `DefId` and args. Since this
637    /// is used to synthesize MIR, assumes `user_ty` is None.
638    pub fn unevaluated_constant(
639        tcx: TyCtxt<'tcx>,
640        def_id: DefId,
641        args: &[GenericArg<'tcx>],
642        span: Span,
643    ) -> Self {
644        let const_ = Const::from_unevaluated(tcx, def_id).instantiate(tcx, args).skip_norm_wip();
645        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
646    }
647
648    /// Convenience helper to make a constant that refers to a zero-sized type.
649    pub fn zero_sized_constant(ty: Ty<'tcx>, span: Span) -> Self {
650        let const_ = Const::Val(ConstValue::ZeroSized, ty);
651        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
652    }
653
654    pub fn is_move(&self) -> bool {
655        #[allow(non_exhaustive_omitted_patterns)] match self {
    Operand::Move(..) => true,
    _ => false,
}matches!(self, Operand::Move(..))
656    }
657
658    /// Convenience helper to make a literal-like constant from a given scalar value.
659    /// Since this is used to synthesize MIR, assumes `user_ty` is None.
660    pub fn const_from_scalar(
661        tcx: TyCtxt<'tcx>,
662        ty: Ty<'tcx>,
663        val: Scalar,
664        span: Span,
665    ) -> Operand<'tcx> {
666        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!({
667            let typing_env = ty::TypingEnv::fully_monomorphized();
668            let type_size = tcx
669                .layout_of(typing_env.as_query_input(ty))
670                .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}"))
671                .size;
672            let scalar_size = match val {
673                Scalar::Int(int) => int.size(),
674                _ => panic!("Invalid scalar type {val:?}"),
675            };
676            scalar_size == type_size
677        });
678        Operand::Constant(Box::new(ConstOperand {
679            span,
680            user_ty: None,
681            const_: Const::Val(ConstValue::Scalar(val), ty),
682        }))
683    }
684
685    pub fn to_copy(&self) -> Self {
686        match *self {
687            Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => self.clone(),
688            Operand::Move(place) => Operand::Copy(place),
689        }
690    }
691
692    /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
693    /// constant.
694    pub fn place(&self) -> Option<Place<'tcx>> {
695        match self {
696            Operand::Copy(place) | Operand::Move(place) => Some(*place),
697            Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
698        }
699    }
700
701    /// Returns the `ConstOperand` that is the target of this `Operand`, or `None` if this `Operand` is a
702    /// place.
703    pub fn constant(&self) -> Option<&ConstOperand<'tcx>> {
704        match self {
705            Operand::Constant(x) => Some(&**x),
706            Operand::Copy(_) | Operand::Move(_) | Operand::RuntimeChecks(_) => None,
707        }
708    }
709
710    /// Gets the `ty::FnDef` from an operand if it's a constant function item.
711    ///
712    /// While this is unlikely in general, it's the normal case of what you'll
713    /// find as the `func` in a [`TerminatorKind::Call`].
714    pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> {
715        let const_ty = self.constant()?.const_.ty();
716        if let ty::FnDef(def_id, args) = *const_ty.kind() {
717            Some((def_id, args.no_bound_vars().unwrap()))
718        } else {
719            None
720        }
721    }
722
723    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
724    where
725        D: ?Sized + HasLocalDecls<'tcx>,
726    {
727        match self {
728            &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
729            Operand::Constant(c) => c.const_.ty(),
730            Operand::RuntimeChecks(_) => tcx.types.bool,
731        }
732    }
733
734    pub fn span<D>(&self, local_decls: &D) -> Span
735    where
736        D: ?Sized + HasLocalDecls<'tcx>,
737    {
738        match self {
739            &Operand::Copy(ref l) | &Operand::Move(ref l) => {
740                local_decls.local_decls()[l.local].source_info.span
741            }
742            Operand::Constant(c) => c.span,
743            // User code should not contain this operand, so we should not need this span.
744            Operand::RuntimeChecks(_) => DUMMY_SP,
745        }
746    }
747}
748
749impl<'tcx> ConstOperand<'tcx> {
750    pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
751        match self.const_.try_to_scalar() {
752            Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance.alloc_id()) {
753                GlobalAlloc::Static(def_id) => {
754                    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));
755                    Some(def_id)
756                }
757                _ => None,
758            },
759            _ => None,
760        }
761    }
762
763    #[inline]
764    pub fn ty(&self) -> Ty<'tcx> {
765        self.const_.ty()
766    }
767}
768
769///////////////////////////////////////////////////////////////////////////
770// Rvalues
771
772impl<'tcx> Rvalue<'tcx> {
773    /// Returns true if rvalue can be safely removed when the result is unused.
774    #[inline]
775    pub fn is_safe_to_remove(&self) -> bool {
776        match self {
777            // Pointer to int casts may be side-effects due to exposing the provenance.
778            // While the model is undecided, we should be conservative. See
779            // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
780            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => false,
781
782            Rvalue::Use(_, _)
783            | Rvalue::CopyForDeref(_)
784            | Rvalue::Repeat(_, _)
785            | Rvalue::Ref(_, _, _)
786            | Rvalue::Reborrow(_, _, _)
787            | Rvalue::ThreadLocalRef(_)
788            | Rvalue::RawPtr(_, _)
789            | Rvalue::Cast(
790                CastKind::IntToInt
791                | CastKind::FloatToInt
792                | CastKind::FloatToFloat
793                | CastKind::IntToFloat
794                | CastKind::FnPtrToPtr
795                | CastKind::PtrToPtr
796                | CastKind::PointerCoercion(_, _)
797                | CastKind::PointerWithExposedProvenance
798                | CastKind::Transmute
799                | CastKind::BoxDerefTransmute
800                | CastKind::Subtype,
801                _,
802                _,
803            )
804            | Rvalue::BinaryOp(_, _)
805            | Rvalue::UnaryOp(_, _)
806            | Rvalue::Discriminant(_)
807            | Rvalue::Aggregate(_, _)
808            | Rvalue::WrapUnsafeBinder(_, _) => true,
809        }
810    }
811
812    /// Returns true if rvalue is a generic Reborrow coercion (usage of Reborrow or CoerceShared
813    /// trait).
814    pub fn is_generic_reborrow(&self) -> bool {
815        #[allow(non_exhaustive_omitted_patterns)] match self {
    Self::Reborrow(..) => true,
    _ => false,
}matches!(self, Self::Reborrow(..))
816    }
817
818    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
819    where
820        D: ?Sized + HasLocalDecls<'tcx>,
821    {
822        match *self {
823            Rvalue::Use(ref operand, _) => operand.ty(local_decls, tcx),
824            Rvalue::Repeat(ref operand, count) => {
825                Ty::new_array_with_const_len(tcx, operand.ty(local_decls, tcx), count)
826            }
827            Rvalue::ThreadLocalRef(did) => tcx.thread_local_ptr_ty(did),
828            Rvalue::Ref(reg, bk, ref place) => {
829                let place_ty = place.ty(local_decls, tcx).ty;
830                Ty::new_ref(tcx, reg, place_ty, bk.to_mutbl_lossy())
831            }
832            Rvalue::Reborrow(target, _, _) => target,
833            Rvalue::RawPtr(kind, ref place) => {
834                let place_ty = place.ty(local_decls, tcx).ty;
835                Ty::new_ptr(tcx, place_ty, kind.to_mutbl_lossy())
836            }
837            Rvalue::Cast(.., ty) => ty,
838            Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
839                let lhs_ty = lhs.ty(local_decls, tcx);
840                let rhs_ty = rhs.ty(local_decls, tcx);
841                op.ty(tcx, lhs_ty, rhs_ty)
842            }
843            Rvalue::UnaryOp(op, ref operand) => {
844                let arg_ty = operand.ty(local_decls, tcx);
845                op.ty(tcx, arg_ty)
846            }
847            Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
848            Rvalue::Aggregate(ref ak, ref ops) => match **ak {
849                AggregateKind::Array(ty) => Ty::new_array(tcx, ty, ops.len() as u64),
850                AggregateKind::Tuple => {
851                    Ty::new_tup_from_iter(tcx, ops.iter().map(|op| op.ty(local_decls, tcx)))
852                }
853                AggregateKind::Adt(did, _, args, _, _) => {
854                    tcx.type_of(did).instantiate(tcx, args).skip_norm_wip()
855                }
856                AggregateKind::Closure(did, args) => Ty::new_closure(tcx, did, args),
857                AggregateKind::Coroutine(did, args) => Ty::new_coroutine(tcx, did, args),
858                AggregateKind::CoroutineClosure(did, args) => {
859                    Ty::new_coroutine_closure(tcx, did, args)
860                }
861                AggregateKind::RawPtr(ty, mutability) => Ty::new_ptr(tcx, ty, mutability),
862            },
863            Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
864            Rvalue::WrapUnsafeBinder(_, ty) => ty,
865        }
866    }
867}
868
869impl BorrowKind {
870    pub fn mutability(&self) -> Mutability {
871        match *self {
872            BorrowKind::Shared | BorrowKind::Fake(_) => Mutability::Not,
873            BorrowKind::Mut { .. } => Mutability::Mut,
874        }
875    }
876
877    /// Returns whether borrows represented by this kind are allowed to be split into separate
878    /// Reservation and Activation phases.
879    pub fn is_two_phase_borrow(&self) -> bool {
880        match *self {
881            BorrowKind::Shared
882            | BorrowKind::Fake(_)
883            | BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::ClosureCapture } => {
884                false
885            }
886            BorrowKind::Mut { kind: MutBorrowKind::TwoPhaseBorrow } => true,
887        }
888    }
889
890    pub fn to_mutbl_lossy(self) -> hir::Mutability {
891        match self {
892            BorrowKind::Mut { .. } => hir::Mutability::Mut,
893            BorrowKind::Shared => hir::Mutability::Not,
894
895            // We have no type corresponding to a shallow borrow, so use
896            // `&` as an approximation.
897            BorrowKind::Fake(_) => hir::Mutability::Not,
898        }
899    }
900}
901
902impl<'tcx> UnOp {
903    pub fn ty(&self, tcx: TyCtxt<'tcx>, arg_ty: Ty<'tcx>) -> Ty<'tcx> {
904        match self {
905            UnOp::Not | UnOp::Neg => arg_ty,
906            UnOp::PtrMetadata => arg_ty.pointee_metadata_ty_or_projection(tcx),
907        }
908    }
909}
910
911impl<'tcx> BinOp {
912    pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
913        // FIXME: handle SIMD correctly
914        match self {
915            &BinOp::Add
916            | &BinOp::AddUnchecked
917            | &BinOp::Sub
918            | &BinOp::SubUnchecked
919            | &BinOp::Mul
920            | &BinOp::MulUnchecked
921            | &BinOp::Div
922            | &BinOp::Rem
923            | &BinOp::BitXor
924            | &BinOp::BitAnd
925            | &BinOp::BitOr => {
926                // these should be integers or floats of the same size.
927                {
    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);
928                lhs_ty
929            }
930            &BinOp::AddWithOverflow | &BinOp::SubWithOverflow | &BinOp::MulWithOverflow => {
931                // these should be integers of the same size.
932                {
    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);
933                Ty::new_tup(tcx, &[lhs_ty, tcx.types.bool])
934            }
935            &BinOp::Shl
936            | &BinOp::ShlUnchecked
937            | &BinOp::Shr
938            | &BinOp::ShrUnchecked
939            | &BinOp::Offset => {
940                lhs_ty // lhs_ty can be != rhs_ty
941            }
942            &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
943                tcx.types.bool
944            }
945            &BinOp::Cmp => {
946                // these should be integer-like types of the same size.
947                {
    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);
948                tcx.ty_ordering_enum(DUMMY_SP)
949            }
950        }
951    }
952    pub(crate) fn to_hir_binop(self) -> hir::BinOpKind {
953        match self {
954            // HIR `+`/`-`/`*` can map to either of these MIR BinOp, depending
955            // on whether overflow checks are enabled or not.
956            BinOp::Add | BinOp::AddWithOverflow => hir::BinOpKind::Add,
957            BinOp::Sub | BinOp::SubWithOverflow => hir::BinOpKind::Sub,
958            BinOp::Mul | BinOp::MulWithOverflow => hir::BinOpKind::Mul,
959            BinOp::Div => hir::BinOpKind::Div,
960            BinOp::Rem => hir::BinOpKind::Rem,
961            BinOp::BitXor => hir::BinOpKind::BitXor,
962            BinOp::BitAnd => hir::BinOpKind::BitAnd,
963            BinOp::BitOr => hir::BinOpKind::BitOr,
964            BinOp::Shl => hir::BinOpKind::Shl,
965            BinOp::Shr => hir::BinOpKind::Shr,
966            BinOp::Eq => hir::BinOpKind::Eq,
967            BinOp::Ne => hir::BinOpKind::Ne,
968            BinOp::Lt => hir::BinOpKind::Lt,
969            BinOp::Gt => hir::BinOpKind::Gt,
970            BinOp::Le => hir::BinOpKind::Le,
971            BinOp::Ge => hir::BinOpKind::Ge,
972            // We don't have HIR syntax for these.
973            BinOp::Cmp
974            | BinOp::AddUnchecked
975            | BinOp::SubUnchecked
976            | BinOp::MulUnchecked
977            | BinOp::ShlUnchecked
978            | BinOp::ShrUnchecked
979            | BinOp::Offset => {
980                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
981            }
982        }
983    }
984
985    /// If this is a `FooWithOverflow`, return `Some(Foo)`.
986    pub fn overflowing_to_wrapping(self) -> Option<BinOp> {
987        Some(match self {
988            BinOp::AddWithOverflow => BinOp::Add,
989            BinOp::SubWithOverflow => BinOp::Sub,
990            BinOp::MulWithOverflow => BinOp::Mul,
991            _ => return None,
992        })
993    }
994
995    /// Returns whether this is a `FooWithOverflow`
996    pub fn is_overflowing(self) -> bool {
997        self.overflowing_to_wrapping().is_some()
998    }
999
1000    /// If this is a `Foo`, return `Some(FooWithOverflow)`.
1001    pub fn wrapping_to_overflowing(self) -> Option<BinOp> {
1002        Some(match self {
1003            BinOp::Add => BinOp::AddWithOverflow,
1004            BinOp::Sub => BinOp::SubWithOverflow,
1005            BinOp::Mul => BinOp::MulWithOverflow,
1006            _ => return None,
1007        })
1008    }
1009}
1010
1011impl From<Mutability> for RawPtrKind {
1012    fn from(other: Mutability) -> Self {
1013        match other {
1014            Mutability::Mut => RawPtrKind::Mut,
1015            Mutability::Not => RawPtrKind::Const,
1016        }
1017    }
1018}
1019
1020impl RawPtrKind {
1021    pub fn is_fake(self) -> bool {
1022        match self {
1023            RawPtrKind::Mut | RawPtrKind::Const => false,
1024            RawPtrKind::FakeForPtrMetadata => true,
1025        }
1026    }
1027
1028    pub fn to_mutbl_lossy(self) -> Mutability {
1029        match self {
1030            RawPtrKind::Mut => Mutability::Mut,
1031            RawPtrKind::Const => Mutability::Not,
1032
1033            // We have no type corresponding to a fake borrow, so use
1034            // `*const` as an approximation.
1035            RawPtrKind::FakeForPtrMetadata => Mutability::Not,
1036        }
1037    }
1038
1039    pub fn ptr_str(self) -> &'static str {
1040        match self {
1041            RawPtrKind::Mut => "mut",
1042            RawPtrKind::Const => "const",
1043            RawPtrKind::FakeForPtrMetadata => "const (fake)",
1044        }
1045    }
1046}
1047
1048// This collection is almost always empty, so we
1049// use thin representation and optimize all methods
1050// for that by inlining the empty check
1051// and outlining the rest. Note that Option is
1052// technically not needed, because empty ThinVec
1053// points to a static singleton, this version performed
1054// better in our benchmarks
1055#[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) {
                let StmtDebugInfos(ref __binding_0) = *self;
                ::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)]
1056pub struct StmtDebugInfos<'tcx>(Option<ThinVec<StmtDebugInfo<'tcx>>>);
1057
1058impl<'tcx> StmtDebugInfos<'tcx> {
1059    pub fn push(&mut self, debuginfo: StmtDebugInfo<'tcx>) {
1060        self.0.get_or_insert_default().push(debuginfo);
1061    }
1062    #[inline]
1063    pub fn drop_debuginfo(&mut self) {
1064        match &mut self.0 {
1065            None => (),
1066            Some(v) => outline(move || v.clear()),
1067        }
1068    }
1069
1070    #[inline]
1071    pub fn is_empty(&self) -> bool {
1072        match &self.0 {
1073            None => true,
1074            Some(v) => outline(move || v.is_empty()),
1075        }
1076    }
1077    #[inline]
1078    pub fn prepend(&mut self, debuginfos: &mut Self) {
1079        if debuginfos.is_empty() {
1080            return;
1081        };
1082        outline(move || {
1083            debuginfos.append(self);
1084            std::mem::swap(debuginfos, self);
1085        })
1086    }
1087    #[inline]
1088    pub fn append(&mut self, debuginfos: &mut Self) {
1089        if debuginfos.is_empty() {
1090            return;
1091        };
1092        outline(move || self.0.get_or_insert_default().append(debuginfos.0.as_mut().unwrap()));
1093    }
1094    #[inline]
1095    pub fn extend(&mut self, debuginfos: &Self) {
1096        if debuginfos.is_empty() {
1097            return;
1098        };
1099        outline(move || self.0.get_or_insert_default().extend_from_slice(debuginfos.as_slice()))
1100    }
1101
1102    #[inline]
1103    pub fn as_slice(&self) -> &[StmtDebugInfo<'tcx>] {
1104        match &self.0 {
1105            None => &[],
1106            Some(items) => outline(move || items.as_slice()),
1107        }
1108    }
1109
1110    #[inline]
1111    pub fn as_mut_slice(&mut self) -> &mut [StmtDebugInfo<'tcx>] {
1112        match &mut self.0 {
1113            None => &mut [],
1114            Some(items) => outline(move || items.as_mut_slice()),
1115        }
1116    }
1117    #[inline]
1118    pub fn retain_locals(&mut self, locals: &DenseBitSet<Local>) {
1119        match &mut self.0 {
1120            None => (),
1121            Some(items) => outline(move || {
1122                items.retain(|debuginfo| match debuginfo {
1123                    StmtDebugInfo::AssignRef(local, _) | StmtDebugInfo::InvalidAssign(local) => {
1124                        locals.contains(*local)
1125                    }
1126                })
1127            }),
1128        }
1129    }
1130}
1131
1132impl<'tcx> ops::Deref for StmtDebugInfos<'tcx> {
1133    type Target = [StmtDebugInfo<'tcx>];
1134
1135    #[inline]
1136    fn deref(&self) -> &Self::Target {
1137        self.as_slice()
1138    }
1139}
1140
1141impl<'tcx> ops::DerefMut for StmtDebugInfos<'tcx> {
1142    #[inline]
1143    fn deref_mut(&mut self) -> &mut Self::Target {
1144        self.as_mut_slice()
1145    }
1146}
1147
1148#[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)]
1149pub enum StmtDebugInfo<'tcx> {
1150    AssignRef(Local, Place<'tcx>),
1151    InvalidAssign(Local),
1152}