]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/abi.rs
884087987ce08c6e98123a696e70730887c5f703
[rust.git] / compiler / rustc_ty_utils / src / abi.rs
1 use rustc_hir as hir;
2 use rustc_hir::lang_items::LangItem;
3 use rustc_middle::ty::layout::{
4     fn_can_unwind, FnAbiError, HasParamEnv, HasTyCtxt, LayoutCx, LayoutOf, TyAndLayout,
5 };
6 use rustc_middle::ty::{self, Ty, TyCtxt};
7 use rustc_session::config::OptLevel;
8 use rustc_span::def_id::DefId;
9 use rustc_target::abi::call::{
10     ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, Conv, FnAbi, PassMode, Reg, RegKind,
11 };
12 use rustc_target::abi::*;
13 use rustc_target::spec::abi::Abi as SpecAbi;
14
15 use std::iter;
16
17 pub fn provide(providers: &mut ty::query::Providers) {
18     *providers = ty::query::Providers { fn_abi_of_fn_ptr, fn_abi_of_instance, ..*providers };
19 }
20
21 // NOTE(eddyb) this is private to avoid using it from outside of
22 // `fn_abi_of_instance` - any other uses are either too high-level
23 // for `Instance` (e.g. typeck would use `Ty::fn_sig` instead),
24 // or should go through `FnAbi` instead, to avoid losing any
25 // adjustments `fn_abi_of_instance` might be performing.
26 #[tracing::instrument(level = "debug", skip(tcx, param_env))]
27 fn fn_sig_for_fn_abi<'tcx>(
28     tcx: TyCtxt<'tcx>,
29     instance: ty::Instance<'tcx>,
30     param_env: ty::ParamEnv<'tcx>,
31 ) -> ty::PolyFnSig<'tcx> {
32     let ty = instance.ty(tcx, param_env);
33     match *ty.kind() {
34         ty::FnDef(..) => {
35             // HACK(davidtwco,eddyb): This is a workaround for polymorphization considering
36             // parameters unused if they show up in the signature, but not in the `mir::Body`
37             // (i.e. due to being inside a projection that got normalized, see
38             // `tests/ui/polymorphization/normalized_sig_types.rs`), and codegen not keeping
39             // track of a polymorphization `ParamEnv` to allow normalizing later.
40             //
41             // We normalize the `fn_sig` again after substituting at a later point.
42             let mut sig = match *ty.kind() {
43                 ty::FnDef(def_id, substs) => tcx
44                     .fn_sig(def_id)
45                     .map_bound(|fn_sig| {
46                         tcx.normalize_erasing_regions(tcx.param_env(def_id), fn_sig)
47                     })
48                     .subst(tcx, substs),
49                 _ => unreachable!(),
50             };
51
52             if let ty::InstanceDef::VTableShim(..) = instance.def {
53                 // Modify `fn(self, ...)` to `fn(self: *mut Self, ...)`.
54                 sig = sig.map_bound(|mut sig| {
55                     let mut inputs_and_output = sig.inputs_and_output.to_vec();
56                     inputs_and_output[0] = tcx.mk_mut_ptr(inputs_and_output[0]);
57                     sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
58                     sig
59                 });
60             }
61             sig
62         }
63         ty::Closure(def_id, substs) => {
64             let sig = substs.as_closure().sig();
65
66             let bound_vars = tcx.mk_bound_variable_kinds(
67                 sig.bound_vars().iter().chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))),
68             );
69             let br = ty::BoundRegion {
70                 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
71                 kind: ty::BoundRegionKind::BrEnv,
72             };
73             let env_region = ty::ReLateBound(ty::INNERMOST, br);
74             let env_ty = tcx.closure_env_ty(def_id, substs, env_region).unwrap();
75
76             let sig = sig.skip_binder();
77             ty::Binder::bind_with_vars(
78                 tcx.mk_fn_sig(
79                     iter::once(env_ty).chain(sig.inputs().iter().cloned()),
80                     sig.output(),
81                     sig.c_variadic,
82                     sig.unsafety,
83                     sig.abi,
84                 ),
85                 bound_vars,
86             )
87         }
88         ty::Generator(did, substs, _) => {
89             let sig = substs.as_generator().poly_sig();
90
91             let bound_vars = tcx.mk_bound_variable_kinds(
92                 sig.bound_vars().iter().chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))),
93             );
94             let br = ty::BoundRegion {
95                 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
96                 kind: ty::BoundRegionKind::BrEnv,
97             };
98             let env_region = ty::ReLateBound(ty::INNERMOST, br);
99             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
100
101             let pin_did = tcx.require_lang_item(LangItem::Pin, None);
102             let pin_adt_ref = tcx.adt_def(pin_did);
103             let pin_substs = tcx.intern_substs(&[env_ty.into()]);
104             let env_ty = tcx.mk_adt(pin_adt_ref, pin_substs);
105
106             let sig = sig.skip_binder();
107             // The `FnSig` and the `ret_ty` here is for a generators main
108             // `Generator::resume(...) -> GeneratorState` function in case we
109             // have an ordinary generator, or the `Future::poll(...) -> Poll`
110             // function in case this is a special generator backing an async construct.
111             let (resume_ty, ret_ty) = if tcx.generator_is_async(did) {
112                 // The signature should be `Future::poll(_, &mut Context<'_>) -> Poll<Output>`
113                 let poll_did = tcx.require_lang_item(LangItem::Poll, None);
114                 let poll_adt_ref = tcx.adt_def(poll_did);
115                 let poll_substs = tcx.intern_substs(&[sig.return_ty.into()]);
116                 let ret_ty = tcx.mk_adt(poll_adt_ref, poll_substs);
117
118                 // We have to replace the `ResumeTy` that is used for type and borrow checking
119                 // with `&mut Context<'_>` which is used in codegen.
120                 #[cfg(debug_assertions)]
121                 {
122                     if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
123                         let expected_adt =
124                             tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
125                         assert_eq!(*resume_ty_adt, expected_adt);
126                     } else {
127                         panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
128                     };
129                 }
130                 let context_mut_ref = tcx.mk_task_context();
131
132                 (context_mut_ref, ret_ty)
133             } else {
134                 // The signature should be `Generator::resume(_, Resume) -> GeneratorState<Yield, Return>`
135                 let state_did = tcx.require_lang_item(LangItem::GeneratorState, None);
136                 let state_adt_ref = tcx.adt_def(state_did);
137                 let state_substs = tcx.intern_substs(&[sig.yield_ty.into(), sig.return_ty.into()]);
138                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
139
140                 (sig.resume_ty, ret_ty)
141             };
142
143             ty::Binder::bind_with_vars(
144                 tcx.mk_fn_sig(
145                     [env_ty, resume_ty].iter(),
146                     &ret_ty,
147                     false,
148                     hir::Unsafety::Normal,
149                     rustc_target::spec::abi::Abi::Rust,
150                 ),
151                 bound_vars,
152             )
153         }
154         _ => bug!("unexpected type {:?} in Instance::fn_sig", ty),
155     }
156 }
157
158 #[inline]
159 fn conv_from_spec_abi(tcx: TyCtxt<'_>, abi: SpecAbi) -> Conv {
160     use rustc_target::spec::abi::Abi::*;
161     match tcx.sess.target.adjust_abi(abi) {
162         RustIntrinsic | PlatformIntrinsic | Rust | RustCall => Conv::Rust,
163         RustCold => Conv::RustCold,
164
165         // It's the ABI's job to select this, not ours.
166         System { .. } => bug!("system abi should be selected elsewhere"),
167         EfiApi => bug!("eficall abi should be selected elsewhere"),
168
169         Stdcall { .. } => Conv::X86Stdcall,
170         Fastcall { .. } => Conv::X86Fastcall,
171         Vectorcall { .. } => Conv::X86VectorCall,
172         Thiscall { .. } => Conv::X86ThisCall,
173         C { .. } => Conv::C,
174         Unadjusted => Conv::C,
175         Win64 { .. } => Conv::X86_64Win64,
176         SysV64 { .. } => Conv::X86_64SysV,
177         Aapcs { .. } => Conv::ArmAapcs,
178         CCmseNonSecureCall => Conv::CCmseNonSecureCall,
179         PtxKernel => Conv::PtxKernel,
180         Msp430Interrupt => Conv::Msp430Intr,
181         X86Interrupt => Conv::X86Intr,
182         AmdGpuKernel => Conv::AmdGpuKernel,
183         AvrInterrupt => Conv::AvrInterrupt,
184         AvrNonBlockingInterrupt => Conv::AvrNonBlockingInterrupt,
185         Wasm => Conv::C,
186
187         // These API constants ought to be more specific...
188         Cdecl { .. } => Conv::C,
189     }
190 }
191
192 fn fn_abi_of_fn_ptr<'tcx>(
193     tcx: TyCtxt<'tcx>,
194     query: ty::ParamEnvAnd<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
195 ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> {
196     let (param_env, (sig, extra_args)) = query.into_parts();
197
198     let cx = LayoutCx { tcx, param_env };
199     fn_abi_new_uncached(&cx, sig, extra_args, None, None, false)
200 }
201
202 fn fn_abi_of_instance<'tcx>(
203     tcx: TyCtxt<'tcx>,
204     query: ty::ParamEnvAnd<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
205 ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> {
206     let (param_env, (instance, extra_args)) = query.into_parts();
207
208     let sig = fn_sig_for_fn_abi(tcx, instance, param_env);
209
210     let caller_location = if instance.def.requires_caller_location(tcx) {
211         Some(tcx.caller_location_ty())
212     } else {
213         None
214     };
215
216     fn_abi_new_uncached(
217         &LayoutCx { tcx, param_env },
218         sig,
219         extra_args,
220         caller_location,
221         Some(instance.def_id()),
222         matches!(instance.def, ty::InstanceDef::Virtual(..)),
223     )
224 }
225
226 // Handle safe Rust thin and fat pointers.
227 fn adjust_for_rust_scalar<'tcx>(
228     cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
229     attrs: &mut ArgAttributes,
230     scalar: Scalar,
231     layout: TyAndLayout<'tcx>,
232     offset: Size,
233     is_return: bool,
234 ) {
235     // Booleans are always a noundef i1 that needs to be zero-extended.
236     if scalar.is_bool() {
237         attrs.ext(ArgExtension::Zext);
238         attrs.set(ArgAttribute::NoUndef);
239         return;
240     }
241
242     if !scalar.is_uninit_valid() {
243         attrs.set(ArgAttribute::NoUndef);
244     }
245
246     // Only pointer types handled below.
247     let Scalar::Initialized { value: Pointer(_), valid_range} = scalar else { return };
248
249     if !valid_range.contains(0) {
250         attrs.set(ArgAttribute::NonNull);
251     }
252
253     if let Some(pointee) = layout.pointee_info_at(&cx, offset) {
254         if let Some(kind) = pointee.safe {
255             attrs.pointee_align = Some(pointee.align);
256
257             // `Box` are not necessarily dereferenceable for the entire duration of the function as
258             // they can be deallocated at any time. Same for non-frozen shared references (see
259             // <https://github.com/rust-lang/rust/pull/98017>). If LLVM had a way to say
260             // "dereferenceable on entry" we could use it here.
261             attrs.pointee_size = match kind {
262                 PointerKind::Box | PointerKind::SharedRef { frozen: false } => Size::ZERO,
263                 PointerKind::SharedRef { frozen: true } | PointerKind::MutableRef { .. } => {
264                     pointee.size
265                 }
266             };
267
268             // The aliasing rules for `Box<T>` are still not decided, but currently we emit
269             // `noalias` for it. This can be turned off using an unstable flag.
270             // See https://github.com/rust-lang/unsafe-code-guidelines/issues/326
271             let noalias_for_box = cx.tcx.sess.opts.unstable_opts.box_noalias;
272
273             // LLVM prior to version 12 had known miscompiles in the presence of noalias attributes
274             // (see #54878), so it was conditionally disabled, but we don't support earlier
275             // versions at all anymore. We still support turning it off using -Zmutable-noalias.
276             let noalias_mut_ref = cx.tcx.sess.opts.unstable_opts.mutable_noalias;
277
278             // `&mut` pointer parameters never alias other parameters,
279             // or mutable global data
280             //
281             // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
282             // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on memory
283             // dependencies rather than pointer equality. However this only applies to arguments,
284             // not return values.
285             let no_alias = match kind {
286                 PointerKind::SharedRef { frozen } => frozen,
287                 PointerKind::MutableRef { unpin } => unpin && noalias_mut_ref,
288                 PointerKind::Box => noalias_for_box,
289             };
290             // We can never add `noalias` in return position; that LLVM attribute has some very surprising semantics
291             // (see <https://github.com/rust-lang/unsafe-code-guidelines/issues/385#issuecomment-1368055745>).
292             if no_alias && !is_return {
293                 attrs.set(ArgAttribute::NoAlias);
294             }
295
296             if matches!(kind, PointerKind::SharedRef { frozen: true }) && !is_return {
297                 attrs.set(ArgAttribute::ReadOnly);
298             }
299         }
300     }
301 }
302
303 // FIXME(eddyb) perhaps group the signature/type-containing (or all of them?)
304 // arguments of this method, into a separate `struct`.
305 #[tracing::instrument(level = "debug", skip(cx, caller_location, fn_def_id, force_thin_self_ptr))]
306 fn fn_abi_new_uncached<'tcx>(
307     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
308     sig: ty::PolyFnSig<'tcx>,
309     extra_args: &[Ty<'tcx>],
310     caller_location: Option<Ty<'tcx>>,
311     fn_def_id: Option<DefId>,
312     // FIXME(eddyb) replace this with something typed, like an `enum`.
313     force_thin_self_ptr: bool,
314 ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> {
315     let sig = cx.tcx.normalize_erasing_late_bound_regions(cx.param_env, sig);
316
317     let conv = conv_from_spec_abi(cx.tcx(), sig.abi);
318
319     let mut inputs = sig.inputs();
320     let extra_args = if sig.abi == RustCall {
321         assert!(!sig.c_variadic && extra_args.is_empty());
322
323         if let Some(input) = sig.inputs().last() {
324             if let ty::Tuple(tupled_arguments) = input.kind() {
325                 inputs = &sig.inputs()[0..sig.inputs().len() - 1];
326                 tupled_arguments
327             } else {
328                 bug!(
329                     "argument to function with \"rust-call\" ABI \
330                         is not a tuple"
331                 );
332             }
333         } else {
334             bug!(
335                 "argument to function with \"rust-call\" ABI \
336                     is not a tuple"
337             );
338         }
339     } else {
340         assert!(sig.c_variadic || extra_args.is_empty());
341         extra_args
342     };
343
344     let target = &cx.tcx.sess.target;
345     let target_env_gnu_like = matches!(&target.env[..], "gnu" | "musl" | "uclibc");
346     let win_x64_gnu = target.os == "windows" && target.arch == "x86_64" && target.env == "gnu";
347     let linux_s390x_gnu_like =
348         target.os == "linux" && target.arch == "s390x" && target_env_gnu_like;
349     let linux_sparc64_gnu_like =
350         target.os == "linux" && target.arch == "sparc64" && target_env_gnu_like;
351     let linux_powerpc_gnu_like =
352         target.os == "linux" && target.arch == "powerpc" && target_env_gnu_like;
353     use SpecAbi::*;
354     let rust_abi = matches!(sig.abi, RustIntrinsic | PlatformIntrinsic | Rust | RustCall);
355
356     let arg_of = |ty: Ty<'tcx>, arg_idx: Option<usize>| -> Result<_, FnAbiError<'tcx>> {
357         let span = tracing::debug_span!("arg_of");
358         let _entered = span.enter();
359         let is_return = arg_idx.is_none();
360
361         let layout = cx.layout_of(ty)?;
362         let layout = if force_thin_self_ptr && arg_idx == Some(0) {
363             // Don't pass the vtable, it's not an argument of the virtual fn.
364             // Instead, pass just the data pointer, but give it the type `*const/mut dyn Trait`
365             // or `&/&mut dyn Trait` because this is special-cased elsewhere in codegen
366             make_thin_self_ptr(cx, layout)
367         } else {
368             layout
369         };
370
371         let mut arg = ArgAbi::new(cx, layout, |layout, scalar, offset| {
372             let mut attrs = ArgAttributes::new();
373             adjust_for_rust_scalar(*cx, &mut attrs, scalar, *layout, offset, is_return);
374             attrs
375         });
376
377         if arg.layout.is_zst() {
378             // For some forsaken reason, x86_64-pc-windows-gnu
379             // doesn't ignore zero-sized struct arguments.
380             // The same is true for {s390x,sparc64,powerpc}-unknown-linux-{gnu,musl,uclibc}.
381             if is_return
382                 || rust_abi
383                 || (!win_x64_gnu
384                     && !linux_s390x_gnu_like
385                     && !linux_sparc64_gnu_like
386                     && !linux_powerpc_gnu_like)
387             {
388                 arg.mode = PassMode::Ignore;
389             }
390         }
391
392         Ok(arg)
393     };
394
395     let mut fn_abi = FnAbi {
396         ret: arg_of(sig.output(), None)?,
397         args: inputs
398             .iter()
399             .copied()
400             .chain(extra_args.iter().copied())
401             .chain(caller_location)
402             .enumerate()
403             .map(|(i, ty)| arg_of(ty, Some(i)))
404             .collect::<Result<_, _>>()?,
405         c_variadic: sig.c_variadic,
406         fixed_count: inputs.len() as u32,
407         conv,
408         can_unwind: fn_can_unwind(cx.tcx(), fn_def_id, sig.abi),
409     };
410     fn_abi_adjust_for_abi(cx, &mut fn_abi, sig.abi, fn_def_id)?;
411     debug!("fn_abi_new_uncached = {:?}", fn_abi);
412     Ok(cx.tcx.arena.alloc(fn_abi))
413 }
414
415 #[tracing::instrument(level = "trace", skip(cx))]
416 fn fn_abi_adjust_for_abi<'tcx>(
417     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
418     fn_abi: &mut FnAbi<'tcx, Ty<'tcx>>,
419     abi: SpecAbi,
420     fn_def_id: Option<DefId>,
421 ) -> Result<(), FnAbiError<'tcx>> {
422     if abi == SpecAbi::Unadjusted {
423         return Ok(());
424     }
425
426     if abi == SpecAbi::Rust
427         || abi == SpecAbi::RustCall
428         || abi == SpecAbi::RustIntrinsic
429         || abi == SpecAbi::PlatformIntrinsic
430     {
431         // Look up the deduced parameter attributes for this function, if we have its def ID and
432         // we're optimizing in non-incremental mode. We'll tag its parameters with those attributes
433         // as appropriate.
434         let deduced_param_attrs = if cx.tcx.sess.opts.optimize != OptLevel::No
435             && cx.tcx.sess.opts.incremental.is_none()
436         {
437             fn_def_id.map(|fn_def_id| cx.tcx.deduced_param_attrs(fn_def_id)).unwrap_or_default()
438         } else {
439             &[]
440         };
441
442         let fixup = |arg: &mut ArgAbi<'tcx, Ty<'tcx>>, arg_idx: Option<usize>| {
443             if arg.is_ignore() {
444                 return;
445             }
446
447             match arg.layout.abi {
448                 Abi::Aggregate { .. } => {}
449
450                 // This is a fun case! The gist of what this is doing is
451                 // that we want callers and callees to always agree on the
452                 // ABI of how they pass SIMD arguments. If we were to *not*
453                 // make these arguments indirect then they'd be immediates
454                 // in LLVM, which means that they'd used whatever the
455                 // appropriate ABI is for the callee and the caller. That
456                 // means, for example, if the caller doesn't have AVX
457                 // enabled but the callee does, then passing an AVX argument
458                 // across this boundary would cause corrupt data to show up.
459                 //
460                 // This problem is fixed by unconditionally passing SIMD
461                 // arguments through memory between callers and callees
462                 // which should get them all to agree on ABI regardless of
463                 // target feature sets. Some more information about this
464                 // issue can be found in #44367.
465                 //
466                 // Note that the platform intrinsic ABI is exempt here as
467                 // that's how we connect up to LLVM and it's unstable
468                 // anyway, we control all calls to it in libstd.
469                 Abi::Vector { .. }
470                     if abi != SpecAbi::PlatformIntrinsic
471                         && cx.tcx.sess.target.simd_types_indirect =>
472                 {
473                     arg.make_indirect();
474                     return;
475                 }
476
477                 _ => return,
478             }
479
480             let size = arg.layout.size;
481             if arg.layout.is_unsized() || size > Pointer(AddressSpace::DATA).size(cx) {
482                 arg.make_indirect();
483             } else {
484                 // We want to pass small aggregates as immediates, but using
485                 // a LLVM aggregate type for this leads to bad optimizations,
486                 // so we pick an appropriately sized integer type instead.
487                 arg.cast_to(Reg { kind: RegKind::Integer, size });
488             }
489
490             // If we deduced that this parameter was read-only, add that to the attribute list now.
491             //
492             // The `readonly` parameter only applies to pointers, so we can only do this if the
493             // argument was passed indirectly. (If the argument is passed directly, it's an SSA
494             // value, so it's implicitly immutable.)
495             if let (Some(arg_idx), &mut PassMode::Indirect { ref mut attrs, .. }) =
496                 (arg_idx, &mut arg.mode)
497             {
498                 // The `deduced_param_attrs` list could be empty if this is a type of function
499                 // we can't deduce any parameters for, so make sure the argument index is in
500                 // bounds.
501                 if let Some(deduced_param_attrs) = deduced_param_attrs.get(arg_idx) {
502                     if deduced_param_attrs.read_only {
503                         attrs.regular.insert(ArgAttribute::ReadOnly);
504                         debug!("added deduced read-only attribute");
505                     }
506                 }
507             }
508         };
509
510         fixup(&mut fn_abi.ret, None);
511         for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() {
512             fixup(arg, Some(arg_idx));
513         }
514     } else {
515         fn_abi.adjust_for_foreign_abi(cx, abi)?;
516     }
517
518     Ok(())
519 }
520
521 #[tracing::instrument(level = "debug", skip(cx))]
522 fn make_thin_self_ptr<'tcx>(
523     cx: &(impl HasTyCtxt<'tcx> + HasParamEnv<'tcx>),
524     layout: TyAndLayout<'tcx>,
525 ) -> TyAndLayout<'tcx> {
526     let tcx = cx.tcx();
527     let fat_pointer_ty = if layout.is_unsized() {
528         // unsized `self` is passed as a pointer to `self`
529         // FIXME (mikeyhew) change this to use &own if it is ever added to the language
530         tcx.mk_mut_ptr(layout.ty)
531     } else {
532         match layout.abi {
533             Abi::ScalarPair(..) | Abi::Scalar(..) => (),
534             _ => bug!("receiver type has unsupported layout: {:?}", layout),
535         }
536
537         // In the case of Rc<Self>, we need to explicitly pass a *mut RcBox<Self>
538         // with a Scalar (not ScalarPair) ABI. This is a hack that is understood
539         // elsewhere in the compiler as a method on a `dyn Trait`.
540         // To get the type `*mut RcBox<Self>`, we just keep unwrapping newtypes until we
541         // get a built-in pointer type
542         let mut fat_pointer_layout = layout;
543         'descend_newtypes: while !fat_pointer_layout.ty.is_unsafe_ptr()
544             && !fat_pointer_layout.ty.is_region_ptr()
545         {
546             for i in 0..fat_pointer_layout.fields.count() {
547                 let field_layout = fat_pointer_layout.field(cx, i);
548
549                 if !field_layout.is_zst() {
550                     fat_pointer_layout = field_layout;
551                     continue 'descend_newtypes;
552                 }
553             }
554
555             bug!("receiver has no non-zero-sized fields {:?}", fat_pointer_layout);
556         }
557
558         fat_pointer_layout.ty
559     };
560
561     // we now have a type like `*mut RcBox<dyn Trait>`
562     // change its layout to that of `*mut ()`, a thin pointer, but keep the same type
563     // this is understood as a special case elsewhere in the compiler
564     let unit_ptr_ty = tcx.mk_mut_ptr(tcx.mk_unit());
565
566     TyAndLayout {
567         ty: fat_pointer_ty,
568
569         // NOTE(eddyb) using an empty `ParamEnv`, and `unwrap`-ing the `Result`
570         // should always work because the type is always `*mut ()`.
571         ..tcx.layout_of(ty::ParamEnv::reveal_all().and(unit_ptr_ty)).unwrap()
572     }
573 }