Skip to main content

rustc_mir_transform/
shim.rs

1use std::{assert_matches, fmt, iter};
2
3use rustc_abi::{ExternAbi, FIRST_VARIANT, FieldIdx, VariantIdx};
4use rustc_attr_ir::lang_items::LangItem;
5use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
6use rustc_hir as hir;
7use rustc_hir::def_id::DefId;
8use rustc_index::{Idx, IndexVec};
9use rustc_middle::mir::visit::{MutVisitor, PlaceContext};
10use rustc_middle::mir::*;
11use rustc_middle::query::Providers;
12use rustc_middle::ty::{
13    self, CoroutineArgs, CoroutineArgsExt, EarlyBinder, GenericArgs, Ty, TyCtxt, Unnormalized,
14};
15use rustc_span::{DUMMY_SP, Span, Spanned, bug, dummy_spanned, span_bug};
16use tracing::{debug, instrument};
17
18use crate::deref_separator::deref_finder;
19use crate::elaborate_drop::{DropElaborator, DropFlagMode, DropStyle, Unwind, elaborate_drop};
20use crate::patch::MirPatch;
21use crate::{
22    abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, inline, instsimplify,
23    mentioned_items, pass_manager as pm, remove_noop_landing_pads, run_optimization_passes,
24    simplify,
25};
26
27mod async_destructor_ctor;
28
29pub(super) fn provide(providers: &mut Providers) {
30    providers.mir_shims = |tcx, shim| tcx.arena.alloc(make_shim(tcx, shim));
31}
32
33fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, shim: ty::ShimKind<'tcx>) -> Body<'tcx> {
34    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:34",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(34u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_shim({0:?})",
                                                    shim) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("make_shim({:?})", shim);
35
36    let mut result = match shim {
37        ty::ShimKind::VTable(def_id) => {
38            let adjustment = Adjustment::Deref { source: DerefSource::MutPtr };
39            build_call_shim(tcx, shim, Some(adjustment), CallKind::Direct(def_id))
40        }
41        ty::ShimKind::FnPtr(def_id, ty) => {
42            let trait_ = tcx.parent(def_id);
43            // Supports `Fn` or `async Fn` traits.
44            let adjustment = match tcx
45                .fn_trait_kind_from_def_id(trait_)
46                .or_else(|| tcx.async_fn_trait_kind_from_def_id(trait_))
47            {
48                Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
49                Some(ty::ClosureKind::Fn) => Adjustment::Deref { source: DerefSource::ImmRef },
50                Some(ty::ClosureKind::FnMut) => Adjustment::Deref { source: DerefSource::MutRef },
51                None => ::rustc_span::macros::bug_impl(None,
    format_args!("fn pointer {0:?} is not an fn", ty), Location::caller())bug!("fn pointer {:?} is not an fn", ty),
52            };
53
54            build_call_shim(tcx, shim, Some(adjustment), CallKind::Indirect(ty))
55        }
56        // We are generating a call back to our def-id, which the
57        // codegen backend knows to turn to an actual call, be it
58        // a virtual call, or a direct call to a function for which
59        // indirect calls must be codegen'd differently than direct ones
60        // (such as `#[track_caller]`).
61        ty::ShimKind::Reify(def_id, _) => {
62            build_call_shim(tcx, shim, None, CallKind::Direct(def_id))
63        }
64        ty::ShimKind::ClosureOnce { call_once: _, closure: _, track_caller: _ } => {
65            let fn_mut = tcx.require_lang_item(LangItem::FnMut, DUMMY_SP);
66            let call_mut = tcx
67                .associated_items(fn_mut)
68                .in_definition_order()
69                .find(|it| it.is_fn())
70                .unwrap()
71                .def_id;
72
73            build_call_shim(tcx, shim, Some(Adjustment::RefMut), CallKind::Direct(call_mut))
74        }
75
76        ty::ShimKind::ConstructCoroutineInClosure { coroutine_closure_def_id, receiver_by_ref } => {
77            build_construct_coroutine_by_move_shim(tcx, coroutine_closure_def_id, receiver_by_ref)
78        }
79
80        ty::ShimKind::DropGlue(def_id, ty) => {
81            // FIXME(#91576): Drop shims for coroutines aren't subject to the MIR passes at the end
82            // of this function. Is this intentional?
83            if let Some(&ty::Coroutine(coroutine_def_id, args)) = ty.map(Ty::kind) {
84                let coroutine_body = tcx.optimized_mir(coroutine_def_id);
85
86                let ty::Coroutine(_, id_args) = *tcx.type_of(coroutine_def_id).skip_binder().kind()
87                else {
88                    ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!()
89                };
90
91                // If this is a regular coroutine, grab its drop shim. If this is a coroutine
92                // that comes from a coroutine-closure, and the kind ty differs from the "maximum"
93                // kind that it supports, then grab the appropriate drop shim. This ensures that
94                // the future returned by `<[coroutine-closure] as AsyncFnOnce>::call_once` will
95                // drop the coroutine-closure's upvars.
96                let body = if id_args.as_coroutine().kind_ty() == args.as_coroutine().kind_ty() {
97                    coroutine_body.coroutine_drop().unwrap()
98                } else {
99                    {
    match (&args.as_coroutine().kind_ty().to_opt_closure_kind().unwrap(),
            &ty::ClosureKind::FnOnce) {
        (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!(
100                        args.as_coroutine().kind_ty().to_opt_closure_kind().unwrap(),
101                        ty::ClosureKind::FnOnce
102                    );
103                    tcx.optimized_mir(tcx.coroutine_by_move_body_def_id(coroutine_def_id))
104                        .coroutine_drop()
105                        .unwrap()
106                };
107
108                let mut body =
109                    EarlyBinder::bind(tcx, body.clone()).instantiate(tcx, args).skip_norm_wip();
110                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:110",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(110u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_shim({0:?}) = {1:?}",
                                                    shim, body) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("make_shim({:?}) = {:?}", shim, body);
111
112                pm::run_passes(
113                    tcx,
114                    &mut body,
115                    &[
116                        &mentioned_items::MentionedItems,
117                        &abort_unwinding_calls::AbortUnwindingCalls,
118                        &add_call_guards::CriticalCallEdges,
119                    ],
120                    Some(MirPhase::Runtime(RuntimePhase::Optimized)),
121                );
122
123                return body;
124            }
125
126            let ty::PseudoCanonicalInput { typing_env, value: ty } =
127                ty::TypingEnv::post_analysis_invalidating_rigid_aliases(tcx, def_id, ty);
128            // We intentionally don't normalize ty here. Any generic parameters it mentions
129            // belong to the caller, not to drop_glue, so typing_env cannot normalize its
130            // aliases. The caller normalizes the shim body in its own env instead.
131            build_drop_shim(tcx, def_id, ty.skip_normalization(), typing_env)
132        }
133        ty::ShimKind::ThreadLocal(..) => build_thread_local_shim(tcx, shim),
134        ty::ShimKind::Clone(def_id, ty) => build_clone_shim(tcx, def_id, ty),
135        ty::ShimKind::FnAddrAsPtr(def_id, ty) => build_fn_addr_as_ptr_shim(tcx, def_id, ty),
136        ty::ShimKind::FnPtrFromPtr(def_id, ty) => build_fn_ptr_from_ptr_shim(tcx, def_id, ty),
137        ty::ShimKind::FutureDropPoll(def_id, proxy_ty, impl_ty) => {
138            let mut body =
139                async_destructor_ctor::build_future_drop_poll_shim(tcx, def_id, proxy_ty, impl_ty);
140
141            pm::run_passes(
142                tcx,
143                &mut body,
144                &[
145                    &mentioned_items::MentionedItems,
146                    &abort_unwinding_calls::AbortUnwindingCalls,
147                    &add_call_guards::CriticalCallEdges,
148                ],
149                Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
150            );
151            run_optimization_passes(tcx, &mut body);
152            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:152",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(152u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_shim({0:?}) = {1:?}",
                                                    shim, body) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("make_shim({:?}) = {:?}", shim, body);
153            return body;
154        }
155        ty::ShimKind::AsyncDropGlue(def_id, ty) => {
156            let mut body = async_destructor_ctor::build_async_drop_shim(tcx, def_id, ty);
157
158            // Main pass required here is StateTransform to convert sync drop ladder
159            // into coroutine.
160            // Others are minimal passes as for sync drop glue shim
161            pm::run_passes_no_validate(
162                tcx,
163                &mut body,
164                &[
165                    &mentioned_items::MentionedItems,
166                    &abort_unwinding_calls::AbortUnwindingCalls,
167                    &add_call_guards::CriticalCallEdges,
168                    &simplify::SimplifyCfg::MakeShim,
169                    &crate::coroutine::StateTransform,
170                ],
171                Some(MirPhase::Runtime(RuntimePhase::PostCleanup)),
172            );
173            run_optimization_passes(tcx, &mut body);
174            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:174",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(174u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_shim({0:?}) = {1:?}",
                                                    shim, body) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("make_shim({:?}) = {:?}", shim, body);
175            return body;
176        }
177
178        ty::ShimKind::AsyncDropGlueCtor(def_id, ty) => {
179            let body = async_destructor_ctor::build_async_destructor_ctor_shim(tcx, def_id, ty);
180            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:180",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(180u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_shim({0:?}) = {1:?}",
                                                    shim, body) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("make_shim({:?}) = {:?}", shim, body);
181            return body;
182        }
183    };
184    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:184",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(184u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_shim({0:?}) = untransformed {1:?}",
                                                    shim, result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("make_shim({:?}) = untransformed {:?}", shim, result);
