1use std::{cmp, fmt};
2
3use rustc_abi as abi;
4use rustc_abi::{
5 AddressSpace, Align, ExternAbi, FieldIdx, FieldsShape, HasDataLayout, LayoutData, PointeeInfo,
6 PointerKind, Primitive, ReprFlags, ReprOptions, Scalar, Size, TagEncoding, TargetDataLayout,
7 TyAbiInterface, VariantIdx, Variants,
8};
9use rustc_data_structures::Limit;
10use rustc_errors::{
11 Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
12};
13use rustc_hir as hir;
14use rustc_hir::LangItem;
15use rustc_hir::def_id::DefId;
16use rustc_macros::{StableHash, TyDecodable, TyEncodable, extension};
17use rustc_session::config::OptLevel;
18use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
19use rustc_target::callconv::FnAbi;
20use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi};
21use tracing::debug;
22
23use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
24use crate::query::TyCtxtAt;
25use crate::traits::ObligationCause;
26use crate::ty::normalize_erasing_regions::NormalizationError;
27use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
28
29impl IntegerExt for abi::Integer {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
use abi::Integer::{I8, I16, I32, I64, I128};
match (*self, signed) {
(I8, false) => tcx.types.u8,
(I16, false) => tcx.types.u16,
(I32, false) => tcx.types.u32,
(I64, false) => tcx.types.u64,
(I128, false) => tcx.types.u128,
(I8, true) => tcx.types.i8,
(I16, true) => tcx.types.i16,
(I32, true) => tcx.types.i32,
(I64, true) => tcx.types.i64,
(I128, true) => tcx.types.i128,
}
}
fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
use abi::Integer::{I8, I16, I32, I64, I128};
match ity {
ty::IntTy::I8 => I8,
ty::IntTy::I16 => I16,
ty::IntTy::I32 => I32,
ty::IntTy::I64 => I64,
ty::IntTy::I128 => I128,
ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
}
}
fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy)
-> abi::Integer {
use abi::Integer::{I8, I16, I32, I64, I128};
match ity {
ty::UintTy::U8 => I8,
ty::UintTy::U16 => I16,
ty::UintTy::U32 => I32,
ty::UintTy::U64 => I64,
ty::UintTy::U128 => I128,
ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
}
}
#[doc =
" Finds the appropriate Integer type and signedness for the given"]
#[doc = " signed discriminant range and `#[repr]` attribute."]
#[doc =
" N.B.: `u128` values above `i128::MAX` will be treated as signed, but"]
#[doc = " that shouldn\'t affect anything, other than maybe debuginfo."]
#[doc = ""]
#[doc =
" This is the basis for computing the type of the *tag* of an enum (which can be smaller than"]
#[doc =
" the type of the *discriminant*, which is determined by [`ReprOptions::discr_type`])."]
fn discr_range_of_repr<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>,
repr: &ReprOptions, min: i128, max: i128) -> (abi::Integer, bool) {
let unsigned_fit =
abi::Integer::fit_unsigned(cmp::max(min as u128, max as u128));
let signed_fit =
cmp::max(abi::Integer::fit_signed(min),
abi::Integer::fit_signed(max));
if let Some(ity) = repr.int {
let discr = abi::Integer::from_attr(&tcx, ity);
let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
if discr < fit {
crate::util::bug::bug_fmt(format_args!("Integer::repr_discr: `#[repr]` hint too small for discriminant range of enum `{0}`",
ty))
}
return (discr, ity.is_signed());
}
let at_least =
if repr.c() {
tcx.data_layout().c_enum_min_size
} else { abi::Integer::I8 };
if unsigned_fit <= signed_fit {
(cmp::max(unsigned_fit, at_least), false)
} else { (cmp::max(signed_fit, at_least), true) }
}
}#[extension(pub trait IntegerExt)]
30impl abi::Integer {
31 #[inline]
32 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> {
33 use abi::Integer::{I8, I16, I32, I64, I128};
34 match (*self, signed) {
35 (I8, false) => tcx.types.u8,
36 (I16, false) => tcx.types.u16,
37 (I32, false) => tcx.types.u32,
38 (I64, false) => tcx.types.u64,
39 (I128, false) => tcx.types.u128,
40 (I8, true) => tcx.types.i8,
41 (I16, true) => tcx.types.i16,
42 (I32, true) => tcx.types.i32,
43 (I64, true) => tcx.types.i64,
44 (I128, true) => tcx.types.i128,
45 }
46 }
47
48 fn from_int_ty<C: HasDataLayout>(cx: &C, ity: ty::IntTy) -> abi::Integer {
49 use abi::Integer::{I8, I16, I32, I64, I128};
50 match ity {
51 ty::IntTy::I8 => I8,
52 ty::IntTy::I16 => I16,
53 ty::IntTy::I32 => I32,
54 ty::IntTy::I64 => I64,
55 ty::IntTy::I128 => I128,
56 ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(),
57 }
58 }
59 fn from_uint_ty<C: HasDataLayout>(cx: &C, ity: ty::UintTy) -> abi::Integer {
60 use abi::Integer::{I8, I16, I32, I64, I128};
61 match ity {
62 ty::UintTy::U8 => I8,
63 ty::UintTy::U16 => I16,
64 ty::UintTy::U32 => I32,
65 ty::UintTy::U64 => I64,
66 ty::UintTy::U128 => I128,
67 ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(),
68 }
69 }
70
71 fn discr_range_of_repr<'tcx>(
79 tcx: TyCtxt<'tcx>,
80 ty: Ty<'tcx>,
81 repr: &ReprOptions,
82 min: i128,
83 max: i128,
84 ) -> (abi::Integer, bool) {
85 let unsigned_fit = abi::Integer::fit_unsigned(cmp::max(min as u128, max as u128));
90 let signed_fit = cmp::max(abi::Integer::fit_signed(min), abi::Integer::fit_signed(max));
91
92 if let Some(ity) = repr.int {
93 let discr = abi::Integer::from_attr(&tcx, ity);
94 let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
95 if discr < fit {
96 bug!(
97 "Integer::repr_discr: `#[repr]` hint too small for \
98 discriminant range of enum `{}`",
99 ty
100 )
101 }
102 return (discr, ity.is_signed());
103 }
104
105 let at_least = if repr.c() {
106 tcx.data_layout().c_enum_min_size
109 } else {
110 abi::Integer::I8
112 };
113
114 if unsigned_fit <= signed_fit {
117 (cmp::max(unsigned_fit, at_least), false)
118 } else {
119 (cmp::max(signed_fit, at_least), true)
120 }
121 }
122}
123
124impl FloatExt for abi::Float {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
use abi::Float::*;
match *self {
F16 => tcx.types.f16,
F32 => tcx.types.f32,
F64 => tcx.types.f64,
F128 => tcx.types.f128,
}
}
fn from_float_ty(fty: ty::FloatTy) -> Self {
use abi::Float::*;
match fty {
ty::FloatTy::F16 => F16,
ty::FloatTy::F32 => F32,
ty::FloatTy::F64 => F64,
ty::FloatTy::F128 => F128,
}
}
}#[extension(pub trait FloatExt)]
125impl abi::Float {
126 #[inline]
127 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
128 use abi::Float::*;
129 match *self {
130 F16 => tcx.types.f16,
131 F32 => tcx.types.f32,
132 F64 => tcx.types.f64,
133 F128 => tcx.types.f128,
134 }
135 }
136
137 fn from_float_ty(fty: ty::FloatTy) -> Self {
138 use abi::Float::*;
139 match fty {
140 ty::FloatTy::F16 => F16,
141 ty::FloatTy::F32 => F32,
142 ty::FloatTy::F64 => F64,
143 ty::FloatTy::F128 => F128,
144 }
145 }
146}
147
148impl PrimitiveExt for Primitive {
#[inline]
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match *self {
Primitive::Int(i, signed) => i.to_ty(tcx, signed),
Primitive::Float(f) => f.to_ty(tcx),
Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
}
}
#[doc = " Return an *integer* type matching this primitive."]
#[doc = " Useful in particular when dealing with enum discriminants."]
#[inline]
fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match *self {
Primitive::Int(i, signed) => i.to_ty(tcx, signed),
Primitive::Pointer(_) => {
let signed = false;
tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
}
Primitive::Float(_) =>
crate::util::bug::bug_fmt(format_args!("floats do not have an int type")),
}
}
}#[extension(pub trait PrimitiveExt)]
149impl Primitive {
150 #[inline]
151 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
152 match *self {
153 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
154 Primitive::Float(f) => f.to_ty(tcx),
155 Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
157 }
158 }
159
160 #[inline]
163 fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
164 match *self {
165 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
166 Primitive::Pointer(_) => {
168 let signed = false;
169 tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
170 }
171 Primitive::Float(_) => bug!("floats do not have an int type"),
172 }
173 }
174}
175
176pub const WIDE_PTR_ADDR: usize = 0;
181
182pub const WIDE_PTR_EXTRA: usize = 1;
187
188pub const MAX_SIMD_LANES: u64 = rustc_abi::MAX_SIMD_LANES;
189
190#[derive(#[automatically_derived]
impl ::core::marker::Copy for ValidityRequirement { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ValidityRequirement {
#[inline]
fn clone(&self) -> ValidityRequirement { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ValidityRequirement {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ValidityRequirement::Inhabited => "Inhabited",
ValidityRequirement::Zero => "Zero",
ValidityRequirement::UninitMitigated0x01Fill =>
"UninitMitigated0x01Fill",
ValidityRequirement::Uninit => "Uninit",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ValidityRequirement {
#[inline]
fn eq(&self, other: &ValidityRequirement) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ValidityRequirement {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ValidityRequirement {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
ValidityRequirement {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
ValidityRequirement::Inhabited => {}
ValidityRequirement::Zero => {}
ValidityRequirement::UninitMitigated0x01Fill => {}
ValidityRequirement::Uninit => {}
}
}
}
};StableHash)]
193pub enum ValidityRequirement {
194 Inhabited,
195 Zero,
196 UninitMitigated0x01Fill,
199 Uninit,
201}
202
203impl ValidityRequirement {
204 pub fn from_intrinsic(intrinsic: Symbol) -> Option<Self> {
205 match intrinsic {
206 sym::assert_inhabited => Some(Self::Inhabited),
207 sym::assert_zero_valid => Some(Self::Zero),
208 sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
209 _ => None,
210 }
211 }
212}
213
214impl fmt::Display for ValidityRequirement {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 match self {
217 Self::Inhabited => f.write_str("is inhabited"),
218 Self::Zero => f.write_str("allows being left zeroed"),
219 Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
220 Self::Uninit => f.write_str("allows being left uninitialized"),
221 }
222 }
223}
224
225#[derive(#[automatically_derived]
impl ::core::marker::Copy for SimdLayoutError { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SimdLayoutError {
#[inline]
fn clone(&self) -> SimdLayoutError {
let _: ::core::clone::AssertParamIsClone<u64>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SimdLayoutError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SimdLayoutError::ZeroLength =>
::core::fmt::Formatter::write_str(f, "ZeroLength"),
SimdLayoutError::TooManyLanes(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TooManyLanes", &__self_0),
}
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
SimdLayoutError {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
SimdLayoutError::ZeroLength => {}
SimdLayoutError::TooManyLanes(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for SimdLayoutError {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
SimdLayoutError::ZeroLength => { 0usize }
SimdLayoutError::TooManyLanes(ref __binding_0) => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
SimdLayoutError::ZeroLength => {}
SimdLayoutError::TooManyLanes(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for SimdLayoutError {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { SimdLayoutError::ZeroLength }
1usize => {
SimdLayoutError::TooManyLanes(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SimdLayoutError`, expected 0..2, actual {0}",
n));
}
}
}
}
};TyDecodable)]
226pub enum SimdLayoutError {
227 ZeroLength,
229 TooManyLanes(u64),
232}
233
234#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutError<'tcx> {
#[inline]
fn clone(&self) -> LayoutError<'tcx> {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<SimdLayoutError>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<NormalizationError<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ErrorGuaranteed>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for LayoutError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LayoutError::Unknown(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Unknown", &__self_0),
LayoutError::SizeOverflow(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SizeOverflow", &__self_0),
LayoutError::InvalidSimd { ty: __self_0, kind: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"InvalidSimd", "ty", __self_0, "kind", &__self_1),
LayoutError::TooGeneric(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TooGeneric", &__self_0),
LayoutError::NormalizationFailure(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"NormalizationFailure", __self_0, &__self_1),
LayoutError::ReferencesError(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ReferencesError", &__self_0),
}
}
}Debug, const _: () =
{
impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
LayoutError<'tcx> {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
LayoutError::Unknown(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
LayoutError::SizeOverflow(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
LayoutError::TooGeneric(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
LayoutError::ReferencesError(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for LayoutError<'tcx> {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
LayoutError::Unknown(ref __binding_0) => { 0usize }
LayoutError::SizeOverflow(ref __binding_0) => { 1usize }
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
2usize
}
LayoutError::TooGeneric(ref __binding_0) => { 3usize }
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
4usize
}
LayoutError::ReferencesError(ref __binding_0) => { 5usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
LayoutError::Unknown(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
LayoutError::SizeOverflow(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
LayoutError::TooGeneric(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
LayoutError::ReferencesError(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for LayoutError<'tcx> {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
LayoutError::Unknown(::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
LayoutError::SizeOverflow(::rustc_serialize::Decodable::decode(__decoder))
}
2usize => {
LayoutError::InvalidSimd {
ty: ::rustc_serialize::Decodable::decode(__decoder),
kind: ::rustc_serialize::Decodable::decode(__decoder),
}
}
3usize => {
LayoutError::TooGeneric(::rustc_serialize::Decodable::decode(__decoder))
}
4usize => {
LayoutError::NormalizationFailure(::rustc_serialize::Decodable::decode(__decoder),
::rustc_serialize::Decodable::decode(__decoder))
}
5usize => {
LayoutError::ReferencesError(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `LayoutError`, expected 0..6, actual {0}",
n));
}
}
}
}
};TyDecodable)]
235pub enum LayoutError<'tcx> {
236 Unknown(Ty<'tcx>),
244 SizeOverflow(Ty<'tcx>),
246 InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
248 TooGeneric(Ty<'tcx>),
253 NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
261 ReferencesError(ErrorGuaranteed),
263}
264
265impl<'tcx> fmt::Display for LayoutError<'tcx> {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 match *self {
268 LayoutError::Unknown(ty) => f.write_fmt(format_args!("the type `{0}` has an unknown layout", ty))write!(f, "the type `{ty}` has an unknown layout"),
269 LayoutError::TooGeneric(ty) => {
270 f.write_fmt(format_args!("the type `{0}` does not have a fixed layout", ty))write!(f, "the type `{ty}` does not have a fixed layout")
271 }
272 LayoutError::SizeOverflow(ty) => {
273 f.write_fmt(format_args!("values of the type `{0}` are too big for the target architecture",
ty))write!(f, "values of the type `{ty}` are too big for the target architecture")
274 }
275 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
276 f.write_fmt(format_args!("the SIMD type `{0}` has more elements than the limit {1}",
ty, max_lanes))write!(f, "the SIMD type `{ty}` has more elements than the limit {max_lanes}")
277 }
278 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
279 f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
280 }
281 LayoutError::NormalizationFailure(t, e) => f.write_fmt(format_args!("unable to determine layout for `{0}` because `{1}` cannot be normalized",
t, e.get_type_for_failure()))write!(
282 f,
283 "unable to determine layout for `{}` because `{}` cannot be normalized",
284 t,
285 e.get_type_for_failure()
286 ),
287 LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
288 }
289 }
290}
291
292impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
293 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
294 self.to_string().into_diag_arg(&mut None)
295 }
296}
297
298#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for LayoutCx<'tcx> {
#[inline]
fn clone(&self) -> LayoutCx<'tcx> {
let _:
::core::clone::AssertParamIsClone<abi::LayoutCalculator<TyCtxt<'tcx>>>;
let _: ::core::clone::AssertParamIsClone<ty::TypingEnv<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for LayoutCx<'tcx> { }Copy)]
299pub struct LayoutCx<'tcx> {
300 pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
301 pub typing_env: ty::TypingEnv<'tcx>,
302}
303
304impl<'tcx> LayoutCx<'tcx> {
305 pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
306 Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
307 }
308}
309
310#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for SizeSkeleton<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for SizeSkeleton<'tcx> {
#[inline]
fn clone(&self) -> SizeSkeleton<'tcx> {
let _: ::core::clone::AssertParamIsClone<Size>;
let _: ::core::clone::AssertParamIsClone<Option<Align>>;
let _: ::core::clone::AssertParamIsClone<bool>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for SizeSkeleton<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SizeSkeleton::Known(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Known",
__self_0, &__self_1),
SizeSkeleton::Pointer { non_zero: __self_0, tail: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Pointer", "non_zero", __self_0, "tail", &__self_1),
}
}
}Debug)]
315pub enum SizeSkeleton<'tcx> {
316 Known(Size, Option<Align>),
319
320 Pointer {
322 non_zero: bool,
324 tail: Ty<'tcx>,
328 },
329}
330
331impl<'tcx> SizeSkeleton<'tcx> {
332 pub fn compute(
333 ty: Ty<'tcx>,
334 tcx: TyCtxt<'tcx>,
335 typing_env: ty::TypingEnv<'tcx>,
336 span: Span,
337 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
338 Self::compute_inner(ty, tcx, typing_env, span, 0)
339 }
340
341 fn compute_inner(
342 ty: Ty<'tcx>,
343 tcx: TyCtxt<'tcx>,
344 typing_env: ty::TypingEnv<'tcx>,
345 span: Span,
346 depth: usize,
347 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
348 if true {
if !!ty.has_non_region_infer() {
::core::panicking::panic("assertion failed: !ty.has_non_region_infer()")
};
};debug_assert!(!ty.has_non_region_infer());
349
350 let recursion_limit = tcx.recursion_limit();
355 if depth >= recursion_limit.0 {
356 let suggested_limit = match recursion_limit {
357 Limit(0) => Limit(2),
358 limit => limit * 2,
359 };
360 let reported = tcx.dcx().emit_err(crate::error::RecursionLimitReachedSizeSkeleton {
361 span,
362 ty,
363 suggested_limit,
364 });
365 return Err(tcx.arena.alloc(LayoutError::ReferencesError(reported)));
366 }
367
368 let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
370 Ok(layout) => {
371 if layout.is_sized() {
372 return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
373 } else {
374 return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
376 }
377 }
378 Err(err @ LayoutError::TooGeneric(_)) => err,
379 Err(
381 e @ LayoutError::Unknown(_)
382 | e @ LayoutError::SizeOverflow(_)
383 | e @ LayoutError::InvalidSimd { .. }
384 | e @ LayoutError::NormalizationFailure(..)
385 | e @ LayoutError::ReferencesError(_),
386 ) => return Err(e),
387 };
388
389 match *ty.kind() {
390 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
391 let non_zero = !ty.is_raw_ptr();
392
393 tcx.assert_fully_normalized(typing_env, pointee);
394 let tail = tcx.struct_tail_raw(
395 pointee,
396 &ObligationCause::dummy(),
397 |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
398 Ok(ty) => ty,
399 Err(e) => Ty::new_error_with_message(
400 tcx,
401 DUMMY_SP,
402 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
e.get_type_for_failure()))
})format!(
403 "normalization failed for {} but no errors reported",
404 e.get_type_for_failure()
405 ),
406 ),
407 },
408 || {},
409 );
410
411 match tail.kind() {
412 ty::Param(_)
415 | ty::Alias(
416 _,
417 ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
418 ) => {
419 if true {
if !tail.has_non_region_param() {
::core::panicking::panic("assertion failed: tail.has_non_region_param()")
};
};debug_assert!(tail.has_non_region_param());
420 Ok(SizeSkeleton::Pointer {
421 non_zero,
422 tail: tcx.erase_and_anonymize_regions(tail),
423 })
424 }
425 ty::Error(guar) => {
426 return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
428 }
429 _ => crate::util::bug::bug_fmt(format_args!("SizeSkeleton::compute({0}): layout errored ({1:?}), yet tail `{2}` is not a type parameter or a projection",
ty, err, tail))bug!(
430 "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
431 tail `{tail}` is not a type parameter or a projection",
432 ),
433 }
434 }
435 ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
436 let len_eval = len.try_to_target_usize(tcx);
437 if len_eval == Some(0) {
438 return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
439 }
440
441 match SizeSkeleton::compute_inner(inner, tcx, typing_env, span, depth + 1)? {
442 SizeSkeleton::Known(s, a) => {
445 if let Some(c) = len_eval {
446 let size = s
447 .bytes()
448 .checked_mul(c)
449 .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
450 return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
452 }
453 Err(err)
454 }
455 SizeSkeleton::Pointer { .. } => Err(err),
456 }
457 }
458
459 ty::Adt(def, args) => {
460 if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
462 return Err(err);
463 }
464 {
466 let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } =
471 def.repr();
472 let mut ignored_flags = ReprFlags::IS_TRANSPARENT
473 | ReprFlags::IS_LINEAR
474 | ReprFlags::RANDOMIZE_LAYOUT;
475 if def.is_struct() {
476 ignored_flags |= ReprFlags::IS_C;
481 }
482 if int.is_some()
483 || align.is_some()
484 || pack.is_some()
485 || flags.difference(ignored_flags) != ReprFlags::default()
486 || scalable.is_some()
487 {
488 return Err(err);
489 }
490 }
491
492 let zero_or_ptr_variant = |i| -> Result<Option<SizeSkeleton<'tcx>>, _> {
496 let i = VariantIdx::from_usize(i);
497 let fields = def.variant(i).fields.iter().map(|field| {
498 SizeSkeleton::compute_inner(
499 field.ty(tcx, args).skip_norm_wip(),
500 tcx,
501 typing_env,
502 span,
503 depth + 1,
504 )
505 });
506 let mut ptr = None;
507 for field in fields {
508 let field = field?;
509 match field {
510 SizeSkeleton::Known(size, align) => {
511 let is_1zst = size.bytes() == 0
512 && align.is_some_and(|align| align.bytes() == 1);
513 if !is_1zst {
514 return Err(err);
515 }
516 }
517 SizeSkeleton::Pointer { .. } => {
518 if ptr.is_some() {
519 return Err(err);
520 }
521 ptr = Some(field);
522 }
523 }
524 }
525 Ok(ptr)
526 };
527
528 let v0 = zero_or_ptr_variant(0)?;
529 if def.variants().len() == 1 {
532 if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
533 return Ok(SizeSkeleton::Pointer { non_zero, tail });
534 } else {
535 return Err(err);
536 }
537 }
538
539 let v1 = zero_or_ptr_variant(1)?;
540 match (v0, v1) {
544 (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
545 | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
546 Ok(SizeSkeleton::Pointer { non_zero: false, tail })
547 }
548 _ => Err(err),
549 }
550 }
551
552 ty::Alias(..) => {
553 let normalized =
554 tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
555 if ty == normalized {
556 Err(err)
557 } else {
558 SizeSkeleton::compute_inner(normalized, tcx, typing_env, span, depth + 1)
559 }
560 }
561
562 ty::Pat(base, pat) => {
563 let base = SizeSkeleton::compute_inner(base, tcx, typing_env, span, depth + 1);
565 match *pat {
566 ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
567 ty::PatternKind::NotNull => match base? {
570 SizeSkeleton::Known(..) => base,
571 SizeSkeleton::Pointer { non_zero: _, tail } => {
572 Ok(SizeSkeleton::Pointer { non_zero: true, tail })
573 }
574 },
575 }
576 }
577
578 _ => Err(err),
579 }
580 }
581
582 pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
583 match (self, other) {
584 (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
585 (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
586 a == b
587 }
588 _ => false,
589 }
590 }
591}
592
593pub trait HasTyCtxt<'tcx>: HasDataLayout {
594 fn tcx(&self) -> TyCtxt<'tcx>;
595}
596
597pub trait HasTypingEnv<'tcx> {
598 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
599}
600
601impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
602 #[inline]
603 fn data_layout(&self) -> &TargetDataLayout {
604 &self.data_layout
605 }
606}
607
608impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
609 fn target_spec(&self) -> &Target {
610 &self.sess.target
611 }
612}
613
614impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
615 fn x86_abi_opt(&self) -> X86Abi {
616 X86Abi {
617 regparm: self.sess.opts.unstable_opts.regparm,
618 reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
619 }
620 }
621}
622
623impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
624 #[inline]
625 fn tcx(&self) -> TyCtxt<'tcx> {
626 *self
627 }
628}
629
630impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
631 #[inline]
632 fn data_layout(&self) -> &TargetDataLayout {
633 &self.data_layout
634 }
635}
636
637impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
638 fn target_spec(&self) -> &Target {
639 &self.sess.target
640 }
641}
642
643impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
644 #[inline]
645 fn tcx(&self) -> TyCtxt<'tcx> {
646 **self
647 }
648}
649
650impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
651 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
652 self.typing_env
653 }
654}
655
656impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
657 fn data_layout(&self) -> &TargetDataLayout {
658 self.calc.cx.data_layout()
659 }
660}
661
662impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
663 fn target_spec(&self) -> &Target {
664 self.calc.cx.target_spec()
665 }
666}
667
668impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
669 fn x86_abi_opt(&self) -> X86Abi {
670 self.calc.cx.x86_abi_opt()
671 }
672}
673
674impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
675 fn tcx(&self) -> TyCtxt<'tcx> {
676 self.calc.cx
677 }
678}
679
680pub trait MaybeResult<T> {
681 type Error;
682
683 fn from(x: Result<T, Self::Error>) -> Self;
684 fn to_result(self) -> Result<T, Self::Error>;
685}
686
687impl<T> MaybeResult<T> for T {
688 type Error = !;
689
690 fn from(Ok(x): Result<T, Self::Error>) -> Self {
691 x
692 }
693 fn to_result(self) -> Result<T, Self::Error> {
694 Ok(self)
695 }
696}
697
698impl<T, E> MaybeResult<T> for Result<T, E> {
699 type Error = E;
700
701 fn from(x: Result<T, Self::Error>) -> Self {
702 x
703 }
704 fn to_result(self) -> Result<T, Self::Error> {
705 self
706 }
707}
708
709pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
710
711pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
714 type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
717
718 #[inline]
721 fn layout_tcx_at_span(&self) -> Span {
722 DUMMY_SP
723 }
724
725 fn handle_layout_err(
733 &self,
734 err: LayoutError<'tcx>,
735 span: Span,
736 ty: Ty<'tcx>,
737 ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
738}
739
740pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
742 #[inline]
745 fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
746 self.spanned_layout_of(ty, DUMMY_SP)
747 }
748
749 #[inline]
754 fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
755 let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
756 let tcx = self.tcx().at(span);
757
758 MaybeResult::from(
759 tcx.layout_of(self.typing_env().as_query_input(ty))
760 .map_err(|err| self.handle_layout_err(*err, span, ty)),
761 )
762 }
763}
764
765impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
766
767impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
768 type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
769
770 #[inline]
771 fn handle_layout_err(
772 &self,
773 err: LayoutError<'tcx>,
774 _: Span,
775 _: Ty<'tcx>,
776 ) -> &'tcx LayoutError<'tcx> {
777 self.tcx().arena.alloc(err)
778 }
779}
780
781impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
782where
783 C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
784{
785 fn ty_and_layout_for_variant(
786 this: TyAndLayout<'tcx>,
787 cx: &C,
788 variant_index: VariantIdx,
789 ) -> TyAndLayout<'tcx> {
790 let layout = match this.variants {
791 Variants::Single { index } if index == variant_index => {
793 return this;
794 }
795
796 Variants::Single { .. } | Variants::Empty => {
797 let tcx = cx.tcx();
802 let typing_env = cx.typing_env();
803
804 if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
806 {
match (&original_layout.variants, &this.variants) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(original_layout.variants, this.variants);
807 }
808
809 let fields = match this.ty.kind() {
810 ty::Adt(def, _) if def.variants().is_empty() => {
811 crate::util::bug::bug_fmt(format_args!("for_variant called on zero-variant enum {0}",
this.ty))bug!("for_variant called on zero-variant enum {}", this.ty)
812 }
813 ty::Adt(def, _) => def.variant(variant_index).fields.len(),
814 _ => crate::util::bug::bug_fmt(format_args!("`ty_and_layout_for_variant` on unexpected type {0}",
this.ty))bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty),
815 };
816 tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
817 }
818
819 Variants::Multiple { .. } => {
820 cx.tcx().mk_layout(LayoutData::for_variant(&this, variant_index))
821 }
822 };
823
824 {
match (&*layout.variants(), &Variants::Single { index: variant_index }) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(*layout.variants(), Variants::Single { index: variant_index });
825
826 TyAndLayout { ty: this.ty, layout }
827 }
828
829 fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
830 enum TyMaybeWithLayout<'tcx> {
831 Ty(Ty<'tcx>),
832 TyAndLayout(TyAndLayout<'tcx>),
833 }
834
835 fn field_ty_or_layout<'tcx>(
836 this: TyAndLayout<'tcx>,
837 cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
838 i: usize,
839 ) -> TyMaybeWithLayout<'tcx> {
840 let tcx = cx.tcx();
841 let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
842 TyAndLayout {
843 layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
844 ty: tag.primitive().to_ty(tcx),
845 }
846 };
847
848 match *this.ty.kind() {
849 ty::Bool
850 | ty::Char
851 | ty::Int(_)
852 | ty::Uint(_)
853 | ty::Float(_)
854 | ty::FnPtr(..)
855 | ty::Never
856 | ty::FnDef(..)
857 | ty::CoroutineWitness(..)
858 | ty::Foreign(..)
859 | ty::Dynamic(_, _) => {
860 crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this)
861 }
862
863 ty::Pat(base, _) => {
864 {
match (&i, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(i, 0);
865 TyMaybeWithLayout::Ty(base)
866 }
867
868 ty::UnsafeBinder(bound_ty) => {
869 let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
870 field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
871 }
872
873 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
875 if !(i < this.fields.count()) {
::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
876
877 if i == 0 {
882 let nil = tcx.types.unit;
883 let unit_ptr_ty = if this.ty.is_raw_ptr() {
884 Ty::new_mut_ptr(tcx, nil)
885 } else {
886 Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
887 };
888
889 let typing_env = ty::TypingEnv::fully_monomorphized();
893 return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
894 ty: this.ty,
895 ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
896 });
897 }
898
899 let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
900 let min_count = ty::vtable_min_entries(
901 tcx,
902 principal.map(|principal| {
903 tcx.instantiate_bound_regions_with_erased(principal)
904 }),
905 );
906 Ty::new_imm_ref(
907 tcx,
908 tcx.lifetimes.re_static,
909 Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
911 )
912 };
913
914 let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
915 && !pointee.references_error()
918 {
919 let metadata = tcx.normalize_erasing_regions(
920 cx.typing_env(),
921 Unnormalized::new(Ty::new_projection(
922 tcx,
923 ty::IsRigid::No,
924 metadata_def_id,
925 [pointee],
926 )),
927 );
928
929 if let ty::Adt(def, args) = metadata.kind()
934 && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
935 && let ty::Dynamic(data, _) = args.type_at(0).kind()
936 {
937 mk_dyn_vtable(data.principal())
938 } else {
939 metadata
940 }
941 } else {
942 match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
943 ty::Slice(_) | ty::Str => tcx.types.usize,
944 ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
945 _ => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this),
946 }
947 };
948
949 TyMaybeWithLayout::Ty(metadata)
950 }
951
952 ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
954 ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
955
956 ty::Closure(_, args) => field_ty_or_layout(
958 TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
959 cx,
960 i,
961 ),
962
963 ty::CoroutineClosure(_, args) => field_ty_or_layout(
964 TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
965 cx,
966 i,
967 ),
968
969 ty::Coroutine(def_id, args) => match this.variants {
970 Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
971 Variants::Single { index } => TyMaybeWithLayout::Ty(
972 args.as_coroutine()
973 .state_tys(def_id, tcx)
974 .nth(index.as_usize())
975 .unwrap()
976 .nth(i)
977 .unwrap(),
978 ),
979 Variants::Multiple { tag, tag_field, .. } => {
980 if FieldIdx::from_usize(i) == tag_field {
981 TyMaybeWithLayout::TyAndLayout(tag_layout(tag))
982 } else {
983 TyMaybeWithLayout::Ty(args.as_coroutine().upvar_tys()[i])
984 }
985 }
986 },
987
988 ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
989
990 ty::Adt(def, args) => {
992 match this.variants {
993 Variants::Single { index } => {
994 let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
995 TyMaybeWithLayout::Ty(field.ty(tcx, args).skip_norm_wip())
996 }
997 Variants::Empty => {
::core::panicking::panic_fmt(format_args!("there is no field in Variants::Empty types"));
}panic!("there is no field in Variants::Empty types"),
998
999 Variants::Multiple { tag, .. } => {
1001 {
match (&i, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(i, 0);
1002 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
1003 }
1004 }
1005 }
1006
1007 ty::Alias(..)
1008 | ty::Bound(..)
1009 | ty::Placeholder(..)
1010 | ty::Param(_)
1011 | ty::Infer(_)
1012 | ty::Error(_) => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field: unexpected type `{0}`",
this.ty))bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
1013 }
1014 }
1015
1016 match field_ty_or_layout(this, cx, i) {
1017 TyMaybeWithLayout::Ty(field_ty) => {
1018 cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
1019 crate::util::bug::bug_fmt(format_args!("failed to get layout for `{0}`: {1:?},\ndespite it being a field (#{2}) of an existing layout: {3:#?}",
field_ty, e, i, this))bug!(
1020 "failed to get layout for `{field_ty}`: {e:?},\n\
1021 despite it being a field (#{i}) of an existing layout: {this:#?}",
1022 )
1023 })
1024 }
1025 TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
1026 }
1027 }
1028
1029 fn ty_and_layout_pointee_info_at(
1032 this: TyAndLayout<'tcx>,
1033 cx: &C,
1034 offset: Size,
1035 ) -> Option<PointeeInfo> {
1036 let tcx = cx.tcx();
1037 let typing_env = cx.typing_env();
1038
1039 let optimize = tcx.sess.opts.optimize != OptLevel::No;
1043
1044 let pointee_info = match *this.ty.kind() {
1045 ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
1046 Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
1047 }
1048 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
1049 tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
1050 let kind = match mt {
1051 hir::Mutability::Not => {
1052 let frozen = optimize && ty.is_freeze(tcx, typing_env);
1053 PointerKind::SharedRef { frozen }
1054 }
1055 hir::Mutability::Mut => {
1056 let unpin = optimize
1057 && ty.is_unpin(tcx, typing_env)
1058 && ty.is_unsafe_unpin(tcx, typing_env);
1059 PointerKind::MutableRef { unpin }
1060 }
1061 };
1062 PointeeInfo { safe: Some(kind), size: layout.size, align: layout.align.abi }
1063 })
1064 }
1065
1066 ty::Adt(..)
1067 if offset.bytes() == 0
1068 && let Some(pointee) = this.ty.boxed_ty() =>
1069 {
1070 tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1071 safe: Some(PointerKind::Box {
1072 unpin: optimize
1074 && pointee.is_unpin(tcx, typing_env)
1075 && pointee.is_unsafe_unpin(tcx, typing_env),
1076 global: this.ty.is_box_global(tcx),
1077 }),
1078 size: layout.size,
1079 align: layout.align.abi,
1080 })
1081 }
1082
1083 ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
1084 Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset).map(|info| {
1085 PointeeInfo {
1086 safe: None,
1089 size: Size::ZERO,
1091 align: info.align,
1093 }
1094 })
1095 }
1096
1097 _ => {
1098 let mut data_variant = match &this.variants {
1099 Variants::Multiple {
1109 tag_encoding:
1110 TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1111 tag_field,
1112 variants,
1113 ..
1114 } if variants.len() == 2
1115 && this.fields.offset(tag_field.as_usize()) == offset =>
1116 {
1117 let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1118 VariantIdx::from_u32(1)
1119 } else {
1120 VariantIdx::from_u32(0)
1121 };
1122 {
match (&tagged_variant, &niche_variants.start) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(tagged_variant, niche_variants.start);
1123 if *niche_start == 0 {
1124 Some(this.for_variant(cx, *untagged_variant))
1130 } else {
1131 None
1132 }
1133 }
1134 Variants::Multiple { .. } => None,
1135 Variants::Empty | Variants::Single { .. } => Some(this),
1136 };
1137
1138 if let Some(variant) = data_variant
1139 && let FieldsShape::Union(_) = variant.fields
1141 {
1142 data_variant = None;
1143 }
1144
1145 let mut result = None;
1146
1147 if let Some(variant) = data_variant {
1148 let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1151 for i in 0..variant.fields.count() {
1152 let field_start = variant.fields.offset(i);
1153 if field_start <= offset {
1154 let field = variant.field(cx, i);
1155 result = field.to_result().ok().and_then(|field| {
1156 if ptr_end <= field_start + field.size {
1157 let field_info =
1159 field.pointee_info_at(cx, offset - field_start);
1160 field_info
1161 } else {
1162 None
1163 }
1164 });
1165 if result.is_some() {
1166 break;
1167 }
1168 }
1169 }
1170 }
1171
1172 result
1173 }
1174 };
1175
1176 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/layout.rs:1176",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1176u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::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!("pointee_info_at (offset={0:?}, type kind: {1:?}) => {2:?}",
offset, this.ty.kind(), pointee_info) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1177 "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1178 offset,
1179 this.ty.kind(),
1180 pointee_info
1181 );
1182
1183 pointee_info
1184 }
1185
1186 fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1187 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1188 }
1189
1190 fn is_never(this: TyAndLayout<'tcx>) -> bool {
1191 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Never => true,
_ => false,
}matches!(this.ty.kind(), ty::Never)
1192 }
1193
1194 fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1195 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1196 }
1197
1198 fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1199 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Tuple(list) if list.len() == 0 => true,
_ => false,
}matches!(this.ty.kind(), ty::Tuple(list) if list.len() == 0)
1200 }
1201
1202 fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1203 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(def, _) if def.repr().transparent() => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.repr().transparent())
1204 }
1205
1206 fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1207 this.ty.is_scalable_vector()
1208 }
1209
1210 fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1212 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(def, _) if
def.repr().flags.contains(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS)
=> true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(def, _) if def.repr().flags.contains(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS))
1213 }
1214}
1215
1216#[inline]
1257#[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_can_unwind",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1257u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&[{
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()
},
{
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::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(&fn_def_id)
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: bool = loop {};
return __tracing_attr_fake_return;
}
{
if let Some(did) = fn_def_id {
if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND)
{
return false;
}
if !tcx.sess.panic_strategy().unwinds() &&
!tcx.is_foreign_item(did) {
return false;
}
if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds() &&
tcx.is_lang_item(did, LangItem::DropGlue) {
return false;
}
}
use ExternAbi::*;
match abi {
C { unwind } | System { unwind } | Cdecl { unwind } |
Stdcall { unwind } | Fastcall { unwind } | Vectorcall {
unwind } | Thiscall { unwind } | Aapcs { unwind } | Win64 {
unwind } | SysV64 { unwind } => unwind,
PtxKernel | Msp430Interrupt | X86Interrupt | GpuKernel |
EfiApi | AvrInterrupt | AvrNonBlockingInterrupt |
CmseNonSecureCall | CmseNonSecureEntry | Custom |
RiscvInterruptM | RiscvInterruptS | RustInvalid | Swift |
Unadjusted => false,
Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
tcx.sess.panic_strategy().unwinds()
}
}
}
}
}#[tracing::instrument(level = "debug", skip(tcx))]
1258pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1259 if let Some(did) = fn_def_id {
1260 if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1262 return false;
1263 }
1264
1265 if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1270 return false;
1271 }
1272
1273 if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1278 && tcx.is_lang_item(did, LangItem::DropGlue)
1279 {
1280 return false;
1281 }
1282 }
1283
1284 use ExternAbi::*;
1291 match abi {
1292 C { unwind }
1293 | System { unwind }
1294 | Cdecl { unwind }
1295 | Stdcall { unwind }
1296 | Fastcall { unwind }
1297 | Vectorcall { unwind }
1298 | Thiscall { unwind }
1299 | Aapcs { unwind }
1300 | Win64 { unwind }
1301 | SysV64 { unwind } => unwind,
1302 PtxKernel
1303 | Msp430Interrupt
1304 | X86Interrupt
1305 | GpuKernel
1306 | EfiApi
1307 | AvrInterrupt
1308 | AvrNonBlockingInterrupt
1309 | CmseNonSecureCall
1310 | CmseNonSecureEntry
1311 | Custom
1312 | RiscvInterruptM
1313 | RiscvInterruptS
1314 | RustInvalid
1315 | Swift
1316 | Unadjusted => false,
1317 Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1318 tcx.sess.panic_strategy().unwinds()
1319 }
1320 }
1321}
1322
1323#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for FnAbiError<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for FnAbiError<'tcx> {
#[inline]
fn clone(&self) -> FnAbiError<'tcx> {
let _: ::core::clone::AssertParamIsClone<LayoutError<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiError<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FnAbiError::Layout(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Layout",
&__self_0),
}
}
}Debug, const _: () =
{
impl<'tcx> ::rustc_data_structures::stable_hash::StableHash for
FnAbiError<'tcx> {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
FnAbiError::Layout(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
1325pub enum FnAbiError<'tcx> {
1326 Layout(LayoutError<'tcx>),
1328}
1329
1330impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1331 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1332 match self {
1333 Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1334 }
1335 }
1336}
1337
1338#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for FnAbiRequest<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FnAbiRequest::OfFnPtr { sig: __self_0, extra_args: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"OfFnPtr", "sig", __self_0, "extra_args", &__self_1),
FnAbiRequest::OfInstance {
instance: __self_0, extra_args: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"OfInstance", "instance", __self_0, "extra_args",
&__self_1),
}
}
}Debug)]
1341pub enum FnAbiRequest<'tcx> {
1342 OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1343 OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1344}
1345
1346pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1349 type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1352
1353 fn handle_fn_abi_err(
1361 &self,
1362 err: FnAbiError<'tcx>,
1363 span: Span,
1364 fn_abi_request: FnAbiRequest<'tcx>,
1365 ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1366}
1367
1368pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1370 #[inline]
1375 fn fn_abi_of_fn_ptr(
1376 &self,
1377 sig: ty::PolyFnSig<'tcx>,
1378 extra_args: &'tcx ty::List<Ty<'tcx>>,
1379 ) -> Self::FnAbiOfResult {
1380 let span = self.layout_tcx_at_span();
1382 let tcx = self.tcx().at(span);
1383
1384 MaybeResult::from(
1385 tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1386 |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1387 ),
1388 )
1389 }
1390
1391 #[inline]
1403 #[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_of_instance_no_deduced_attrs",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1403u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::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()
},
{
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(&instance)
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: Self::FnAbiOfResult = loop {};
return __tracing_attr_fake_return;
}
{
let span = self.layout_tcx_at_span();
let tcx = self.tcx().at(span);
MaybeResult::from(tcx.fn_abi_of_instance_no_deduced_attrs(self.typing_env().as_query_input((instance,
extra_args))).map_err(|err|
{
let span =
if !span.is_dummy() {
span
} else { tcx.def_span(instance.def_id()) };
self.handle_fn_abi_err(*err, span,
FnAbiRequest::OfInstance { instance, extra_args })
}))
}
}
}#[tracing::instrument(level = "debug", skip(self))]
1404 fn fn_abi_of_instance_no_deduced_attrs(
1405 &self,
1406 instance: ty::Instance<'tcx>,
1407 extra_args: &'tcx ty::List<Ty<'tcx>>,
1408 ) -> Self::FnAbiOfResult {
1409 let span = self.layout_tcx_at_span();
1411 let tcx = self.tcx().at(span);
1412
1413 MaybeResult::from(
1414 tcx.fn_abi_of_instance_no_deduced_attrs(
1415 self.typing_env().as_query_input((instance, extra_args)),
1416 )
1417 .map_err(|err| {
1418 let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1423 self.handle_fn_abi_err(
1424 *err,
1425 span,
1426 FnAbiRequest::OfInstance { instance, extra_args },
1427 )
1428 }),
1429 )
1430 }
1431
1432 #[inline]
1442 #[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_of_instance",
"rustc_middle::ty::layout", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/layout.rs"),
::tracing_core::__macro_support::Option::Some(1442u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::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()
},
{
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(&instance)
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: Self::FnAbiOfResult = loop {};
return __tracing_attr_fake_return;
}
{
let span = self.layout_tcx_at_span();
let tcx = self.tcx().at(span);
MaybeResult::from(tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance,
extra_args))).map_err(|err|
{
let span =
if !span.is_dummy() {
span
} else { tcx.def_span(instance.def_id()) };
self.handle_fn_abi_err(*err, span,
FnAbiRequest::OfInstance { instance, extra_args })
}))
}
}
}#[tracing::instrument(level = "debug", skip(self))]
1443 fn fn_abi_of_instance(
1444 &self,
1445 instance: ty::Instance<'tcx>,
1446 extra_args: &'tcx ty::List<Ty<'tcx>>,
1447 ) -> Self::FnAbiOfResult {
1448 let span = self.layout_tcx_at_span();
1450 let tcx = self.tcx().at(span);
1451
1452 MaybeResult::from(
1453 tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1454 .map_err(|err| {
1455 let span =
1460 if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1461 self.handle_fn_abi_err(
1462 *err,
1463 span,
1464 FnAbiRequest::OfInstance { instance, extra_args },
1465 )
1466 }),
1467 )
1468 }
1469}
1470
1471impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}