Skip to main content

rustc_transmute/maybe_transmutable/
mod.rs

1use tracing::{debug, instrument, trace};
2
3pub(crate) mod query_context;
4#[cfg(test)]
5mod tests;
6
7use crate::layout::{self, Def, Dfa, Reference, Tree, dfa, union};
8use crate::maybe_transmutable::query_context::QueryContext;
9use crate::{Answer, Condition, Map, Reason};
10
11pub(crate) struct MaybeTransmutableQuery<L, C>
12where
13    C: QueryContext,
14{
15    src: L,
16    dst: L,
17    assume: crate::Assume,
18    context: C,
19}
20
21impl<L, C> MaybeTransmutableQuery<L, C>
22where
23    C: QueryContext,
24{
25    pub(crate) fn new(src: L, dst: L, assume: crate::Assume, context: C) -> Self {
26        Self { src, dst, assume, context }
27    }
28}
29
30// FIXME: Nix this cfg, so we can write unit tests independently of rustc
31#[cfg(feature = "rustc")]
32mod rustc {
33    use rustc_middle::ty::layout::LayoutCx;
34    use rustc_middle::ty::{Ty, TyCtxt, TypingEnv};
35
36    use super::*;
37    use crate::layout::tree::rustc::Err;
38
39    impl<'tcx> MaybeTransmutableQuery<Ty<'tcx>, TyCtxt<'tcx>> {
40        /// This method begins by converting `src` and `dst` from `Ty`s to `Tree`s,
41        /// then computes an answer using those trees.
42        #[allow(clippy :: suspicious_else_formatting)]
{
    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("answer",
                                    "rustc_transmute::maybe_transmutable::rustc",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(42u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable::rustc"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("src")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("src");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("dst")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("dst");
                                                        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.src)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.dst)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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:
                    Answer<<TyCtxt<'tcx> as QueryContext>::Region,
                    <TyCtxt<'tcx> as QueryContext>::Type> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let Self { src, dst, assume, context } = self;
            let layout_cx =
                LayoutCx::new(context, TypingEnv::fully_monomorphized());
            let src = Tree::from_ty(src, layout_cx);
            let dst = Tree::from_ty(dst, layout_cx);
            match (src, dst) {
                (Err(Err::TypeError(_)), _) | (_, Err(Err::TypeError(_))) => {
                    Answer::No(Reason::TypeError)
                }
                (Err(Err::UnknownLayout), _) =>
                    Answer::No(Reason::SrcLayoutUnknown),
                (_, Err(Err::UnknownLayout)) =>
                    Answer::No(Reason::DstLayoutUnknown),
                (Err(Err::NotYetSupported), _) =>
                    Answer::No(Reason::SrcIsNotYetSupported),
                (_, Err(Err::NotYetSupported)) =>
                    Answer::No(Reason::DstIsNotYetSupported),
                (Err(Err::SizeOverflow), _) =>
                    Answer::No(Reason::SrcSizeOverflow),
                (_, Err(Err::SizeOverflow)) =>
                    Answer::No(Reason::DstSizeOverflow),
                (Ok(src), Ok(dst)) =>
                    MaybeTransmutableQuery {
                            src,
                            dst,
                            assume,
                            context,
                        }.answer(),
            }
        }
    }
}#[instrument(level = "debug", skip(self), fields(src = ?self.src, dst = ?self.dst))]
43        pub(crate) fn answer(
44            self,
45        ) -> Answer<<TyCtxt<'tcx> as QueryContext>::Region, <TyCtxt<'tcx> as QueryContext>::Type>
46        {
47            let Self { src, dst, assume, context } = self;
48
49            let layout_cx = LayoutCx::new(context, TypingEnv::fully_monomorphized());
50
51            // Convert `src` and `dst` from their rustc representations, to `Tree`-based
52            // representations.
53            let src = Tree::from_ty(src, layout_cx);
54            let dst = Tree::from_ty(dst, layout_cx);
55
56            match (src, dst) {
57                (Err(Err::TypeError(_)), _) | (_, Err(Err::TypeError(_))) => {
58                    Answer::No(Reason::TypeError)
59                }
60                (Err(Err::UnknownLayout), _) => Answer::No(Reason::SrcLayoutUnknown),
61                (_, Err(Err::UnknownLayout)) => Answer::No(Reason::DstLayoutUnknown),
62                (Err(Err::NotYetSupported), _) => Answer::No(Reason::SrcIsNotYetSupported),
63                (_, Err(Err::NotYetSupported)) => Answer::No(Reason::DstIsNotYetSupported),
64                (Err(Err::SizeOverflow), _) => Answer::No(Reason::SrcSizeOverflow),
65                (_, Err(Err::SizeOverflow)) => Answer::No(Reason::DstSizeOverflow),
66                (Ok(src), Ok(dst)) => MaybeTransmutableQuery { src, dst, assume, context }.answer(),
67            }
68        }
69    }
70}
71
72impl<C>
73    MaybeTransmutableQuery<
74        Tree<<C as QueryContext>::Def, <C as QueryContext>::Region, <C as QueryContext>::Type>,
75        C,
76    >
77where
78    C: QueryContext,
79{
80    /// Answers whether a `Tree` is transmutable into another `Tree`.
81    ///
82    /// This method begins by de-def'ing `src` and `dst`, and prunes private paths from `dst`,
83    /// then converts `src` and `dst` to `Dfa`s, and computes an answer using those DFAs.
84    #[inline(always)]
85    #[allow(clippy :: suspicious_else_formatting)]
{
    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("answer",
                                    "rustc_transmute::maybe_transmutable",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(85u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("src")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("src");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("dst")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("dst");
                                                        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.src)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.dst)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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:
                    Answer<<C as QueryContext>::Region,
                    <C as QueryContext>::Type> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let Self { src, dst, assume, context } = self;
            let src = src.prune(&|_def| false);
            if src.is_inhabited() && !dst.is_inhabited() {
                return Answer::No(Reason::DstUninhabited);
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_transmute/src/maybe_transmutable/mod.rs:100",
                                    "rustc_transmute::maybe_transmutable",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(100u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                                    ::tracing_core::field::FieldSet::new(&["message",
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("src")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("src");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::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(&format_args!("pruned src")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let dst =
                if assume.safety {
                    dst.prune(&|_def| false)
                } else { dst.prune(&|def| def.has_safety_invariants()) };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_transmute/src/maybe_transmutable/mod.rs:113",
                                    "rustc_transmute::maybe_transmutable",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(113u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                                    ::tracing_core::field::FieldSet::new(&["message",
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("dst")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("dst");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::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(&format_args!("pruned dst")
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dst)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let src =
                match Dfa::from_tree(src) {
                    Ok(src) => src,
                    Err(layout::Uninhabited) => return Answer::Yes,
                };
            let dst =
                match Dfa::from_tree(dst) {
                    Ok(dst) => dst,
                    Err(layout::Uninhabited) =>
                        return Answer::No(Reason::DstMayHaveSafetyInvariants),
                };
            MaybeTransmutableQuery { src, dst, assume, context }.answer()
        }
    }
}#[instrument(level = "debug", skip(self), fields(src = ?self.src, dst = ?self.dst))]
86    pub(crate) fn answer(self) -> Answer<<C as QueryContext>::Region, <C as QueryContext>::Type> {
87        let Self { src, dst, assume, context } = self;
88
89        // Unconditionally remove all `Def` nodes from `src`, without pruning away the
90        // branches they appear in. This is valid to do for value-to-value
91        // transmutations, but not for `&mut T` to `&mut U`; we will need to be
92        // more sophisticated to handle transmutations between mutable
93        // references.
94        let src = src.prune(&|_def| false);
95
96        if src.is_inhabited() && !dst.is_inhabited() {
97            return Answer::No(Reason::DstUninhabited);
98        }
99
100        trace!(?src, "pruned src");
101
102        // Remove all `Def` nodes from `dst`, additionally...
103        let dst = if assume.safety {
104            // ...if safety is assumed, don't check if they carry safety
105            // invariants; retain all paths.
106            dst.prune(&|_def| false)
107        } else {
108            // ...otherwise, prune away all paths with safety invariants from
109            // the `Dst` layout.
110            dst.prune(&|def| def.has_safety_invariants())
111        };
112
113        trace!(?dst, "pruned dst");
114
115        // Convert `src` from a tree-based representation to an DFA-based
116        // representation. If the conversion fails because `src` is uninhabited,
117        // conclude that the transmutation is acceptable, because instances of
118        // the `src` type do not exist.
119        let src = match Dfa::from_tree(src) {
120            Ok(src) => src,
121            Err(layout::Uninhabited) => return Answer::Yes,
122        };
123
124        // Convert `dst` from a tree-based representation to an DFA-based
125        // representation. If the conversion fails because `src` is uninhabited,
126        // conclude that the transmutation is unacceptable. Valid instances of
127        // the `dst` type do not exist, either because it's genuinely
128        // uninhabited, or because there are no branches of the tree that are
129        // free of safety invariants.
130        let dst = match Dfa::from_tree(dst) {
131            Ok(dst) => dst,
132            Err(layout::Uninhabited) => return Answer::No(Reason::DstMayHaveSafetyInvariants),
133        };
134
135        MaybeTransmutableQuery { src, dst, assume, context }.answer()
136    }
137}
138
139impl<C> MaybeTransmutableQuery<Dfa<<C as QueryContext>::Region, <C as QueryContext>::Type>, C>
140where
141    C: QueryContext,
142{
143    /// Answers whether a `Dfa` is transmutable into another `Dfa`.
144    pub(crate) fn answer(self) -> Answer<<C as QueryContext>::Region, <C as QueryContext>::Type> {
145        self.answer_memo(&mut Map::default(), self.src.start, self.dst.start)
146    }
147
148    #[inline(always)]
149    #[allow(clippy :: suspicious_else_formatting)]
{
    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("answer_memo",
                                    "rustc_transmute::maybe_transmutable",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(149u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cache")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cache");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("src_state")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("src_state");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("dst_state")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("dst_state");
                                                        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(&cache)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src_state)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dst_state)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[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:
                    Answer<<C as QueryContext>::Region,
                    <C as QueryContext>::Type> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(answer) = cache.get(&(src_state, dst_state)) {
                answer.clone()
            } else {
                let answer = self.answer_impl(cache, src_state, dst_state);
                if let Some(..) =
                        cache.insert((src_state, dst_state), answer.clone()) {
                    {
                        ::core::panicking::panic_fmt(format_args!("failed to correctly cache transmutability"));
                    }
                }
                answer
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
150    fn answer_memo(
151        &self,
152        cache: &mut Map<
153            (dfa::State, dfa::State),
154            Answer<<C as QueryContext>::Region, <C as QueryContext>::Type>,
155        >,
156        src_state: dfa::State,
157        dst_state: dfa::State,
158    ) -> Answer<<C as QueryContext>::Region, <C as QueryContext>::Type> {
159        if let Some(answer) = cache.get(&(src_state, dst_state)) {
160            answer.clone()
161        } else {
162            let answer = self.answer_impl(cache, src_state, dst_state);
163            if let Some(..) = cache.insert((src_state, dst_state), answer.clone()) {
164                panic!("failed to correctly cache transmutability")
165            }
166            answer
167        }
168    }
169
170    fn answer_impl(
171        &self,
172        cache: &mut Map<
173            (dfa::State, dfa::State),
174            Answer<<C as QueryContext>::Region, <C as QueryContext>::Type>,
175        >,
176        src_state: dfa::State,
177        dst_state: dfa::State,
178    ) -> Answer<<C as QueryContext>::Region, <C as QueryContext>::Type> {
179        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_transmute/src/maybe_transmutable/mod.rs:179",
                        "rustc_transmute::maybe_transmutable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(179u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("src_state")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("src_state");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("dst_state")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("dst_state");
                                            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(&src_state)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dst_state)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?src_state, ?dst_state);
180        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_transmute/src/maybe_transmutable/mod.rs:180",
                        "rustc_transmute::maybe_transmutable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(180u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("src")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("src");
                                            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(&self.src)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(src = ?self.src);
181        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_transmute/src/maybe_transmutable/mod.rs:181",
                        "rustc_transmute::maybe_transmutable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(181u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("dst")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("dst");
                                            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(&self.dst)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(dst = ?self.dst);
182        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_transmute/src/maybe_transmutable/mod.rs:182",
                        "rustc_transmute::maybe_transmutable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(182u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("src_transitions_len")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("src_transitions_len");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("dst_transitions_len")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("dst_transitions_len");
                                            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(&self.src.transitions.len()
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&self.dst.transitions.len()
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
183            src_transitions_len = self.src.transitions.len(),
184            dst_transitions_len = self.dst.transitions.len()
185        );
186        if dst_state == self.dst.accept {
187            // truncation: `size_of(Src) >= size_of(Dst)`
188            //
189            // Why is truncation OK to do? Because even though the Src is bigger, all we care about
190            // is whether we have enough data for the Dst to be valid in accordance with what its
191            // type dictates.
192            // For example, in a u8 to `()` transmutation, we have enough data available from the u8
193            // to transmute it to a `()` (though in this case does `()` really need any data to
194            // begin with? It doesn't). Same thing with u8 to fieldless struct.
195            // Now then, why is something like u8 to bool not allowed? That is not because the bool
196            // is smaller in size, but rather because those 2 bits that we are re-interpreting from
197            // the u8 could introduce invalid states for the bool type.
198            //
199            // So, if it's possible to transmute to a smaller Dst by truncating, and we can guarantee
200            // that none of the actually-used data can introduce an invalid state for Dst's type, we
201            // are able to safely transmute, even with truncation.
202            Answer::Yes
203        } else if src_state == self.src.accept {
204            // extension: `size_of(Src) <= size_of(Dst)`
205            if let Some(dst_state_prime) = self.dst.get_uninit_edge_dst(dst_state) {
206                self.answer_memo(cache, src_state, dst_state_prime)
207            } else {
208                Answer::No(Reason::DstIsTooBig)
209            }
210        } else {
211            let src_quantifier = if self.assume.validity {
212                // if the compiler may assume that the programmer is doing additional validity checks,
213                // (e.g.: that `src != 3u8` when the destination type is `bool`)
214                // then there must exist at least one transition out of `src_state` such that the transmute is viable...
215                Quantifier::ThereExists
216            } else {
217                // if the compiler cannot assume that the programmer is doing additional validity checks,
218                // then for all transitions out of `src_state`, such that the transmute is viable...
219                // then there must exist at least one transition out of `dst_state` such that the transmute is viable...
220                Quantifier::ForAll
221            };
222
223            let bytes_answer = src_quantifier.apply(
224                union(self.src.bytes_from(src_state), self.dst.bytes_from(dst_state)).filter_map(
225                    |(_range, (src_state_prime, dst_state_prime))| {
226                        match (src_state_prime, dst_state_prime) {
227                            // No matching transitions in `src`. Skip.
228                            (None, _) => None,
229                            // No matching transitions in `dst`. Fail.
230                            (Some(_), None) => Some(Answer::No(Reason::DstIsBitIncompatible)),
231                            // Matching transitions. Continue with successor states.
232                            (Some(src_state_prime), Some(dst_state_prime)) => {
233                                Some(self.answer_memo(cache, src_state_prime, dst_state_prime))
234                            }
235                        }
236                    },
237                ),
238            );
239
240            // The below early returns reflect how this code would behave:
241            //   if self.assume.validity {
242            //       or(bytes_answer, refs_answer)
243            //   } else {
244            //       and(bytes_answer, refs_answer)
245            //   }
246            // ...if `refs_answer` was computed lazily. The below early
247            // returns can be deleted without impacting the correctness of
248            // the algorithm; only its performance.
249            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_transmute/src/maybe_transmutable/mod.rs:249",
                        "rustc_transmute::maybe_transmutable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_transmute/src/maybe_transmutable/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(249u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_transmute::maybe_transmutable"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("bytes_answer")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("bytes_answer");
                                            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(&bytes_answer)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?bytes_answer);
250            match bytes_answer {
251                Answer::No(_) if !self.assume.validity => return bytes_answer,
252                Answer::Yes if self.assume.validity => return bytes_answer,
253                _ => {}
254            };
255
256            let refs_answer = src_quantifier.apply(
257                // for each reference transition out of `src_state`...
258                self.src.refs_from(src_state).map(|(src_ref, src_state_prime)| {
259                    // ...there exists a reference transition out of `dst_state`...
260                    Quantifier::ThereExists.apply(self.dst.refs_from(dst_state).map(
261                        |(dst_ref, dst_state_prime)| {
262                            if !src_ref.is_mut && dst_ref.is_mut {
263                                Answer::No(Reason::DstIsMoreUnique)
264                            } else if !self.assume.alignment
265                                && src_ref.referent_align < dst_ref.referent_align
266                            {
267                                Answer::No(Reason::DstHasStricterAlignment {
268                                    src_min_align: src_ref.referent_align,
269                                    dst_min_align: dst_ref.referent_align,
270                                })
271                            } else if dst_ref.referent_size > src_ref.referent_size {
272                                Answer::No(Reason::DstRefIsTooBig {
273                                    src: src_ref.referent,
274                                    src_size: src_ref.referent_size,
275                                    dst: dst_ref.referent,
276                                    dst_size: dst_ref.referent_size,
277                                })
278                            } else {
279                                let mut conditions = Vec::with_capacity(4);
280                                let mut is_transmutable =
281                                    |src: Reference<_, _>, dst: Reference<_, _>| {
282                                        conditions.push(Condition::Transmutable {
283                                            src: src.referent,
284                                            dst: dst.referent,
285                                        });
286                                        if !self.assume.lifetimes {
287                                            conditions.push(Condition::Outlives {
288                                                long: src.region,
289                                                short: dst.region,
290                                            });
291                                        }
292                                    };
293
294                                is_transmutable(src_ref, dst_ref);
295
296                                if dst_ref.is_mut {
297                                    is_transmutable(dst_ref, src_ref);
298                                } else {
299                                    conditions.push(Condition::Immutable { ty: dst_ref.referent });
300                                }
301
302                                Answer::If(Condition::IfAll(conditions)).and(self.answer_memo(
303                                    cache,
304                                    src_state_prime,
305                                    dst_state_prime,
306                                ))
307                            }
308                        },
309                    ))
310                }),
311            );
312
313            if self.assume.validity {
314                bytes_answer.or(refs_answer)
315            } else {
316                bytes_answer.and(refs_answer)
317            }
318        }
319    }
320}
321
322impl<R, T> Answer<R, T> {
323    fn and(self, rhs: Answer<R, T>) -> Answer<R, T> {
324        let lhs = self;
325        match (lhs, rhs) {
326            // If both are errors, then we should return the more specific one
327            (Answer::No(Reason::DstIsBitIncompatible), Answer::No(reason))
328            | (Answer::No(reason), Answer::No(_))
329            // If either is an error, return it
330            | (Answer::No(reason), _) | (_, Answer::No(reason)) => Answer::No(reason),
331            // If only one side has a condition, pass it along
332            (Answer::Yes, other) | (other, Answer::Yes) => other,
333            // If both sides have IfAll conditions, merge them
334            (Answer::If(Condition::IfAll(mut lhs)), Answer::If(Condition::IfAll(ref mut rhs))) => {
335                lhs.append(rhs);
336                Answer::If(Condition::IfAll(lhs))
337            }
338            // If only one side is an IfAll, add the other Condition to it
339            (Answer::If(cond), Answer::If(Condition::IfAll(mut conds)))
340            | (Answer::If(Condition::IfAll(mut conds)), Answer::If(cond)) => {
341                conds.push(cond);
342                Answer::If(Condition::IfAll(conds))
343            }
344            // Otherwise, both lhs and rhs conditions can be combined in a parent IfAll
345            (Answer::If(lhs), Answer::If(rhs)) => Answer::If(Condition::IfAll(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [lhs, rhs]))vec![lhs, rhs])),
346        }
347    }
348
349    fn or(self, rhs: Answer<R, T>) -> Answer<R, T> {
350        let lhs = self;
351        match (lhs, rhs) {
352            // If both are errors, then we should return the more specific one
353            (Answer::No(Reason::DstIsBitIncompatible), Answer::No(reason))
354            | (Answer::No(reason), Answer::No(_)) => Answer::No(reason),
355            // Otherwise, errors can be ignored for the rest of the pattern matching
356            (Answer::No(_), other) | (other, Answer::No(_)) => other.or(Answer::Yes),
357            // If only one side has a condition, pass it along
358            (Answer::Yes, other) | (other, Answer::Yes) => other,
359            // If both sides have IfAny conditions, merge them
360            (Answer::If(Condition::IfAny(mut lhs)), Answer::If(Condition::IfAny(ref mut rhs))) => {
361                lhs.append(rhs);
362                Answer::If(Condition::IfAny(lhs))
363            }
364            // If only one side is an IfAny, add the other Condition to it
365            (Answer::If(cond), Answer::If(Condition::IfAny(mut conds)))
366            | (Answer::If(Condition::IfAny(mut conds)), Answer::If(cond)) => {
367                conds.push(cond);
368                Answer::If(Condition::IfAny(conds))
369            }
370            // Otherwise, both lhs and rhs conditions can be combined in a parent IfAny
371            (Answer::If(lhs), Answer::If(rhs)) => Answer::If(Condition::IfAny(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [lhs, rhs]))vec![lhs, rhs])),
372        }
373    }
374}
375
376enum Quantifier {
377    ThereExists,
378    ForAll,
379}
380
381impl Quantifier {
382    fn apply<R, T, I>(&self, iter: I) -> Answer<R, T>
383    where
384        R: layout::Region,
385        T: layout::Type,
386        I: IntoIterator<Item = Answer<R, T>>,
387    {
388        use std::ops::ControlFlow::{Break, Continue};
389
390        let (init, try_fold_f): (_, fn(_, _) -> _) = match self {
391            Self::ThereExists => {
392                (Answer::No(Reason::DstIsBitIncompatible), |accum: Answer<R, T>, next| match accum
393                    .or(next)
394                {
395                    Answer::Yes => Break(Answer::Yes),
396                    maybe => Continue(maybe),
397                })
398            }
399            Self::ForAll => (Answer::Yes, |accum: Answer<R, T>, next| {
400                let answer = accum.and(next);
401                match answer {
402                    Answer::No(_) => Break(answer),
403                    maybe => Continue(maybe),
404                }
405            }),
406        };
407
408        let (Continue(result) | Break(result)) = iter.into_iter().try_fold(init, try_fold_f);
409        result
410    }
411}