185
186    deref_finder(tcx, &mut result, false);
187
188    // We don't validate MIR here because the shims may generate code that's
189    // only valid in a `PostAnalysis` param-env. However, since we do initial
190    // validation with the MirBuilt phase, which uses a user-facing param-env.
191    // This causes validation errors when TAITs are involved.
192    pm::run_passes_no_validate(
193        tcx,
194        &mut result,
195        &[
196            &mentioned_items::MentionedItems,
197            &add_moves_for_packed_drops::AddMovesForPackedDrops,
198            &remove_noop_landing_pads::RemoveNoopLandingPads,
199            &simplify::SimplifyCfg::MakeShim,
200            &instsimplify::InstSimplify::BeforeInline,
201            // Perform inlining of `#[rustc_force_inline]`-annotated callees.
202            &inline::ForceInline,
203            &abort_unwinding_calls::AbortUnwindingCalls,
204            &add_call_guards::CriticalCallEdges,
205        ],
206        Some(MirPhase::Runtime(RuntimePhase::Optimized)),
207    );
208
209    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:209",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(209u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("make_shim({0:?}) = {1:?}",
                                                    shim, result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("make_shim({:?}) = {:?}", shim, result);
210
211    result
212}
213
214#[derive(#[automatically_derived]impl ::core::marker::Copy for DerefSource { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DerefSource {
}
#[automatically_derived]impl ::core::clone::Clone for DerefSource {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for DerefSource {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DerefSource::ImmRef => "ImmRef",
                DerefSource::MutRef => "MutRef",
                DerefSource::MutPtr => "MutPtr",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    DerefSource {
}
#[automatically_derived]impl ::core::cmp::PartialEq for DerefSource {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
215enum DerefSource {
216    /// `fn shim(&self) { inner(*self )}`.
217    ImmRef,
218    /// `fn shim(&mut self) { inner(*self )}`.
219    MutRef,
220    /// `fn shim(*mut self) { inner(*self )}`.
221    MutPtr,
222}
223
224#[derive(#[automatically_derived]impl ::core::marker::Copy for Adjustment { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Adjustment {
}
#[automatically_derived]impl ::core::clone::Clone for Adjustment {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<DerefSource>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Adjustment {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Identity =>
                ::core::fmt::Formatter::write_str(f, "Identity"),
            Self::Deref { source: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Deref source", &__self_0),
            Self::RefMut => ::core::fmt::Formatter::write_str(f, "RefMut"),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    Adjustment {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Adjustment {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Deref { source: __self_0 }, Self::Deref {
                    source: __arg1_0 }) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
225enum Adjustment {
226    /// Pass the receiver as-is.
227    Identity,
228
229    /// We get passed a reference or a raw pointer to `self` and call the target with `*self`.
230    ///
231    /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it
232    /// (for `VTableShim`, which effectively is passed `&own Self`).
233    Deref { source: DerefSource },
234
235    /// We get passed `self: Self` and call the target with `&mut self`.
236    ///
237    /// In this case we need to ensure that the `Self` is dropped after the call, as the callee
238    /// won't do it for us.
239    RefMut,
240}
241
242#[derive(#[automatically_derived]impl<'tcx> ::core::marker::Copy for CallKind<'tcx> { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for CallKind<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for CallKind<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<DefId>;
        *self
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for CallKind<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Indirect(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Indirect", &__self_0),
            Self::Direct(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Direct", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl<'tcx> ::core::marker::StructuralPartialEq for
    CallKind<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::cmp::PartialEq for CallKind<'tcx> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Indirect(__self_0), Self::Indirect(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Direct(__self_0), Self::Direct(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
243enum CallKind<'tcx> {
244    /// Call the `FnPtr` that was passed as the receiver.
245    Indirect(Ty<'tcx>),
246
247    /// Call a known `FnDef`.
248    Direct(DefId),
249}
250
251fn local_decls_for_sig<'tcx>(
252    sig: &ty::FnSig<'tcx>,
253    span: Span,
254) -> IndexVec<Local, LocalDecl<'tcx>> {
255    iter::once(LocalDecl::new(sig.output(), span))
256        .chain(sig.inputs().iter().map(|ity| LocalDecl::new(*ity, span).immutable()))
257        .collect()
258}
259
260/// Builds the drop glue for the provided type. The `def_id` is that of `core::ptr::drop_glue`.
261///
262/// Inside rustc this is only called on a monomorphic type, but we expose the function for
263/// rustc_driver writers to be able to generate drop glue for a polymorphic type.
264pub fn build_drop_shim<'tcx>(
265    tcx: TyCtxt<'tcx>,
266    def_id: DefId,
267    ty: Option<Ty<'tcx>>,
268    typing_env: ty::TypingEnv<'tcx>,
269) -> Body<'tcx> {
270    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:270",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(270u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_drop_shim(def_id={0:?}, ty={1:?})",
                                                    def_id, ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
271
272    if !!#[allow(non_exhaustive_omitted_patterns)] match ty {
                Some(ty) if ty.is_coroutine() => true,
                _ => false,
            } {
    ::core::panicking::panic("assertion failed: !matches!(ty, Some(ty) if ty.is_coroutine())")
};assert!(!matches!(ty, Some(ty) if ty.is_coroutine()));
273
274    let args = if let Some(ty) = ty {
275        tcx.mk_args(&[ty.into()])
276    } else {
277        GenericArgs::identity_for_item(tcx, def_id)
278    };
279    let sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip();
280    let sig = tcx.instantiate_bound_regions_with_erased(sig);
281    let span = tcx.def_span(def_id);
282
283    let source_info = SourceInfo::outermost(span);
284
285    let return_block = BasicBlock::new(1);
286    let mut blocks = IndexVec::with_capacity(2);
287    let block = |blocks: &mut IndexVec<_, _>, kind| -> BasicBlock {
288        blocks.push(BasicBlockData::new(Terminator { source_info, kind }, false))
289    };
290    if ty.is_some() {
291        block(&mut blocks, TerminatorKind::goto(return_block));
292    }
293    let ret = block(&mut blocks, TerminatorKind::Return);
294    blocks[ret].statements.push(Statement::new(
295        source_info,
296        StatementKind::Assign(Box::new((
297            Place::return_place(),
298            Rvalue::Use(Operand::zero_sized_constant(tcx.types.unit, span), WithRetag::Yes),
299        ))),
300    ));
301
302    let source = MirSource::from_shim(ty::ShimKind::DropGlue(def_id, ty));
303    let mut body =
304        new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
305
306    let Some(ty) = ty else {
307        return body;
308    };
309
310    let dropee_ptr = Place::from(Local::arg(0));
311
312    if let ty::Array(ety, _len) = *ty.kind() {
313        // Don't write out the elaboration for each array type.
314        // Instead, just delegate to the slice version.
315        let slice_ty = Ty::new_slice(tcx, ety);
316        let mut_slice_ty = Ty::new_ref(tcx, tcx.lifetimes.re_erased, slice_ty, ty::Mutability::Mut);
317        let erased_local = body.local_decls.push(LocalDecl::new(mut_slice_ty, span));
318
319        let start = &mut body.basic_blocks_mut()[START_BLOCK];
320        start.statements.push(Statement::new(
321            source_info,
322            StatementKind::Assign(Box::new((
323                Place::from(erased_local),
324                Rvalue::Cast(
325                    CastKind::PointerCoercion(
326                        ty::adjustment::PointerCoercion::Unsize,
327                        CoercionSource::Implicit,
328                    ),
329                    Operand::Move(dropee_ptr),
330                    mut_slice_ty,
331                ),
332            ))),
333        ));
334        start.terminator = Terminator {
335            source_info,
336            kind: TerminatorKind::Call {
337                func: Operand::function_handle(
338                    tcx,
339                    def_id,
340                    &[ty::GenericArg::from(slice_ty)],
341                    span,
342                ),
343                args: Box::new([Spanned { span, node: Operand::Move(Place::from(erased_local)) }]),
344                destination: Place::from(RETURN_PLACE),
345                target: Some(return_block),
346                unwind: UnwindAction::Continue,
347                call_source: CallSource::Misc,
348                fn_span: span,
349            },
350        };
351    } else {
352        let patch = {
353            let mut elaborator = DropShimElaborator {
354                body: &body,
355                patch: MirPatch::new(&body),
356                tcx,
357                typing_env,
358                produce_async_drops: false,
359            };
360            let dropee = tcx.mk_place_deref(dropee_ptr);
361            let resume_block = elaborator.patch.resume_block();
362            elaborate_drop(
363                &mut elaborator,
364                source_info,
365                dropee,
366                (),
367                return_block,
368                Unwind::To(resume_block),
369                START_BLOCK,
370                None,
371            );
372            elaborator.patch
373        };
374        patch.apply(&mut body);
375    }
376
377    body
378}
379
380fn new_body<'tcx>(
381    source: MirSource<'tcx>,
382    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
383    local_decls: IndexVec<Local, LocalDecl<'tcx>>,
384    arg_count: usize,
385    span: Span,
386) -> Body<'tcx> {
387    let mut body = Body::new(
388        source,
389        basic_blocks,
390        IndexVec::from_elem_n(
391            SourceScopeData {
392                span,
393                parent_scope: None,
394                inlined: None,
395                inlined_parent_scope: None,
396                local_data: ClearCrossCrate::Clear,
397            },
398            1,
399        ),
400        local_decls,
401        IndexVec::new(),
402        arg_count,
403        ::alloc::vec::Vec::new()vec![],
404        span,
405        None,
406        // FIXME(compiler-errors): is this correct?
407        None,
408    );
409    // Shims do not directly mention any consts.
410    body.set_required_consts(Vec::new());
411    // We don't do any analysis on shims.
412    body.phase = MirPhase::Runtime(RuntimePhase::Initial);
413    body
414}
415
416pub(super) struct DropShimElaborator<'a, 'tcx> {
417    pub body: &'a Body<'tcx>,
418    pub patch: MirPatch<'tcx>,
419    pub tcx: TyCtxt<'tcx>,
420    pub typing_env: ty::TypingEnv<'tcx>,
421    pub produce_async_drops: bool,
422}
423
424impl fmt::Debug for DropShimElaborator<'_, '_> {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
426        f.debug_struct("DropShimElaborator").finish_non_exhaustive()
427    }
428}
429
430impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
431    type Path = ();
432
433    fn patch_ref(&self) -> &MirPatch<'tcx> {
434        &self.patch
435    }
436    fn patch(&mut self) -> &mut MirPatch<'tcx> {
437        &mut self.patch
438    }
439    fn body(&self) -> &'a Body<'tcx> {
440        self.body
441    }
442    fn tcx(&self) -> TyCtxt<'tcx> {
443        self.tcx
444    }
445    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
446        self.typing_env
447    }
448
449    fn allow_async_drops(&self) -> bool {
450        self.produce_async_drops
451    }
452
453    fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
454        match mode {
455            DropFlagMode::Shallow => {
456                // Drops for the contained fields are "shallow" and "static" - they will simply call
457                // the field's own drop glue.
458                DropStyle::Static
459            }
460            DropFlagMode::Deep => {
461                // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
462                // dropping each field contained in the value.
463                DropStyle::Open
464            }
465        }
466    }
467
468    fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
469        None
470    }
471
472    fn drop_flags_for(&mut self, _path: Self::Path, _mode: DropFlagMode) -> Vec<Place<'tcx>> {
473        Vec::new()
474    }
475
476    fn field_subpath(&self, _path: Self::Path, _field: FieldIdx) -> Option<Self::Path> {
477        None
478    }
479    fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
480        None
481    }
482    fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
483        Some(())
484    }
485    fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> {
486        None
487    }
488}
489
490fn build_thread_local_shim<'tcx>(tcx: TyCtxt<'tcx>, shim: ty::ShimKind<'tcx>) -> Body<'tcx> {
491    let def_id = shim.def_id();
492
493    let span = tcx.def_span(def_id);
494    let source_info = SourceInfo::outermost(span);
495
496    let blocks = IndexVec::from_raw(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [BasicBlockData::new_stmts({
                        let len = [()].len();
                        let mut vec = ::thin_vec::ThinVec::with_capacity(len);
                        vec.push(Statement::new(source_info,
                                StatementKind::Assign(Box::new((Place::return_place(),
                                            Rvalue::ThreadLocalRef(def_id))))));
                        vec
                    }, Terminator { source_info, kind: TerminatorKind::Return },
                    false)]))vec![BasicBlockData::new_stmts(
497        thin_vec![Statement::new(
498            source_info,
499            StatementKind::Assign(Box::new((
500                Place::return_place(),
501                Rvalue::ThreadLocalRef(def_id),
502            ))),
503        )],
504        Terminator { source_info, kind: TerminatorKind::Return },
505        false,
506    )]);
507
508    new_body(
509        MirSource::from_shim(shim),
510        blocks,
511        IndexVec::from_raw(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [LocalDecl::new(tcx.thread_local_ptr_ty(def_id), span)]))vec![LocalDecl::new(tcx.thread_local_ptr_ty(def_id), span)]),
512        0,
513        span,
514    )
515}
516
517/// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
518fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
519    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:519",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(519u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_clone_shim(def_id={0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_clone_shim(def_id={:?})", def_id);
520
521    let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
522
523    let dest = Place::return_place();
524    let src = tcx.mk_place_deref(Place::from(Local::arg(0)));
525
526    match self_ty.kind() {
527        ty::FnDef(..) | ty::FnPtr(..) => builder.copy_shim(),
528        ty::Closure(_, args) => builder.tuple_like_shim(dest, src, args.as_closure().upvar_tys()),
529        ty::CoroutineClosure(_, args) => {
530            builder.tuple_like_shim(dest, src, args.as_coroutine_closure().upvar_tys())
531        }
532        ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
533        ty::Coroutine(coroutine_def_id, args) => {
534            {
    match (&tcx.coroutine_movability(*coroutine_def_id),
            &hir::Movability::Movable) {
        (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!(tcx.coroutine_movability(*coroutine_def_id), hir::Movability::Movable);
535            builder.coroutine_shim(dest, src, *coroutine_def_id, args.as_coroutine())
536        }
537        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("clone shim for `{0:?}` which is not `Copy` and is not an aggregate",
        self_ty), Location::caller())bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
538    };
539
540    builder.into_mir()
541}
542
543struct CloneShimBuilder<'tcx> {
544    tcx: TyCtxt<'tcx>,
545    def_id: DefId,
546    local_decls: IndexVec<Local, LocalDecl<'tcx>>,
547    blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
548    span: Span,
549    sig: ty::FnSig<'tcx>,
550}
551
552impl<'tcx> CloneShimBuilder<'tcx> {
553    fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
554        // we must instantiate the self_ty because it's
555        // otherwise going to be TySelf and we can't index
556        // or access fields of a Place of type TySelf.
557        let sig = tcx.fn_sig(def_id).instantiate(tcx, &[self_ty.into()]).skip_norm_wip();
558        let sig = tcx.instantiate_bound_regions_with_erased(sig);
559        let span = tcx.def_span(def_id);
560
561        CloneShimBuilder {
562            tcx,
563            def_id,
564            local_decls: local_decls_for_sig(&sig, span),
565            blocks: IndexVec::new(),
566            span,
567            sig,
568        }
569    }
570
571    fn into_mir(self) -> Body<'tcx> {
572        let source =
573            MirSource::from_shim(ty::ShimKind::Clone(self.def_id, self.sig.inputs_and_output[0]));
574        new_body(source, self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
575    }
576
577    fn source_info(&self) -> SourceInfo {
578        SourceInfo::outermost(self.span)
579    }
580
581    fn block(
582        &mut self,
583        statements: ThinVec<Statement<'tcx>>,
584        kind: TerminatorKind<'tcx>,
585        is_cleanup: bool,
586    ) -> BasicBlock {
587        let source_info = self.source_info();
588        self.blocks.push(BasicBlockData::new_stmts(
589            statements,
590            Terminator { source_info, kind },
591            is_cleanup,
592        ))
593    }
594
595    /// Gives the index of an upcoming BasicBlock, with an offset.
596    /// offset=0 will give you the index of the next BasicBlock,
597    /// offset=1 will give the index of the next-to-next block,
598    /// offset=-1 will give you the index of the last-created block
599    fn block_index_offset(&self, offset: usize) -> BasicBlock {
600        BasicBlock::new(self.blocks.len() + offset)
601    }
602
603    fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
604        Statement::new(self.source_info(), kind)
605    }
606
607    fn copy_shim(&mut self) {
608        let rcvr = self.tcx.mk_place_deref(Place::from(Local::arg(0)));
609        let ret_statement = self.make_statement(StatementKind::Assign(Box::new((
610            Place::return_place(),
611            Rvalue::Use(Operand::Copy(rcvr), WithRetag::Yes),
612        ))));
613        self.block({
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(ret_statement);
    vec
}thin_vec![ret_statement], TerminatorKind::Return, false);
614    }
615
616    fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
617        let span = self.span;
618        let mut local = LocalDecl::new(ty, span);
619        if mutability.is_not() {
620            local = local.immutable();
621        }
622        Place::from(self.local_decls.push(local))
623    }
624
625    fn make_clone_call(
626        &mut self,
627        dest: Place<'tcx>,
628        src: Place<'tcx>,
629        ty: Ty<'tcx>,
630        next: BasicBlock,
631        cleanup: BasicBlock,
632    ) {
633        let tcx = self.tcx;
634
635        // `func == Clone::clone(&ty) -> ty`
636        let func_ty = tcx.type_of(self.def_id).instantiate(tcx, &[ty.into()]).skip_norm_wip();
637        let func = Operand::Constant(Box::new(ConstOperand {
638            span: self.span,
639            user_ty: None,
640            const_: Const::zero_sized(func_ty),
641        }));
642
643        let ref_loc =
644            self.make_place(Mutability::Not, Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty));
645
646        // `let ref_loc: &ty = &src;`
647        let statement = self.make_statement(StatementKind::Assign(Box::new((
648            ref_loc,
649            Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
650        ))));
651
652        // `let loc = Clone::clone(ref_loc);`
653        self.block(
654            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(statement);
    vec
}thin_vec![statement],
655            TerminatorKind::Call {
656                func,
657                args: [Spanned { node: Operand::Move(ref_loc), span: DUMMY_SP }].into(),
658                destination: dest,
659                target: Some(next),
660                unwind: UnwindAction::Cleanup(cleanup),
661                call_source: CallSource::Normal,
662                fn_span: self.span,
663            },
664            false,
665        );
666    }
667
668    fn clone_fields<I>(
669        &mut self,
670        dest: Place<'tcx>,
671        src: Place<'tcx>,
672        target: BasicBlock,
673        mut unwind: BasicBlock,
674        tys: I,
675    ) -> BasicBlock
676    where
677        I: IntoIterator<Item = Ty<'tcx>>,
678    {
679        // For an iterator of length n, create 2*n + 1 blocks.
680        for (i, ity) in tys.into_iter().enumerate() {
681            // Each iteration creates two blocks, referred to here as block 2*i and block 2*i + 1.
682            //
683            // Block 2*i attempts to clone the field. If successful it branches to 2*i + 2 (the
684            // next clone block). If unsuccessful it branches to the previous unwind block, which
685            // is initially the `unwind` argument passed to this function.
686            //
687            // Block 2*i + 1 is the unwind block for this iteration. It drops the cloned value
688            // created by block 2*i. We store this block in `unwind` so that the next clone block
689            // will unwind to it if cloning fails.
690
691            let field = FieldIdx::new(i);
692            let src_field = self.tcx.mk_place_field(src, field, ity);
693
694            let dest_field = self.tcx.mk_place_field(dest, field, ity);
695
696            let next_unwind = self.block_index_offset(1);
697            let next_block = self.block_index_offset(2);
698            self.make_clone_call(dest_field, src_field, ity, next_block, unwind);
699            self.block(
700                ::thin_vec::ThinVec::new()thin_vec![],
701                TerminatorKind::Drop {
702                    place: dest_field,
703                    target: unwind,
704                    unwind: UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
705                    replace: false,
706                    drop: None,
707                },
708                /* is_cleanup */ true,
709            );
710            unwind = next_unwind;
711        }
712        // If all clones succeed then we end up here.
713        self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::goto(target), false);
714        unwind
715    }
716
717    fn tuple_like_shim(
718        &mut self,
719        dest: Place<'tcx>,
720        src: Place<'tcx>,
721        tys: &'tcx ty::List<Ty<'tcx>>,
722    ) {
723        if tys.is_empty() {
724            // With no fields to clone, initialize the return local directly.
725            self.copy_shim();
726            return;
727        }
728
729        self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::goto(self.block_index_offset(3)), false);
730        let unwind = self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::UnwindResume, true);
731        let target = self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::Return, false);
732
733        let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, tys);
734    }
735
736    fn coroutine_shim(
737        &mut self,
738        dest: Place<'tcx>,
739        src: Place<'tcx>,
740        coroutine_def_id: DefId,
741        args: CoroutineArgs<TyCtxt<'tcx>>,
742    ) {
743        self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::goto(self.block_index_offset(3)), false);
744        let unwind = self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::UnwindResume, true);
745        // This will get overwritten with a switch once we know the target blocks
746        let switch = self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::Unreachable, false);
747        let unwind = self.clone_fields(dest, src, switch, unwind, args.upvar_tys());
748        let target = self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::Return, false);
749        let unreachable = self.block(::thin_vec::ThinVec::new()thin_vec![], TerminatorKind::Unreachable, false);
750        let mut cases = Vec::with_capacity(args.state_tys(coroutine_def_id, self.tcx).count());
751        for (index, state_tys) in args.state_tys(coroutine_def_id, self.tcx).enumerate() {
752            let variant_index = VariantIdx::new(index);
753            let dest = self.tcx.mk_place_downcast_unnamed(dest, variant_index);
754            let src = self.tcx.mk_place_downcast_unnamed(src, variant_index);
755            let clone_block = self.block_index_offset(1);
756            let start_block = self.block(
757                {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self.make_statement(StatementKind::SetDiscriminant {
                place: Box::new(Place::return_place()),
                variant_index,
            }));
    vec
}thin_vec![self.make_statement(StatementKind::SetDiscriminant {
758                    place: Box::new(Place::return_place()),
759                    variant_index,
760                })],
761                TerminatorKind::goto(clone_block),
762                false,
763            );
764            cases.push((index as u128, start_block));
765            let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, state_tys);
766        }
767        let discr_ty = args.discr_ty(self.tcx);
768        let temp = self.make_place(Mutability::Mut, discr_ty);
769        let rvalue = Rvalue::Discriminant(src);
770        let statement = self.make_statement(StatementKind::Assign(Box::new((temp, rvalue))));
771
772        let block = &mut self.blocks[switch];
773        block.statements.push(statement);
774        block.terminator.kind = TerminatorKind::SwitchInt {
775            discr: Operand::Move(temp),
776            targets: SwitchTargets::new(cases.into_iter(), unreachable),
777        };
778    }
779}
780
781/// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`,
782/// first adjusting its first argument according to `rcvr_adjustment`.
783{}
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("build_call_shim",
                                "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                                ::tracing_core::__macro_support::Option::Some(783u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("shim")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("shim");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("rcvr_adjustment")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("rcvr_adjustment");
                                                    NAME.as_str()
                                                },
                                                {
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("call_kind")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("call_kind");
                                                    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(&shim)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rcvr_adjustment)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&call_kind)
                                                        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: Body<'tcx> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let (sig_args, untuple_args) =
                            if let ty::ShimKind::FnPtr(_, ty) = shim {
                                let sig =
                                    tcx.instantiate_bound_regions_with_erased(ty.fn_sig(tcx));
                                let untuple_args = sig.inputs();
                                let arg_tup = Ty::new_tup(tcx, untuple_args);
                                (Some([ty.into(), arg_tup.into()]), Some(untuple_args))
                            } else { (None, None) };
                        let def_id = shim.def_id();
                        let sig = tcx.fn_sig(def_id);
                        let sig =
                            sig.map_bound(|sig|
                                    tcx.instantiate_bound_regions_with_erased(sig));
                        {
                            match (&sig_args.is_some(),
                                    &!shim.has_polymorphic_mir_body()) {
                                (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);
                                    }
                                }
                            }
                        };
                        let mut sig =
                            if let Some(sig_args) = sig_args {
                                sig.instantiate(tcx, &sig_args).skip_norm_wip()
                            } else { sig.instantiate_identity().skip_norm_wip() };
                        if let CallKind::Indirect(fnty) = call_kind {
                            let mut inputs_and_output = sig.inputs_and_output.to_vec();
                            {
                                match (&inputs_and_output.len(), &3) {
                                    (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);
                                        }
                                    }
                                }
                            };
                            let self_arg = &mut inputs_and_output[0];
                            *self_arg =
                                match rcvr_adjustment.unwrap() {
                                    Adjustment::Identity => fnty,
                                    Adjustment::Deref { source } =>
                                        match source {
                                            DerefSource::ImmRef =>
                                                Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, fnty),
                                            DerefSource::MutRef =>
                                                Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, fnty),
                                            DerefSource::MutPtr => Ty::new_mut_ptr(tcx, fnty),
                                        },
                                    Adjustment::RefMut =>
                                        ::rustc_span::macros::bug_impl(None,
                                            format_args!("`RefMut` is never used with indirect calls: {0:?}",
                                                shim), Location::caller()),
                                };
                            sig.inputs_and_output =
                                tcx.mk_type_list(&inputs_and_output);
                        }
                        if let ty::ShimKind::VTable(..) = shim {
                            let mut inputs_and_output = sig.inputs_and_output.to_vec();
                            let self_arg = &mut inputs_and_output[0];
                            if true {
                                if !(tcx.generics_of(def_id).has_self &&
                                            *self_arg == tcx.types.self_param) {
                                    ::core::panicking::panic("assertion failed: tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param")
                                };
                            };
                            *self_arg = Ty::new_mut_ptr(tcx, *self_arg);
                            sig.inputs_and_output =
                                tcx.mk_type_list(&inputs_and_output);
                        }
                        let span = tcx.def_span(def_id);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:858",
                                                "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                                                ::tracing_core::__macro_support::Option::Some(858u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("sig")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("sig");
                                                                    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(&sig)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let mut local_decls = local_decls_for_sig(&sig, span);
                        let source_info = SourceInfo::outermost(span);
                        let destination = Place::return_place();
                        let rcvr_place =
                            ||
                                {
                                    if !rcvr_adjustment.is_some() {
                                        ::core::panicking::panic("assertion failed: rcvr_adjustment.is_some()")
                                    };
                                    Place::from(Local::arg(0))
                                };
                        let mut statements = ::thin_vec::ThinVec::new();
                        let rcvr =
                            rcvr_adjustment.map(|rcvr_adjustment|
                                    match rcvr_adjustment {
                                        Adjustment::Identity => Operand::Move(rcvr_place()),
                                        Adjustment::Deref { source: _ } =>
                                            Operand::Move(tcx.mk_place_deref(rcvr_place())),
                                        Adjustment::RefMut => {
                                            let ref_rcvr =
                                                local_decls.push(LocalDecl::new(Ty::new_mut_ref(tcx,
                                                                tcx.lifetimes.re_erased, sig.inputs()[0]),
                                                            span).immutable());
                                            let borrow_kind =
                                                BorrowKind::Mut { kind: MutBorrowKind::Default };
                                            statements.push(Statement::new(source_info,
                                                    StatementKind::Assign(Box::new((Place::from(ref_rcvr),
                                                                Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind,
                                                                    rcvr_place()))))));
                                            Operand::Move(Place::from(ref_rcvr))
                                        }
                                    });
                        let (callee, mut args) =
                            match call_kind {
                                CallKind::Indirect(_) =>
                                    (rcvr.unwrap(), ::alloc::vec::Vec::new()),
                                CallKind::Direct(def_id) => {
                                    let ty =
                                        tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
                                    (Operand::Constant(Box::new(ConstOperand {
                                                    span,
                                                    user_ty: None,
                                                    const_: Const::zero_sized(ty),
                                                })), rcvr.into_iter().collect::<Vec<_>>())
                                }
                            };
                        let mut arg_range = 0..sig.inputs().len();
                        if rcvr_adjustment.is_some() { arg_range.start += 1; }
                        if untuple_args.is_some() { arg_range.end -= 1; }
                        args.extend(arg_range.map(|i|
                                    Operand::Move(Place::from(Local::arg(i)))));
                        if let Some(untuple_args) = untuple_args {
                            let tuple_arg = Local::arg(sig.inputs().len() - 1);
                            args.extend(untuple_args.iter().enumerate().map(|(i, ity)|
                                        {
                                            Operand::Move(tcx.mk_place_field(Place::from(tuple_arg),
                                                    FieldIdx::new(i), *ity))
                                        }));
                        }
                        let n_blocks =
                            if let Some(Adjustment::RefMut) = rcvr_adjustment {
                                5
                            } else { 2 };
                        let mut blocks = IndexVec::with_capacity(n_blocks);
                        let block =
                            |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup|
                                {
                                    blocks.push(BasicBlockData::new_stmts(statements,
                                            Terminator { source_info, kind }, is_cleanup))
                                };
                        let args =
                            args.into_iter().map(|a|
                                        Spanned { node: a, span: DUMMY_SP }).collect();
                        block(&mut blocks, statements,
                            TerminatorKind::Call {
                                func: callee,
                                args,
                                destination,
                                target: Some(BasicBlock::new(1)),
                                unwind: if let Some(Adjustment::RefMut) = rcvr_adjustment {
                                    UnwindAction::Cleanup(BasicBlock::new(3))
                                } else { UnwindAction::Continue },
                                call_source: CallSource::Misc,
                                fn_span: span,
                            }, false);
                        if let Some(Adjustment::RefMut) = rcvr_adjustment {
                            block(&mut blocks, ::thin_vec::ThinVec::new(),
                                TerminatorKind::Drop {
                                    place: rcvr_place(),
                                    target: BasicBlock::new(2),
                                    unwind: UnwindAction::Continue,
                                    replace: false,
                                    drop: None,
                                }, false);
                        }
                        let stmts = ::thin_vec::ThinVec::new();
                        block(&mut blocks, stmts, TerminatorKind::Return, false);
                        if let Some(Adjustment::RefMut) = rcvr_adjustment {
                            block(&mut blocks, ::thin_vec::ThinVec::new(),
                                TerminatorKind::Drop {
                                    place: rcvr_place(),
                                    target: BasicBlock::new(4),
                                    unwind: UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
                                    replace: false,
                                    drop: None,
                                }, true);
                            block(&mut blocks, ::thin_vec::ThinVec::new(),
                                TerminatorKind::UnwindResume, true);
                        }
                        let mut body =
                            new_body(MirSource::from_shim(shim), blocks, local_decls,
                                sig.inputs().len(), span);
                        if let ExternAbi::RustCall = sig.abi() {
                            body.spread_arg = Some(Local::new(sig.inputs().len()));
                        }
                        body
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:783",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(783u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::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)]
784fn build_call_shim<'tcx>(
785    tcx: TyCtxt<'tcx>,
786    shim: ty::ShimKind<'tcx>,
787    rcvr_adjustment: Option<Adjustment>,
788    call_kind: CallKind<'tcx>,
789) -> Body<'tcx> {
790    // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used
791    // to instantiate into the signature of the shim. It is not necessary for users of this
792    // MIR body to perform further instantiations (see `InstanceKind::has_polymorphic_mir_body`).
793    let (sig_args, untuple_args) = if let ty::ShimKind::FnPtr(_, ty) = shim {
794        let sig = tcx.instantiate_bound_regions_with_erased(ty.fn_sig(tcx));
795
796        let untuple_args = sig.inputs();
797
798        // Create substitutions for the `Self` and `Args` generic parameters of the shim body.
799        let arg_tup = Ty::new_tup(tcx, untuple_args);
800
801        (Some([ty.into(), arg_tup.into()]), Some(untuple_args))
802    } else {
803        (None, None)
804    };
805
806    let def_id = shim.def_id();
807
808    let sig = tcx.fn_sig(def_id);
809    let sig = sig.map_bound(|sig| tcx.instantiate_bound_regions_with_erased(sig));
810
811    assert_eq!(sig_args.is_some(), !shim.has_polymorphic_mir_body());
812    let mut sig = if let Some(sig_args) = sig_args {
813        sig.instantiate(tcx, &sig_args).skip_norm_wip()
814    } else {
815        sig.instantiate_identity().skip_norm_wip()
816    };
817
818    if let CallKind::Indirect(fnty) = call_kind {
819        // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
820        // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
821        // the implemented `FnX` trait.
822
823        // Apply the opposite adjustment to the MIR input.
824        let mut inputs_and_output = sig.inputs_and_output.to_vec();
825
826        // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
827        // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
828        assert_eq!(inputs_and_output.len(), 3);
829
830        // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
831        // `FnDef` and `FnPtr` callees, not the `Self` type param.
832        let self_arg = &mut inputs_and_output[0];
833        *self_arg = match rcvr_adjustment.unwrap() {
834            Adjustment::Identity => fnty,
835            Adjustment::Deref { source } => match source {
836                DerefSource::ImmRef => Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, fnty),
837                DerefSource::MutRef => Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, fnty),
838                DerefSource::MutPtr => Ty::new_mut_ptr(tcx, fnty),
839            },
840            Adjustment::RefMut => bug!("`RefMut` is never used with indirect calls: {shim:?}"),
841        };
842        sig.inputs_and_output = tcx.mk_type_list(&inputs_and_output);
843    }
844
845    // FIXME: Avoid having to adjust the signature both here and in
846    // `fn_sig_for_fn_abi`.
847    if let ty::ShimKind::VTable(..) = shim {
848        // Modify fn(self, ...) to fn(self: *mut Self, ...)
849        let mut inputs_and_output = sig.inputs_and_output.to_vec();
850        let self_arg = &mut inputs_and_output[0];
851        debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
852        *self_arg = Ty::new_mut_ptr(tcx, *self_arg);
853        sig.inputs_and_output = tcx.mk_type_list(&inputs_and_output);
854    }
855
856    let span = tcx.def_span(def_id);
857
858    debug!(?sig);
859
860    let mut local_decls = local_decls_for_sig(&sig, span);
861    let source_info = SourceInfo::outermost(span);
862
863    let destination = Place::return_place();
864
865    let rcvr_place = || {
866        assert!(rcvr_adjustment.is_some());
867        Place::from(Local::arg(0))
868    };
869    let mut statements = thin_vec![];
870
871    let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
872        Adjustment::Identity => Operand::Move(rcvr_place()),
873        Adjustment::Deref { source: _ } => Operand::Move(tcx.mk_place_deref(rcvr_place())),
874        Adjustment::RefMut => {
875            // let rcvr = &mut rcvr;
876            let ref_rcvr = local_decls.push(
877                LocalDecl::new(
878                    Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, sig.inputs()[0]),
879                    span,
880                )
881                .immutable(),
882            );
883            let borrow_kind = BorrowKind::Mut { kind: MutBorrowKind::Default };
884            statements.push(Statement::new(
885                source_info,
886                StatementKind::Assign(Box::new((
887                    Place::from(ref_rcvr),
888                    Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
889                ))),
890            ));
891            Operand::Move(Place::from(ref_rcvr))
892        }
893    });
894
895    let (callee, mut args) = match call_kind {
896        // `FnPtr` call has no receiver. Args are untupled below.
897        CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
898
899        // `FnDef` call with optional receiver.
900        CallKind::Direct(def_id) => {
901            let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
902            (
903                Operand::Constant(Box::new(ConstOperand {
904                    span,
905                    user_ty: None,
906                    const_: Const::zero_sized(ty),
907                })),
908                rcvr.into_iter().collect::<Vec<_>>(),
909            )
910        }
911    };
912
913    let mut arg_range = 0..sig.inputs().len();
914
915    // Take the `self` ("receiver") argument out of the range (it's adjusted above).
916    if rcvr_adjustment.is_some() {
917        arg_range.start += 1;
918    }
919
920    // Take the last argument, if we need to untuple it (handled below).
921    if untuple_args.is_some() {
922        arg_range.end -= 1;
923    }
924
925    // Pass all of the non-special arguments directly.
926    args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::arg(i)))));
927
928    // Untuple the last argument, if we have to.
929    if let Some(untuple_args) = untuple_args {
930        let tuple_arg = Local::arg(sig.inputs().len() - 1);
931        args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
932            Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), FieldIdx::new(i), *ity))
933        }));
934    }
935
936    let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
937    let mut blocks = IndexVec::with_capacity(n_blocks);
938    let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
939        blocks.push(BasicBlockData::new_stmts(
940            statements,
941            Terminator { source_info, kind },
942            is_cleanup,
943        ))
944    };
945
946    // BB #0
947    let args = args.into_iter().map(|a| Spanned { node: a, span: DUMMY_SP }).collect();
948    block(
949        &mut blocks,
950        statements,
951        TerminatorKind::Call {
952            func: callee,
953            args,
954            destination,
955            target: Some(BasicBlock::new(1)),
956            unwind: if let Some(Adjustment::RefMut) = rcvr_adjustment {
957                UnwindAction::Cleanup(BasicBlock::new(3))
958            } else {
959                UnwindAction::Continue
960            },
961            call_source: CallSource::Misc,
962            fn_span: span,
963        },
964        false,
965    );
966
967    if let Some(Adjustment::RefMut) = rcvr_adjustment {
968        // BB #1 - drop for Self
969        block(
970            &mut blocks,
971            thin_vec![],
972            TerminatorKind::Drop {
973                place: rcvr_place(),
974                target: BasicBlock::new(2),
975                unwind: UnwindAction::Continue,
976                replace: false,
977                drop: None,
978            },
979            false,
980        );
981    }
982    // BB #1/#2 - return
983    let stmts = thin_vec![];
984    block(&mut blocks, stmts, TerminatorKind::Return, false);
985    if let Some(Adjustment::RefMut) = rcvr_adjustment {
986        // BB #3 - drop if closure panics
987        block(
988            &mut blocks,
989            thin_vec![],
990            TerminatorKind::Drop {
991                place: rcvr_place(),
992                target: BasicBlock::new(4),
993                unwind: UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
994                replace: false,
995                drop: None,
996            },
997            /* is_cleanup */ true,
998        );
999
1000        // BB #4 - resume
1001        block(&mut blocks, thin_vec![], TerminatorKind::UnwindResume, true);
1002    }
1003
1004    let mut body =
1005        new_body(MirSource::from_shim(shim), blocks, local_decls, sig.inputs().len(), span);
1006
1007    if let ExternAbi::RustCall = sig.abi() {
1008        body.spread_arg = Some(Local::new(sig.inputs().len()));
1009    }
1010
1011    body
1012}
1013
1014pub(super) fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
1015    if true {
    if !tcx.is_constructor(ctor_id) {
        ::core::panicking::panic("assertion failed: tcx.is_constructor(ctor_id)")
    };
};debug_assert!(tcx.is_constructor(ctor_id));
1016
1017    let typing_env = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, ctor_id);
1018
1019    // Normalize the sig.
1020    let sig = tcx
1021        .fn_sig(ctor_id)
1022        .instantiate_identity()
1023        .skip_norm_wip()
1024        .no_bound_vars()
1025        .expect("LBR in ADT constructor signature");
1026    let sig = tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(sig));
1027
1028    let ty::Adt(adt_def, args) = sig.output().kind() else {
1029        ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected type for ADT ctor {0:?}", sig.output()),
    Location::caller());bug!("unexpected type for ADT ctor {:?}", sig.output());
