Skip to main content

rustc_ty_utils/
abi.rs

1use std::{assert_matches, iter};
2
3use rustc_abi::Primitive::Pointer;
4use rustc_abi::{Align, BackendRepr, ExternAbi, PointerKind, Scalar, Size};
5use rustc_hir::attrs::lang_items::LangItem;
6use rustc_hir::{self as hir, find_attr};
7use rustc_middle::bug;
8use rustc_middle::middle::deduced_param_attrs::DeducedParamAttrs;
9use rustc_middle::query::Providers;
10use rustc_middle::ty::layout::{
11    FnAbiError, HasTyCtxt, HasTypingEnv, LayoutCx, LayoutOf, TyAndLayout, fn_can_unwind,
12};
13use rustc_middle::ty::{self, InstanceKind, ShimKind, Ty, TyCtxt, Unnormalized};
14use rustc_span::DUMMY_SP;
15use rustc_span::def_id::DefId;
16use rustc_target::callconv::{AbiMap, ArgAbi, ArgAttribute, ArgAttributes, FnAbi, PassMode};
17use tracing::debug;
18
19pub(crate) fn provide(providers: &mut Providers) {
20    *providers = Providers {
21        fn_abi_of_fn_ptr,
22        fn_abi_of_instance_no_deduced_attrs,
23        fn_abi_of_instance_raw,
24        ..*providers
25    };
26}
27
28// NOTE(eddyb) this is private to avoid using it from outside of
29// `fn_abi_of_instance` - any other uses are either too high-level
30// for `Instance` (e.g. typeck would use `Ty::fn_sig` instead),
31// or should go through `FnAbi` instead, to avoid losing any
32// adjustments `fn_abi_of_instance` might be performing.
33#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_sig_for_fn_abi",
                                    "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                    ::tracing_core::__macro_support::Option::Some(33u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        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(&instance)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ty::FnSig<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let InstanceKind::Shim(ShimKind::ThreadLocal(..)) =
                    instance.def {
                return tcx.mk_fn_sig_safe_rust_abi([],
                        tcx.thread_local_ptr_ty(instance.def_id()));
            }
            let ty = instance.ty(tcx, typing_env);
            match *ty.kind() {
                ty::FnDef(def_id, args) => {
                    let mut sig =
                        tcx.instantiate_bound_regions_with_erased(tcx.fn_sig(def_id).instantiate(tcx,
                                    args.no_bound_vars().unwrap()).skip_norm_wip());
                    if let ty::InstanceKind::Shim(ty::ShimKind::VTable(..)) =
                            instance.def {
                        let mut inputs_and_output = sig.inputs_and_output.to_vec();
                        inputs_and_output[0] =
                            Ty::new_mut_ptr(tcx, inputs_and_output[0]);
                        sig.inputs_and_output =
                            tcx.mk_type_list(&inputs_and_output);
                    }
                    sig
                }
                ty::Closure(def_id, args) => {
                    let sig =
                        tcx.instantiate_bound_regions_with_erased(args.as_closure().sig());
                    let env_ty =
                        tcx.closure_env_ty(Ty::new_closure(tcx, def_id, args),
                            args.as_closure().kind(), tcx.lifetimes.re_erased);
                    tcx.mk_fn_sig(iter::once(env_ty).chain(sig.inputs().iter().cloned()),
                        sig.output(), sig.fn_sig_kind)
                }
                ty::CoroutineClosure(def_id, args) => {
                    let coroutine_ty =
                        Ty::new_coroutine_closure(tcx, def_id, args);
                    let sig =
                        args.as_coroutine_closure().coroutine_closure_sig();
                    let mut coroutine_kind = args.as_coroutine_closure().kind();
                    let env_ty =
                        if let InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure {
                                receiver_by_ref, .. }) = instance.def {
                            coroutine_kind = ty::ClosureKind::FnOnce;
                            if receiver_by_ref {
                                Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty)
                            } else { coroutine_ty }
                        } else {
                            tcx.closure_env_ty(coroutine_ty, coroutine_kind,
                                tcx.lifetimes.re_erased)
                        };
                    let sig = tcx.instantiate_bound_regions_with_erased(sig);
                    tcx.mk_fn_sig(iter::once(env_ty).chain([sig.tupled_inputs_ty]),
                        sig.to_coroutine_given_kind_and_upvars(tcx,
                            args.as_coroutine_closure().parent_args(),
                            tcx.coroutine_for_closure(def_id), coroutine_kind,
                            tcx.lifetimes.re_erased,
                            args.as_coroutine_closure().tupled_upvars_ty(),
                            args.as_coroutine_closure().coroutine_captures_by_ref_ty()),
                        sig.fn_sig_kind)
                }
                ty::Coroutine(did, args) => {
                    let coroutine_kind = tcx.coroutine_kind(did).unwrap();
                    let sig = args.as_coroutine().sig();
                    let env_ty =
                        Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
                    let pin_did =
                        tcx.require_lang_item(LangItem::Pin, DUMMY_SP);
                    let pin_adt_ref = tcx.adt_def(pin_did);
                    let pin_args = tcx.mk_args(&[env_ty.into()]);
                    let env_ty =
                        match coroutine_kind {
                            hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                _) => {
                                env_ty
                            }
                            hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                _) |
                                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                _) | hir::CoroutineKind::Coroutine(_) =>
                                Ty::new_adt(tcx, pin_adt_ref, pin_args),
                        };
                    let (resume_ty, ret_ty) =
                        match coroutine_kind {
                            hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async,
                                _) => {
                                {
                                    match (&sig.yield_ty, &tcx.types.unit) {
                                        (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 poll_did =
                                    tcx.require_lang_item(LangItem::Poll, DUMMY_SP);
                                let poll_adt_ref = tcx.adt_def(poll_did);
                                let poll_args = tcx.mk_args(&[sig.return_ty.into()]);
                                let ret_ty = Ty::new_adt(tcx, poll_adt_ref, poll_args);
                                {
                                    if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
                                        let expected_adt =
                                            tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy,
                                                    DUMMY_SP));
                                        {
                                            match (&*resume_ty_adt, &expected_adt) {
                                                (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);
                                                    }
                                                }
                                            }
                                        };
                                    } else {
                                        {
                                            ::core::panicking::panic_fmt(format_args!("expected `ResumeTy`, found `{0:?}`",
                                                    sig.resume_ty));
                                        };
                                    };
                                }
                                let context_mut_ref = Ty::new_task_context(tcx);
                                (Some(context_mut_ref), ret_ty)
                            }
                            hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen,
                                _) => {
                                let option_did =
                                    tcx.require_lang_item(LangItem::Option, DUMMY_SP);
                                let option_adt_ref = tcx.adt_def(option_did);
                                let option_args = tcx.mk_args(&[sig.yield_ty.into()]);
                                let ret_ty = Ty::new_adt(tcx, option_adt_ref, option_args);
                                {
                                    match (&sig.return_ty, &tcx.types.unit) {
                                        (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);
                                            }
                                        }
                                    }
                                };
                                {
                                    match (&sig.resume_ty, &tcx.types.unit) {
                                        (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);
                                            }
                                        }
                                    }
                                };
                                (None, ret_ty)
                            }
                            hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen,
                                _) => {
                                {
                                    match (&sig.return_ty, &tcx.types.unit) {
                                        (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 ret_ty = sig.yield_ty;
                                {
                                    if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
                                        let expected_adt =
                                            tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy,
                                                    DUMMY_SP));
                                        {
                                            match (&*resume_ty_adt, &expected_adt) {
                                                (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);
                                                    }
                                                }
                                            }
                                        };
                                    } else {
                                        {
                                            ::core::panicking::panic_fmt(format_args!("expected `ResumeTy`, found `{0:?}`",
                                                    sig.resume_ty));
                                        };
                                    };
                                }
                                let context_mut_ref = Ty::new_task_context(tcx);
                                (Some(context_mut_ref), ret_ty)
                            }
                            hir::CoroutineKind::Coroutine(_) => {
                                let state_did =
                                    tcx.require_lang_item(LangItem::CoroutineState, DUMMY_SP);
                                let state_adt_ref = tcx.adt_def(state_did);
                                let state_args =
                                    tcx.mk_args(&[sig.yield_ty.into(), sig.return_ty.into()]);
                                let ret_ty = Ty::new_adt(tcx, state_adt_ref, state_args);
                                (Some(sig.resume_ty), ret_ty)
                            }
                        };
                    if let Some(resume_ty) = resume_ty {
                        tcx.mk_fn_sig_safe_rust_abi([env_ty, resume_ty], ret_ty)
                    } else { tcx.mk_fn_sig_safe_rust_abi([env_ty], ret_ty) }
                }
                _ =>
                    ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type {0:?} in Instance::fn_sig",
                            ty)),
            }
        }
    }
}#[tracing::instrument(level = "debug", skip(tcx, typing_env))]
34fn fn_sig_for_fn_abi<'tcx>(
35    tcx: TyCtxt<'tcx>,
36    instance: ty::Instance<'tcx>,
37    typing_env: ty::TypingEnv<'tcx>,
38) -> ty::FnSig<'tcx> {
39    if let InstanceKind::Shim(ShimKind::ThreadLocal(..)) = instance.def {
40        return tcx.mk_fn_sig_safe_rust_abi([], tcx.thread_local_ptr_ty(instance.def_id()));
41    }
42
43    let ty = instance.ty(tcx, typing_env);
44    match *ty.kind() {
45        ty::FnDef(def_id, args) => {
46            let mut sig = tcx.instantiate_bound_regions_with_erased(
47                tcx.fn_sig(def_id).instantiate(tcx, args.no_bound_vars().unwrap()).skip_norm_wip(),
48            );
49
50            // Modify `fn(self, ...)` to `fn(self: *mut Self, ...)`.
51            if let ty::InstanceKind::Shim(ty::ShimKind::VTable(..)) = instance.def {
52                let mut inputs_and_output = sig.inputs_and_output.to_vec();
53                inputs_and_output[0] = Ty::new_mut_ptr(tcx, inputs_and_output[0]);
54                sig.inputs_and_output = tcx.mk_type_list(&inputs_and_output);
55            }
56
57            sig
58        }
59        ty::Closure(def_id, args) => {
60            let sig = tcx.instantiate_bound_regions_with_erased(args.as_closure().sig());
61            let env_ty = tcx.closure_env_ty(
62                Ty::new_closure(tcx, def_id, args),
63                args.as_closure().kind(),
64                tcx.lifetimes.re_erased,
65            );
66
67            tcx.mk_fn_sig(
68                iter::once(env_ty).chain(sig.inputs().iter().cloned()),
69                sig.output(),
70                sig.fn_sig_kind,
71            )
72        }
73        ty::CoroutineClosure(def_id, args) => {
74            let coroutine_ty = Ty::new_coroutine_closure(tcx, def_id, args);
75            let sig = args.as_coroutine_closure().coroutine_closure_sig();
76
77            // When this `CoroutineClosure` comes from a `ConstructCoroutineInClosureShim`,
78            // make sure we respect the `target_kind` in that shim.
79            // FIXME(async_closures): This shouldn't be needed, and we should be populating
80            // a separate def-id for these bodies.
81            let mut coroutine_kind = args.as_coroutine_closure().kind();
82
83            let env_ty = if let InstanceKind::Shim(ShimKind::ConstructCoroutineInClosure {
84                receiver_by_ref,
85                ..
86            }) = instance.def
87            {
88                coroutine_kind = ty::ClosureKind::FnOnce;
89
90                // Implementations of `FnMut` and `Fn` for coroutine-closures
91                // still take their receiver by ref.
92                if receiver_by_ref {
93                    Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty)
94                } else {
95                    coroutine_ty
96                }
97            } else {
98                tcx.closure_env_ty(coroutine_ty, coroutine_kind, tcx.lifetimes.re_erased)
99            };
100
101            let sig = tcx.instantiate_bound_regions_with_erased(sig);
102
103            tcx.mk_fn_sig(
104                iter::once(env_ty).chain([sig.tupled_inputs_ty]),
105                sig.to_coroutine_given_kind_and_upvars(
106                    tcx,
107                    args.as_coroutine_closure().parent_args(),
108                    tcx.coroutine_for_closure(def_id),
109                    coroutine_kind,
110                    tcx.lifetimes.re_erased,
111                    args.as_coroutine_closure().tupled_upvars_ty(),
112                    args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
113                ),
114                sig.fn_sig_kind,
115            )
116        }
117        ty::Coroutine(did, args) => {
118            let coroutine_kind = tcx.coroutine_kind(did).unwrap();
119            let sig = args.as_coroutine().sig();
120
121            let env_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
122
123            let pin_did = tcx.require_lang_item(LangItem::Pin, DUMMY_SP);
124            let pin_adt_ref = tcx.adt_def(pin_did);
125            let pin_args = tcx.mk_args(&[env_ty.into()]);
126            let env_ty = match coroutine_kind {
127                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {
128                    // Iterator::next doesn't accept a pinned argument,
129                    // unlike for all other coroutine kinds.
130                    env_ty
131                }
132                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
133                | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)
134                | hir::CoroutineKind::Coroutine(_) => Ty::new_adt(tcx, pin_adt_ref, pin_args),
135            };
136
137            // The `FnSig` and the `ret_ty` here is for a coroutines main
138            // `Coroutine::resume(...) -> CoroutineState` function in case we
139            // have an ordinary coroutine, the `Future::poll(...) -> Poll`
140            // function in case this is a special coroutine backing an async construct
141            // or the `Iterator::next(...) -> Option` function in case this is a
142            // special coroutine backing a gen construct.
143            let (resume_ty, ret_ty) = match coroutine_kind {
144                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _) => {
145                    // The signature should be `Future::poll(_, &mut Context<'_>) -> Poll<Output>`
146                    assert_eq!(sig.yield_ty, tcx.types.unit);
147
148                    let poll_did = tcx.require_lang_item(LangItem::Poll, DUMMY_SP);
149                    let poll_adt_ref = tcx.adt_def(poll_did);
150                    let poll_args = tcx.mk_args(&[sig.return_ty.into()]);
151                    let ret_ty = Ty::new_adt(tcx, poll_adt_ref, poll_args);
152
153                    // We have to replace the `ResumeTy` that is used for type and borrow checking
154                    // with `&mut Context<'_>` which is used in codegen.
155                    #[cfg(debug_assertions)]
156                    {
157                        if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
158                            let expected_adt =
159                                tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, DUMMY_SP));
160                            assert_eq!(*resume_ty_adt, expected_adt);
161                        } else {
162                            panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
163                        };
164                    }
165                    let context_mut_ref = Ty::new_task_context(tcx);
166
167                    (Some(context_mut_ref), ret_ty)
168                }
169                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {
170                    // The signature should be `Iterator::next(_) -> Option<Yield>`
171                    let option_did = tcx.require_lang_item(LangItem::Option, DUMMY_SP);
172                    let option_adt_ref = tcx.adt_def(option_did);
173                    let option_args = tcx.mk_args(&[sig.yield_ty.into()]);
174                    let ret_ty = Ty::new_adt(tcx, option_adt_ref, option_args);
175
176                    assert_eq!(sig.return_ty, tcx.types.unit);
177                    assert_eq!(sig.resume_ty, tcx.types.unit);
178
179                    (None, ret_ty)
180                }
181                hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => {
182                    // The signature should be
183                    // `AsyncIterator::poll_next(_, &mut Context<'_>) -> Poll<Option<Output>>`
184                    assert_eq!(sig.return_ty, tcx.types.unit);
185
186                    // Yield type is already `Poll<Option<yield_ty>>`
187                    let ret_ty = sig.yield_ty;
188
189                    // We have to replace the `ResumeTy` that is used for type and borrow checking
190                    // with `&mut Context<'_>` which is used in codegen.
191                    #[cfg(debug_assertions)]
192                    {
193                        if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
194                            let expected_adt =
195                                tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, DUMMY_SP));
196                            assert_eq!(*resume_ty_adt, expected_adt);
197                        } else {
198                            panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
199                        };
200                    }
201                    let context_mut_ref = Ty::new_task_context(tcx);
202
203                    (Some(context_mut_ref), ret_ty)
204                }
205                hir::CoroutineKind::Coroutine(_) => {
206                    // The signature should be `Coroutine::resume(_, Resume) -> CoroutineState<Yield, Return>`
207                    let state_did = tcx.require_lang_item(LangItem::CoroutineState, DUMMY_SP);
208                    let state_adt_ref = tcx.adt_def(state_did);
209                    let state_args = tcx.mk_args(&[sig.yield_ty.into(), sig.return_ty.into()]);
210                    let ret_ty = Ty::new_adt(tcx, state_adt_ref, state_args);
211
212                    (Some(sig.resume_ty), ret_ty)
213                }
214            };
215
216            if let Some(resume_ty) = resume_ty {
217                tcx.mk_fn_sig_safe_rust_abi([env_ty, resume_ty], ret_ty)
218            } else {
219                // `Iterator::next` doesn't have a `resume` argument.
220                tcx.mk_fn_sig_safe_rust_abi([env_ty], ret_ty)
221            }
222        }
223        _ => bug!("unexpected type {:?} in Instance::fn_sig", ty),
224    }
225}
226
227/// Describes a function for determination of its ABI.
228struct FnAbiDesc<'tcx> {
229    layout_cx: LayoutCx<'tcx>,
230    sig: ty::FnSig<'tcx>,
231
232    /// The function's definition, if its body can be used to deduce parameter attributes.
233    determined_fn_def_id: Option<DefId>,
234    caller_location: Option<Ty<'tcx>>,
235    is_virtual_call: bool,
236    extra_args: &'tcx [Ty<'tcx>],
237}
238
239impl<'tcx> FnAbiDesc<'tcx> {
240    fn for_fn_ptr(
241        tcx: TyCtxt<'tcx>,
242        query: ty::PseudoCanonicalInput<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
243    ) -> Self {
244        let ty::PseudoCanonicalInput { typing_env, value: (sig, extra_args) } = query;
245        Self {
246            layout_cx: LayoutCx::new(tcx, typing_env),
247            sig: tcx.normalize_erasing_regions(
248                typing_env,
249                Unnormalized::new_wip(tcx.instantiate_bound_regions_with_erased(sig)),
250            ),
251            // Parameter attributes can never be deduced for indirect calls, as there is no
252            // function body available to use.
253            determined_fn_def_id: None,
254            caller_location: None,
255            is_virtual_call: false,
256            extra_args,
257        }
258    }
259
260    fn for_instance(
261        tcx: TyCtxt<'tcx>,
262        query: ty::PseudoCanonicalInput<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
263    ) -> Self {
264        let ty::PseudoCanonicalInput { typing_env, value: (instance, extra_args) } = query;
265        let is_virtual_call = #[allow(non_exhaustive_omitted_patterns)] match instance.def {
    ty::InstanceKind::Virtual(..) => true,
    _ => false,
}matches!(instance.def, ty::InstanceKind::Virtual(..));
266        let is_tls_shim_call =
267            #[allow(non_exhaustive_omitted_patterns)] match instance.def {
    ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(_)) => true,
    _ => false,
}matches!(instance.def, ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(_)));
268        Self {
269            layout_cx: LayoutCx::new(tcx, typing_env),
270            sig: tcx.normalize_erasing_regions(
271                typing_env,
272                Unnormalized::new_wip(fn_sig_for_fn_abi(tcx, instance, typing_env)),
273            ),
274            // Parameter attributes can be deduced from the bodies of neither:
275            // - virtual calls, as they might call other functions from the vtable; nor
276            // - TLS shims, as they would refer to the underlying static.
277            determined_fn_def_id: (!is_virtual_call && !is_tls_shim_call)
278                .then(|| instance.def_id()),
279            caller_location: instance
280                .def
281                .requires_caller_location(tcx)
282                .then(|| tcx.caller_location_ty()),
283            is_virtual_call,
284            extra_args,
285        }
286    }
287}
288
289fn fn_abi_of_fn_ptr<'tcx>(
290    tcx: TyCtxt<'tcx>,
291    query: ty::PseudoCanonicalInput<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
292) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
293    let desc = FnAbiDesc::for_fn_ptr(tcx, query);
294    fn_abi_new_uncached(desc)
295}
296
297fn fn_abi_of_instance_no_deduced_attrs<'tcx>(
298    tcx: TyCtxt<'tcx>,
299    query: ty::PseudoCanonicalInput<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
300) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
301    let desc = FnAbiDesc::for_instance(tcx, query);
302    fn_abi_new_uncached(desc)
303}
304
305fn fn_abi_of_instance_raw<'tcx>(
306    tcx: TyCtxt<'tcx>,
307    query: ty::PseudoCanonicalInput<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
308) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
309    // The `fn_abi_of_instance_no_deduced_attrs` query may have been called during CTFE, so we
310    // delegate to it here in order to reuse (and, if necessary, augment) its result.
311    tcx.fn_abi_of_instance_no_deduced_attrs(query).map(|fn_abi| {
312        let params = FnAbiDesc::for_instance(tcx, query);
313        // If the function's body can be used to deduce parameter attributes, then adjust such
314        // "no deduced attrs" ABI; otherwise, return that ABI unadjusted.
315        params.determined_fn_def_id.map_or(fn_abi, |fn_def_id| {
316            fn_abi_adjust_for_deduced_attrs(&params.layout_cx, fn_abi, params.sig.abi(), fn_def_id)
317        })
318    })
319}
320
321/// Returns argument attributes for a scalar argument.
322fn arg_attrs_for_rust_scalar<'tcx>(
323    cx: LayoutCx<'tcx>,
324    scalar: Scalar,
325    layout: TyAndLayout<'tcx>,
326    offset: Size,
327    is_return: bool,
328    determined_fn_def_id: Option<DefId>,
329) -> ArgAttributes {
330    let mut attrs = ArgAttributes::new();
331
332    if !scalar.is_uninit_valid() {
333        attrs.set(ArgAttribute::NoUndef);
334    }
335
336    // Only pointer types handled below.
337    let Scalar::Initialized { value: Pointer(_), valid_range } = scalar else { return attrs };
338
339    // Set `nonnull` if the validity range excludes zero.
340    if !valid_range.contains(0) {
341        attrs.set(ArgAttribute::NonNull);
342    }
343
344    let tcx = cx.tcx();
345
346    if let Some(pointee) = layout.pointee_info_at(&cx, offset) {
347        if pointee.align > Align::ONE {
348            attrs.pointee_align =
349                Some(pointee.align.min(cx.tcx().sess.target.max_reliable_alignment()));
350        }
351
352        attrs.pointee_size = pointee.size;
353
354        if let Some(kind) = pointee.safe {
355            // The aliasing rules for `Box<T>` are still not decided, but currently we emit
356            // `noalias` for it. This can be turned off using an unstable flag.
357            // See https://github.com/rust-lang/unsafe-code-guidelines/issues/326
358            let noalias_for_box = tcx.sess.opts.unstable_opts.box_noalias;
359
360            // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
361            // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on memory
362            // dependencies rather than pointer equality. However this only applies to arguments,
363            // not return values.
364            //
365            // `&mut T` and `Box<T>` where `T: Unpin` are unique and hence `noalias`.
366            let no_alias = match kind {
367                PointerKind::SharedRef { frozen } => frozen,
368                PointerKind::MutableRef { unpin } => unpin,
369                PointerKind::Box { unpin, global } => unpin && global && noalias_for_box,
370            };
371            // We can never add `noalias` in return position; that LLVM attribute has some very surprising semantics
372            // (see <https://github.com/rust-lang/unsafe-code-guidelines/issues/385#issuecomment-1368055745>).
373            if no_alias && !is_return {
374                attrs.set(ArgAttribute::NoAlias);
375            }
376
377            // Set writable if no_alias is set, it's a mutable reference and the feature is enabled.
378            if tcx.sess.opts.unstable_opts.llvm_writable
379                && #[allow(non_exhaustive_omitted_patterns)] match kind {
    PointerKind::MutableRef { unpin: true } => true,
    _ => false,
}matches!(kind, PointerKind::MutableRef { unpin: true })
380                && !is_return
381            {
382                let rustc_no_writable = match determined_fn_def_id {
383                    Some(def_id) => {
        {
            'done:
                {
                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcNoWritable) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, def_id, RustcNoWritable),
384                    None => true, // If no def_id exists, we make the conservative choice and disable the feature.
385                };
386
387                if !rustc_no_writable {
388                    attrs.set(ArgAttribute::Writable);
389                }
390            }
391
392            // NoFree is not valid on return values. If it were, it would mean something like
393            // "will not be freed until the end of the program", which is generally not valid for
394            // references.
395            let no_free = !is_return
396                && match kind {
397                    // Non-frozen shared references are not necessarily dereferenceable for the
398                    // entire duration of the function
399                    // (see <https://github.com/rust-lang/rust/pull/98017>).
400                    PointerKind::SharedRef { frozen } => frozen,
401                    // Mutable references to potentially self-referential types are not necessarily
402                    // dereferenceable for the entire duration of the function
403                    // (see <https://github.com/rust-lang/unsafe-code-guidelines/issues/381>).
404                    PointerKind::MutableRef { unpin } => unpin,
405                    // Box may be deallocated during execution of the function.
406                    PointerKind::Box { .. } => false,
407                };
408            if no_free {
409                attrs.set(ArgAttribute::NoFree);
410            }
411
412            if #[allow(non_exhaustive_omitted_patterns)] match kind {
    PointerKind::SharedRef { frozen: true } => true,
    _ => false,
}matches!(kind, PointerKind::SharedRef { frozen: true }) && !is_return {
413                attrs.set(ArgAttribute::ReadOnly);
414                attrs.set(ArgAttribute::CapturesReadOnly);
415            }
416        }
417    }
418
419    attrs
420}
421
422/// Ensure that the ABI makes basic sense.
423fn fn_abi_sanity_check<'tcx>(
424    cx: &LayoutCx<'tcx>,
425    fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
426    spec_abi: ExternAbi,
427) {
428    fn fn_arg_attrs_sanity_check(attrs: &ArgAttributes, is_ret: bool) {
429        if attrs.regular.contains(ArgAttribute::NoFree) {
430            if !!is_ret {
    {
        ::core::panicking::panic_fmt(format_args!("NoFree not valid on return values"));
    }
};assert!(!is_ret, "NoFree not valid on return values");
431        }
432    }
433
434    fn fn_arg_sanity_check<'tcx>(
435        cx: &LayoutCx<'tcx>,
436        spec_abi: ExternAbi,
437        arg: &ArgAbi<'tcx, Ty<'tcx>>,
438        is_ret: bool,
439    ) {
440        let tcx = cx.tcx();
441
442        if spec_abi.is_rustic_abi() {
443            if arg.layout.is_zst() {
444                // Casting closures to function pointers depends on ZST closure types being
445                // omitted entirely in the calling convention.
446                if !arg.is_ignore() {
    ::core::panicking::panic("assertion failed: arg.is_ignore()")
};assert!(arg.is_ignore());
447            }
448            if let PassMode::Indirect { on_stack, .. } = arg.mode
449                && spec_abi != ExternAbi::RustTail
450            {
451                if !!on_stack {
    {
        ::core::panicking::panic_fmt(format_args!("rustic abi {0:?} shouldn\'t use on_stack",
                spec_abi));
    }
};assert!(!on_stack, "rustic abi {spec_abi:?} shouldn't use on_stack");
452            }
453        } else if arg.layout.pass_indirectly_in_non_rustic_abis(cx) {
454            {
    match arg.mode {
        PassMode::Indirect { on_stack: false, .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "PassMode::Indirect { on_stack: false, .. }",
                ::core::option::Option::Some(format_args!("the {0} ABI does not implement `#[rustc_pass_indirectly_in_non_rustic_abis]`",
                        spec_abi)));
        }
    }
};assert_matches!(
455                arg.mode,
456                PassMode::Indirect { on_stack: false, .. },
457                "the {spec_abi} ABI does not implement `#[rustc_pass_indirectly_in_non_rustic_abis]`"
458            );
459        }
460
461        match &arg.mode {
462            PassMode::Ignore => {
463                if !arg.layout.is_zst() {
    ::core::panicking::panic("assertion failed: arg.layout.is_zst()")
};assert!(arg.layout.is_zst());
464            }
465            PassMode::Direct(attrs) => {
466                // Here the Rust type is used to determine the actual ABI, so we have to be very
467                // careful. Scalar/Vector is fine, since backends will generally use
468                // `layout.backend_repr` and ignore everything else.
469                match arg.layout.backend_repr {
470                    BackendRepr::Scalar(_)
471                    | BackendRepr::SimdVector { .. }
472                    | BackendRepr::SimdScalableVector { .. } => {}
473                    BackendRepr::ScalarPair { .. } => {
474                        {
    ::core::panicking::panic_fmt(format_args!("`PassMode::Direct` used for ScalarPair type {0}",
            arg.layout.ty));
}panic!("`PassMode::Direct` used for ScalarPair type {}", arg.layout.ty)
475                    }
476                    BackendRepr::Memory { .. } => {
477                        {
    ::core::panicking::panic_fmt(format_args!("`PassMode::Direct` for aggregates not allowed\nProblematic type: {0:#?}",
            arg.layout));
};panic!(
478                            "`PassMode::Direct` for aggregates not allowed\n\
479                             Problematic type: {:#?}",
480                            arg.layout,
481                        );
482                    }
483                }
484                fn_arg_attrs_sanity_check(attrs, is_ret);
485            }
486            PassMode::Pair(attrs1, attrs2) => {
487                // Similar to `Direct`, we need to make sure that backends use `layout.backend_repr`
488                // and ignore the rest of the layout.
489                if !#[allow(non_exhaustive_omitted_patterns)] match arg.layout.backend_repr {
            BackendRepr::ScalarPair { .. } => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("PassMode::Pair for type {0}",
                arg.layout.ty));
    }
};assert!(
490                    matches!(arg.layout.backend_repr, BackendRepr::ScalarPair { .. }),
491                    "PassMode::Pair for type {}",
492                    arg.layout.ty
493                );
494                fn_arg_attrs_sanity_check(attrs1, is_ret);
495                fn_arg_attrs_sanity_check(attrs2, is_ret);
496            }
497            PassMode::Cast { .. } => {
498                // `Cast` means "transmute to `CastType`"; that only makes sense for sized types.
499                if !arg.layout.is_sized() {
    ::core::panicking::panic("assertion failed: arg.layout.is_sized()")
};assert!(arg.layout.is_sized());
500            }
501            PassMode::Indirect { meta_attrs: None, attrs, .. } => {
502                // No metadata, must be sized.
503                // Conceptually, unsized arguments must be copied around, which requires dynamically
504                // determining their size, which we cannot do without metadata. Consult
505                // t-opsem before removing this check.
506                if !arg.layout.is_sized() {
    ::core::panicking::panic("assertion failed: arg.layout.is_sized()")
};assert!(arg.layout.is_sized());
507                // Indirect returns are arguments from an ABI perspective.
508                fn_arg_attrs_sanity_check(attrs, false);
509            }
510            PassMode::Indirect { meta_attrs: Some(meta_attrs), attrs, on_stack } => {
511                // With metadata. Must be unsized and not on the stack.
512                if !(arg.layout.is_unsized() && !on_stack) {
    ::core::panicking::panic("assertion failed: arg.layout.is_unsized() && !on_stack")
};assert!(arg.layout.is_unsized() && !on_stack);
513                // Also, must not be `extern` type.
514                let tail = tcx.struct_tail_for_codegen(arg.layout.ty, cx.typing_env);
515                if #[allow(non_exhaustive_omitted_patterns)] match tail.kind() {
    ty::Foreign(..) => true,
    _ => false,
}matches!(tail.kind(), ty::Foreign(..)) {
516                    // These types do not have metadata, so having `meta_attrs` is bogus.
517                    // Conceptually, unsized arguments must be copied around, which requires dynamically
518                    // determining their size. Therefore, we cannot allow `extern` types here. Consult
519                    // t-opsem before removing this check.
520                    {
    ::core::panicking::panic_fmt(format_args!("unsized arguments must not be `extern` types"));
};panic!("unsized arguments must not be `extern` types");
521                }
522                // Indirect returns are arguments from an ABI perspective.
523                fn_arg_attrs_sanity_check(attrs, false);
524                fn_arg_attrs_sanity_check(meta_attrs, false);
525            }
526        }
527    }
528
529    for arg in fn_abi.args.iter() {
530        fn_arg_sanity_check(cx, spec_abi, arg, false);
531    }
532    fn_arg_sanity_check(cx, spec_abi, &fn_abi.ret, true);
533}
534
535#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("fn_abi_new_uncached",
                                    "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                    ::tracing_core::__macro_support::Option::Some(535u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                    ::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()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("extra_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("extra_args");
                                                        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(&sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<&'tcx FnAbi<'tcx, Ty<'tcx>>,
                    &'tcx FnAbiError<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = cx.tcx();
            let abi_map = AbiMap::from_target(&tcx.sess.target);
            let conv =
                abi_map.canonize_abi(sig.abi(), sig.c_variadic()).unwrap();
            let mut inputs = sig.inputs();
            let extra_args =
                if sig.abi() == ExternAbi::RustCall {
                    if !(!sig.c_variadic() && extra_args.is_empty()) {
                        ::core::panicking::panic("assertion failed: !sig.c_variadic() && extra_args.is_empty()")
                    };
                    if let Some(input) = sig.inputs().last() &&
                            let ty::Tuple(tupled_arguments) = input.kind() {
                        inputs = &sig.inputs()[0..sig.inputs().len() - 1];
                        tupled_arguments
                    } else {
                        ::rustc_middle::util::bug::bug_fmt(format_args!("argument to function with \"rust-call\" ABI is not a tuple"));
                    }
                } else {
                    if !(sig.c_variadic() || extra_args.is_empty()) {
                        ::core::panicking::panic("assertion failed: sig.c_variadic() || extra_args.is_empty()")
                    };
                    extra_args
                };
            let arg_of =
                |ty: Ty<'tcx>, arg_idx: Option<usize>|
                    -> Result<_, &'tcx FnAbiError<'tcx>>
                    {
                        let span =
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("arg_of",
                                                    "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(575u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                                    ::tracing_core::field::FieldSet::new(&[],
                                                        ::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,
                                        &{ meta.fields().value_set_all(&[]) })
                                } else {
                                    let span =
                                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                                    {};
                                    span
                                }
                            };
                        let _entered = span.enter();
                        let is_return = arg_idx.is_none();
                        let layout =
                            cx.layout_of(ty).map_err(|err|
                                        &*tcx.arena.alloc(FnAbiError::Layout(*err)))?;
                        let layout =
                            if is_virtual_call && arg_idx == Some(0) {
                                make_thin_self_ptr(cx, layout)
                            } else { layout };
                        Ok(ArgAbi::new(layout,
                                |scalar, offset|
                                    {
                                        arg_attrs_for_rust_scalar(*cx, scalar, layout, offset,
                                            is_return, determined_fn_def_id)
                                    }))
                    };
            let mut fn_abi =
                FnAbi {
                    ret: arg_of(sig.output(), None)?,
                    args: inputs.iter().copied().chain(extra_args.iter().copied()).chain(caller_location).enumerate().map(|(i,
                                        ty)| arg_of(ty, Some(i))).collect::<Result<_, _>>()?,
                    c_variadic: sig.c_variadic(),
                    fixed_count: inputs.len() as u32,
                    conv,
                    can_unwind: fn_can_unwind(tcx, determined_fn_def_id,
                        sig.abi()),
                };
            fn_abi_adjust_for_abi(cx, &mut fn_abi, sig.abi());
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/abi.rs:616",
                                    "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                    ::tracing_core::__macro_support::Option::Some(616u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                    ::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!("fn_abi_new_uncached = {0:?}",
                                                                fn_abi) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            fn_abi_sanity_check(cx, &fn_abi, sig.abi());
            Ok(tcx.arena.alloc(fn_abi))
        }
    }
}#[tracing::instrument(
536    level = "debug",
537    skip(cx, caller_location, determined_fn_def_id, is_virtual_call)
538)]
539fn fn_abi_new_uncached<'tcx>(
540    FnAbiDesc {
541        layout_cx: ref cx,
542        sig,
543        determined_fn_def_id,
544        caller_location,
545        is_virtual_call,
546        extra_args,
547    }: FnAbiDesc<'tcx>,
548) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
549    let tcx = cx.tcx();
550
551    let abi_map = AbiMap::from_target(&tcx.sess.target);
552    let conv = abi_map.canonize_abi(sig.abi(), sig.c_variadic()).unwrap();
553
554    let mut inputs = sig.inputs();
555    let extra_args = if sig.abi() == ExternAbi::RustCall {
556        assert!(!sig.c_variadic() && extra_args.is_empty());
557
558        if let Some(input) = sig.inputs().last()
559            && let ty::Tuple(tupled_arguments) = input.kind()
560        {
561            inputs = &sig.inputs()[0..sig.inputs().len() - 1];
562            tupled_arguments
563        } else {
564            bug!(
565                "argument to function with \"rust-call\" ABI \
566                    is not a tuple"
567            );
568        }
569    } else {
570        assert!(sig.c_variadic() || extra_args.is_empty());
571        extra_args
572    };
573
574    let arg_of = |ty: Ty<'tcx>, arg_idx: Option<usize>| -> Result<_, &'tcx FnAbiError<'tcx>> {
575        let span = tracing::debug_span!("arg_of");
576        let _entered = span.enter();
577        let is_return = arg_idx.is_none();
578
579        let layout = cx.layout_of(ty).map_err(|err| &*tcx.arena.alloc(FnAbiError::Layout(*err)))?;
580        let layout = if is_virtual_call && arg_idx == Some(0) {
581            // Don't pass the vtable, it's not an argument of the virtual fn.
582            // Instead, pass just the data pointer, but give it the type `*const/mut dyn Trait`
583            // or `&/&mut dyn Trait` because this is special-cased elsewhere in codegen
584            make_thin_self_ptr(cx, layout)
585        } else {
586            layout
587        };
588
589        Ok(ArgAbi::new(layout, |scalar, offset| {
590            arg_attrs_for_rust_scalar(*cx, scalar, layout, offset, is_return, determined_fn_def_id)
591        }))
592    };
593
594    let mut fn_abi = FnAbi {
595        ret: arg_of(sig.output(), None)?,
596        args: inputs
597            .iter()
598            .copied()
599            .chain(extra_args.iter().copied())
600            .chain(caller_location)
601            .enumerate()
602            .map(|(i, ty)| arg_of(ty, Some(i)))
603            .collect::<Result<_, _>>()?,
604        c_variadic: sig.c_variadic(),
605        fixed_count: inputs.len() as u32,
606        conv,
607        // FIXME return false for tls shim
608        can_unwind: fn_can_unwind(
609            tcx,
610            // Since `#[rustc_nounwind]` can change unwinding, we cannot infer unwinding by `fn_def_id` for a virtual call.
611            determined_fn_def_id,
612            sig.abi(),
613        ),
614    };
615    fn_abi_adjust_for_abi(cx, &mut fn_abi, sig.abi());
616    debug!("fn_abi_new_uncached = {:?}", fn_abi);
617    fn_abi_sanity_check(cx, &fn_abi, sig.abi());
618    Ok(tcx.arena.alloc(fn_abi))
619}
620
621#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("fn_abi_adjust_for_abi",
                                    "rustc_ty_utils::abi", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                    ::tracing_core::__macro_support::Option::Some(621u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_abi")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_abi");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("abi")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("abi");
                                                        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::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::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(&fn_abi)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&abi)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                match (&(abi), &(ExternAbi::Unadjusted)) {
                    (left_val, right_val) => {
                        if *left_val == *right_val {
                            let kind = ::core::panicking::AssertKind::Ne;
                            ::core::panicking::assert_failed(kind, &*left_val,
                                &*right_val,
                                ::core::option::Option::Some(format_args!("fn_abi_of_instance should not be called on LLVM intrinsics")));
                        }
                    }
                }
            };
            if abi.is_rustic_abi() {
                fn_abi.adjust_for_rust_abi(cx);
            } else { fn_abi.adjust_for_foreign_abi(cx, abi); }
        }
    }
}#[tracing::instrument(level = "trace", skip(cx))]
622fn fn_abi_adjust_for_abi<'tcx>(
623    cx: &LayoutCx<'tcx>,
624    fn_abi: &mut FnAbi<'tcx, Ty<'tcx>>,
625    abi: ExternAbi,
626) {
627    assert_ne!(
628        abi,
629        ExternAbi::Unadjusted,
630        "fn_abi_of_instance should not be called on LLVM intrinsics"
631    );
632
633    if abi.is_rustic_abi() {
634        fn_abi.adjust_for_rust_abi(cx);
635    } else {
636        fn_abi.adjust_for_foreign_abi(cx, abi);
637    }
638}
639
640#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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("fn_abi_adjust_for_deduced_attrs",
                                    "rustc_ty_utils::abi", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                    ::tracing_core::__macro_support::Option::Some(640u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_abi")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_abi");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("abi")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("abi");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_def_id");
                                                        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::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::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(&fn_abi)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&abi)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'tcx FnAbi<'tcx, Ty<'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = cx.tcx();
            let deduced =
                if abi.is_rustic_abi() {
                    tcx.deduced_param_attrs(fn_def_id)
                } else { &[] };
            if deduced.is_empty() {
                fn_abi
            } else {
                let mut fn_abi = fn_abi.clone();
                apply_deduced_attributes(cx, deduced, 0, &mut fn_abi.ret);
                for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() {
                    apply_deduced_attributes(cx, deduced, arg_idx + 1, arg);
                }
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/abi.rs:659",
                                        "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                        ::tracing_core::__macro_support::Option::Some(659u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                        ::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!("fn_abi_adjust_for_deduced_attrs = {0:?}",
                                                                    fn_abi) as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                fn_abi_sanity_check(cx, &fn_abi, abi);
                tcx.arena.alloc(fn_abi)
            }
        }
    }
}#[tracing::instrument(level = "trace", skip(cx))]
641fn fn_abi_adjust_for_deduced_attrs<'tcx>(
642    cx: &LayoutCx<'tcx>,
643    fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
644    abi: ExternAbi,
645    fn_def_id: DefId,
646) -> &'tcx FnAbi<'tcx, Ty<'tcx>> {
647    let tcx = cx.tcx();
648    // Look up the deduced parameter attributes for this function, if we have its def ID.
649    // We'll tag its parameters with those attributes as appropriate.
650    let deduced = if abi.is_rustic_abi() { tcx.deduced_param_attrs(fn_def_id) } else { &[] };
651    if deduced.is_empty() {
652        fn_abi
653    } else {
654        let mut fn_abi = fn_abi.clone();
655        apply_deduced_attributes(cx, deduced, 0, &mut fn_abi.ret);
656        for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() {
657            apply_deduced_attributes(cx, deduced, arg_idx + 1, arg);
658        }
659        debug!("fn_abi_adjust_for_deduced_attrs = {:?}", fn_abi);
660        fn_abi_sanity_check(cx, &fn_abi, abi);
661        tcx.arena.alloc(fn_abi)
662    }
663}
664
665/// Apply deduced optimization attributes to a parameter using an indirect pass mode.
666///
667/// `deduced` is a possibly truncated list of deduced attributes for a return place and arguments.
668/// `idx` the index of the parameter on the list (0 for a return place, and 1.. for arguments).
669fn apply_deduced_attributes<'tcx>(
670    cx: &LayoutCx<'tcx>,
671    deduced: &[DeducedParamAttrs],
672    idx: usize,
673    arg: &mut ArgAbi<'tcx, Ty<'tcx>>,
674) {
675    // Deduction is performed under the assumption of the indirection pass mode.
676    let PassMode::Indirect { ref mut attrs, .. } = arg.mode else {
677        return;
678    };
679    // The default values at the tail of the list are not encoded.
680    let Some(deduced) = deduced.get(idx) else {
681        return;
682    };
683    if deduced.read_only(cx.tcx(), cx.typing_env, arg.layout.ty) {
684        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/abi.rs:684",
                        "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                        ::tracing_core::__macro_support::Option::Some(684u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                        ::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!("added deduced ReadOnly attribute")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("added deduced ReadOnly attribute");
685        attrs.regular.insert(ArgAttribute::ReadOnly);
686    }
687    if deduced.captures_none(cx.tcx(), cx.typing_env, arg.layout.ty) {
688        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/abi.rs:688",
                        "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                        ::tracing_core::__macro_support::Option::Some(688u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                        ::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!("added deduced CapturesNone attribute")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("added deduced CapturesNone attribute");
689        attrs.regular.insert(ArgAttribute::CapturesNone);
690    }
691}
692
693#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("make_thin_self_ptr",
                                    "rustc_ty_utils::abi", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/abi.rs"),
                                    ::tracing_core::__macro_support::Option::Some(693u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::abi"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("layout")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("layout");
                                                        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(&layout)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: TyAndLayout<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = cx.tcx();
            let wide_pointer_ty =
                if layout.is_unsized() {
                    Ty::new_mut_ptr(tcx, layout.ty)
                } else {
                    match layout.backend_repr {
                        BackendRepr::ScalarPair { .. } | BackendRepr::Scalar(..) =>
                            (),
                        _ =>
                            ::rustc_middle::util::bug::bug_fmt(format_args!("receiver type has unsupported layout: {0:?}",
                                    layout)),
                    }
                    let mut wide_pointer_layout = layout;
                    while !wide_pointer_layout.ty.is_raw_ptr() &&
                            !wide_pointer_layout.ty.is_ref() {
                        wide_pointer_layout =
                            wide_pointer_layout.non_1zst_field(cx).expect("not exactly one non-1-ZST field in a `DispatchFromDyn` type").1
                    }
                    wide_pointer_layout.ty
                };
            let unit_ptr_ty = Ty::new_mut_ptr(tcx, tcx.types.unit);
            TyAndLayout {
                ty: wide_pointer_ty,
                ..tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(unit_ptr_ty)).unwrap()
            }
        }
    }
}#[tracing::instrument(level = "debug", skip(cx))]
694fn make_thin_self_ptr<'tcx>(
695    cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
696    layout: TyAndLayout<'tcx>,
697) -> TyAndLayout<'tcx> {
698    let tcx = cx.tcx();
699    let wide_pointer_ty = if layout.is_unsized() {
700        // unsized `self` is passed as a pointer to `self`
701        // FIXME (mikeyhew) change this to use &own if it is ever added to the language
702        Ty::new_mut_ptr(tcx, layout.ty)
703    } else {
704        match layout.backend_repr {
705            BackendRepr::ScalarPair { .. } | BackendRepr::Scalar(..) => (),
706            _ => bug!("receiver type has unsupported layout: {:?}", layout),
707        }
708
709        // In the case of Rc<Self>, we need to explicitly pass a *mut RcInner<Self>
710        // with a Scalar (not ScalarPair) ABI. This is a hack that is understood
711        // elsewhere in the compiler as a method on a `dyn Trait`.
712        // To get the type `*mut RcInner<Self>`, we just keep unwrapping newtypes until we
713        // get a built-in pointer type
714        let mut wide_pointer_layout = layout;
715        while !wide_pointer_layout.ty.is_raw_ptr() && !wide_pointer_layout.ty.is_ref() {
716            wide_pointer_layout = wide_pointer_layout
717                .non_1zst_field(cx)
718                .expect("not exactly one non-1-ZST field in a `DispatchFromDyn` type")
719                .1
720        }
721
722        wide_pointer_layout.ty
723    };
724
725    // we now have a type like `*mut RcInner<dyn Trait>`
726    // change its layout to that of `*mut ()`, a thin pointer, but keep the same type
727    // this is understood as a special case elsewhere in the compiler
728    let unit_ptr_ty = Ty::new_mut_ptr(tcx, tcx.types.unit);
729
730    TyAndLayout {
731        ty: wide_pointer_ty,
732
733        // NOTE(eddyb) using an empty `ParamEnv`, and `unwrap`-ing the `Result`
734        // should always work because the type is always `*mut ()`.
735        ..tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(unit_ptr_ty)).unwrap()
736    }
737}