1030    };
1031
1032    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:1032",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(1032u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_ctor: ctor_id={0:?} sig={1:?}",
                                                    ctor_id, sig) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
1033
1034    let span = tcx.def_span(ctor_id);
1035
1036    let local_decls = local_decls_for_sig(&sig, span);
1037
1038    let source_info = SourceInfo::outermost(span);
1039
1040    let variant_index =
1041        if adt_def.is_enum() { adt_def.variant_index_with_ctor_id(ctor_id) } else { FIRST_VARIANT };
1042
1043    // Generate the following MIR:
1044    //
1045    // (return as Variant).field0 = arg0;
1046    // (return as Variant).field1 = arg1;
1047    //
1048    // return;
1049    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs:1049",
                        "rustc_mir_transform::shim", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/75a3786afbc93bbddf2c0259033b63957b45ace1/compiler/rustc_mir_transform/src/shim.rs"),
                        ::tracing_core::__macro_support::Option::Some(1049u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_transform::shim"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_ctor: variant_index={0:?}",
                                                    variant_index) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_ctor: variant_index={:?}", variant_index);
1050
1051    let kind = AggregateKind::Adt(adt_def.did(), variant_index, *args, None, None);
1052    let variant = adt_def.variant(variant_index);
1053    let statement = Statement::new(
1054        source_info,
1055        StatementKind::Assign(Box::new((
1056            Place::return_place(),
1057            Rvalue::Aggregate(
1058                Box::new(kind),
1059                (0..variant.fields.len())
1060                    .map(|idx| Operand::Move(Place::from(Local::arg(idx))))
1061                    .collect(),
1062            ),
1063        ))),
1064    );
1065
1066    let start_block = BasicBlockData::new_stmts(
1067        {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(statement);
    vec
}thin_vec![statement],
1068        Terminator { source_info, kind: TerminatorKind::Return },
1069        false,
1070    );
1071
1072    let source = MirSource::item(ctor_id);
1073    let mut body = new_body(
1074        source,
1075        IndexVec::from_elem_n(start_block, 1),
1076        local_decls,
1077        sig.inputs().len(),
1078        span,
1079    );
1080    // A constructor doesn't mention any other items (and we don't run the usual optimization passes
1081    // so this would otherwise not get filled).
1082    body.set_mentioned_items(Vec::new());
1083
1084    // We don't pass any passes here, we just force a phase change to `Optimized`.
1085    // Otherwise this bit of MIR will trigger assertions trying to detect MIR with an invalid phase.
1086    pm::run_passes_no_validate(
1087        tcx,
1088        &mut body,
1089        &[],
1090        Some(MirPhase::Runtime(RuntimePhase::Optimized)),
1091    );
1092
1093    body
1094}
1095
1096/// ```ignore (pseudo-impl)
1097/// impl FnPtr for fn(u32) {
1098///     fn addr(self) -> NonNull<Code> {
1099///         unsafe { transmute(self as *const Code)}
1100///     }
1101/// }
1102/// ```
1103fn build_fn_addr_as_ptr_shim<'tcx>(
1104    tcx: TyCtxt<'tcx>,
1105    def_id: DefId,
1106    self_ty: Ty<'tcx>,
1107) -> Body<'tcx> {
1108    {
    match self_ty.kind() {
        ty::FnPtr(..) | ty::FnDef(..) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "ty::FnPtr(..) | ty::FnDef(..)",
                ::core::option::Option::Some(format_args!("expected fn ptr or function def, found {0}",
                        self_ty)));
        }
    }
};assert_matches!(
1109        self_ty.kind(),
1110        ty::FnPtr(..) | ty::FnDef(..),
1111        "expected fn ptr or function def, found {self_ty}"
1112    );
1113
1114    let span = tcx.def_span(def_id);
1115    let nonnull_did = tcx.require_lang_item(LangItem::NonNull, span);
1116    let code_did = tcx.require_lang_item(LangItem::Code, span);
1117    let nonnull_ty = tcx
1118        .type_of(nonnull_did)
1119        .instantiate(
1120            tcx,
1121            &[ty::GenericArg::from(tcx.type_of(code_did).instantiate_identity().skip_norm_wip())],
1122        )
1123        .skip_norm_wip();
1124
1125    let Some(sig) =
1126        tcx.fn_sig(def_id).instantiate(tcx, &[self_ty.into()]).skip_norm_wip().no_bound_vars()
1127    else {
1128        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("FnAddr::as_ptr with bound vars for `{0}`", self_ty),
    Location::caller());span_bug!(span, "FnAddr::as_ptr with bound vars for `{self_ty}`");
1129    };
1130    let mut locals = local_decls_for_sig(&sig, span);
1131
1132    let source_info = SourceInfo::outermost(span);
1133
1134    let mut statements = ::thin_vec::ThinVec::new()thin_vec![];
1135    // FIXME: use `expose_provenance` once we figure out whether function pointers have meaningful
1136    // provenance.
1137    let raw_unit_ptr = Ty::new_imm_ptr(tcx, tcx.types.unit);
1138
1139    let fn_ptr_operand = match self_ty.kind() {
1140        ty::FnDef(..) => {
1141            let fn_sig = self_ty.fn_sig(tcx);
1142            let fn_ptr_ty = Ty::new_fn_ptr(tcx, fn_sig);
1143            let fn_ptr =
1144                Place::from(locals.push(LocalDecl::with_source_info(fn_ptr_ty, source_info)));
1145
1146            statements.push(Statement::new(
1147                source_info,
1148                StatementKind::Assign(Box::new((
1149                    fn_ptr,
1150                    Rvalue::Cast(
1151                        CastKind::PointerCoercion(
1152                            ty::adjustment::PointerCoercion::ReifyFnPointer(fn_sig.safety()),
1153                            CoercionSource::Implicit,
1154                        ),
1155                        Operand::Move(Place::from(Local::arg(0))),
1156                        fn_ptr_ty,
1157                    ),
1158                ))),
1159            ));
1160
1161            Operand::Move(fn_ptr)
1162        }
1163        _ => Operand::Move(Place::from(Local::arg(0))),
1164    };
1165
1166    let cast_to_raw_rvalue = Rvalue::Cast(CastKind::FnPtrToPtr, fn_ptr_operand, raw_unit_ptr);
1167
1168    let raw_ptr = locals.push(LocalDecl::with_source_info(raw_unit_ptr, source_info)).into();
1169    statements.push(Statement::new(
1170        source_info,
1171        StatementKind::Assign(Box::new((raw_ptr, cast_to_raw_rvalue))),
1172    ));
1173
1174    let transmute_to_nonnull =
1175        Rvalue::Cast(CastKind::Transmute, Operand::Move(Place::from(raw_ptr)), nonnull_ty);
1176    statements.push(Statement::new(
1177        source_info,
1178        StatementKind::Assign(Box::new((Place::return_place(), transmute_to_nonnull))),
1179    ));
1180
1181    let start_block = BasicBlockData::new_stmts(
1182        statements,
1183        Terminator { source_info, kind: TerminatorKind::Return },
1184        false,
1185    );
1186    let source = MirSource::from_shim(ty::ShimKind::FnAddrAsPtr(def_id, self_ty));
1187    new_body(source, IndexVec::from_elem_n(start_block, 1), locals, sig.inputs().len(), span)
1188}
1189
1190fn build_fn_ptr_from_ptr_shim<'tcx>(
1191    tcx: TyCtxt<'tcx>,
1192    def_id: DefId,
1193    self_ty: Ty<'tcx>,
1194) -> Body<'tcx> {
1195    {
    match self_ty.kind() {
        ty::FnPtr(..) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "ty::FnPtr(..)",
                ::core::option::Option::Some(format_args!("expected fn ptr, found {0}",
                        self_ty)));
        }
    }
};assert_matches!(self_ty.kind(), ty::FnPtr(..), "expected fn ptr, found {self_ty}");
1196
1197    let span = tcx.def_span(def_id);
1198
1199    let Some(sig) =
1200        tcx.fn_sig(def_id).instantiate(tcx, &[self_ty.into()]).skip_norm_wip().no_bound_vars()
1201    else {
1202        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("FnPtr::as_ptr with bound vars for `{0}`", self_ty),
    Location::caller());span_bug!(span, "FnPtr::as_ptr with bound vars for `{self_ty}`");
1203    };
1204    let locals = local_decls_for_sig(&sig, span);
1205
1206    let source_info = SourceInfo::outermost(span);
1207
1208    let mut statements = ::thin_vec::ThinVec::new()thin_vec![];
1209    let transmute_to_self =
1210        Rvalue::Cast(CastKind::Transmute, Operand::Move(Place::from(Local::arg(0))), self_ty);
1211    statements.push(Statement::new(
1212        source_info,
1213        StatementKind::Assign(Box::new((Place::return_place(), transmute_to_self))),
1214    ));
1215
1216    let start_block = BasicBlockData::new_stmts(
1217        statements,
1218        Terminator { source_info, kind: TerminatorKind::Return },
1219        false,
1220    );
1221    let source = MirSource::from_shim(ty::ShimKind::FnPtrFromPtr(def_id, self_ty));
1222    new_body(source, IndexVec::from_elem_n(start_block, 1), locals, sig.inputs().len(), span)
1223}
1224
1225fn build_construct_coroutine_by_move_shim<'tcx>(
1226    tcx: TyCtxt<'tcx>,
1227    coroutine_closure_def_id: DefId,
1228    receiver_by_ref: bool,
1229) -> Body<'tcx> {
1230    let mut self_ty = tcx.type_of(coroutine_closure_def_id).instantiate_identity().skip_norm_wip();
1231    let mut self_local: Place<'tcx> = Local::arg(0).into();
1232    let ty::CoroutineClosure(_, args) = *self_ty.kind() else {
1233        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
1234    };
1235
1236    // We use `&Self` here because we only need to emit an ABI-compatible shim body,
1237    // rather than match the signature exactly (which might take `&mut self` instead).
1238    //
1239    // We adjust the `self_local` to be a deref since we want to copy fields out of
1240    // a reference to the closure.
1241    if receiver_by_ref {
1242        self_local = tcx.mk_place_deref(self_local);
1243        self_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, self_ty);
1244    }
1245
1246    let poly_sig = args.as_coroutine_closure().coroutine_closure_sig().map_bound(|sig| {
1247        tcx.mk_fn_sig(
1248            [self_ty].into_iter().chain(sig.tupled_inputs_ty.tuple_fields()),
1249            sig.to_coroutine_given_kind_and_upvars(
1250                tcx,
1251                args.as_coroutine_closure().parent_args(),
1252                tcx.coroutine_for_closure(coroutine_closure_def_id),
1253                ty::ClosureKind::FnOnce,
1254                tcx.lifetimes.re_erased,
1255                args.as_coroutine_closure().tupled_upvars_ty(),
1256                args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
1257            ),
1258            sig.fn_sig_kind,
1259        )
1260    });
1261    let sig = tcx.liberate_late_bound_regions(coroutine_closure_def_id, poly_sig);
1262    let ty::Coroutine(coroutine_def_id, coroutine_args) = *sig.output().kind() else {
1263        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
1264    };
1265
1266    let span = tcx.def_span(coroutine_closure_def_id);
1267    let locals = local_decls_for_sig(&sig, span);
1268
1269    let mut fields = ::alloc::vec::Vec::new()vec![];
1270
1271    // Move all of the closure args.
1272    for idx in 1..sig.inputs().len() {
1273        fields.push(Operand::Move(Local::arg(idx).into()));
1274    }
1275
1276    for (idx, ty) in args.as_coroutine_closure().upvar_tys().iter().enumerate() {
1277        if receiver_by_ref {
1278            // The only situation where it's possible is when we capture immuatable references,
1279            // since those don't need to be reborrowed with the closure's env lifetime. Since
1280            // references are always `Copy`, just emit a copy.
1281            if !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Ref(_, _, hir::Mutability::Not) => true,
    _ => false,
}matches!(ty.kind(), ty::Ref(_, _, hir::Mutability::Not)) {
1282                // This copy is only sound if it's a `&T`. This may be
1283                // reachable e.g. when eagerly computing the `Fn` instance
1284                // of an async closure that doesn't borrowck.
1285                tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("field should be captured by immutable ref if we have an `Fn` instance, but it was: {0}",
                ty))
    })format!(
1286                    "field should be captured by immutable ref if we have \
1287                    an `Fn` instance, but it was: {ty}"
1288                ));
1289            }
1290            fields.push(Operand::Copy(tcx.mk_place_field(
1291                self_local,
1292                FieldIdx::from_usize(idx),
1293                ty,
1294            )));
1295        } else {
1296            fields.push(Operand::Move(tcx.mk_place_field(
1297                self_local,
1298                FieldIdx::from_usize(idx),
1299                ty,
1300            )));
1301        }
1302    }
1303
1304    let source_info = SourceInfo::outermost(span);
1305    let rvalue = Rvalue::Aggregate(
1306        Box::new(AggregateKind::Coroutine(coroutine_def_id, coroutine_args)),
1307        IndexVec::from_raw(fields),
1308    );
1309    let stmt = Statement::new(
1310        source_info,
1311        StatementKind::Assign(Box::new((Place::return_place(), rvalue))),
1312    );
1313    let statements = {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(stmt);
    vec
}thin_vec![stmt];
1314    let start_block = BasicBlockData::new_stmts(
1315        statements,
1316        Terminator { source_info, kind: TerminatorKind::Return },
1317        false,
1318    );
1319
1320    let source = MirSource::from_shim(ty::ShimKind::ConstructCoroutineInClosure {
1321        coroutine_closure_def_id,
1322        receiver_by_ref,
1323    });
1324
1325    let body =
1326        new_body(source, IndexVec::from_elem_n(start_block, 1), locals, sig.inputs().len(), span);
1327
1328    let pass_name =
1329        if receiver_by_ref { "coroutine_closure_by_ref" } else { "coroutine_closure_by_move" };
1330    if let Some(dumper) = MirDumper::new(tcx, pass_name, &body) {
1331        dumper.dump_mir(&body);
1332    }
1333
1334    body
1335}