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 = " discriminant range and `#[repr]` attribute."]
#[doc = ""]
#[doc =
" To represent the way the values were written in the rust source, min and max"]
#[doc =
" are in different types. It\'s thus possible to pass in an unrepresentable range,"]
#[doc = " and the method will panic in those cases."]
#[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_negative: i128, max_positive: u128)
-> (abi::Integer, bool) {
if !(min_negative >= 0 || max_positive <= i128::MAX.cast_unsigned()) {
{
::core::panicking::panic_fmt(format_args!("No type can represent the full range of {0}..={1}",
min_negative, max_positive));
}
};
let unsigned_fit =
abi::Integer::fit_unsigned(cmp::max(min_negative.cast_unsigned(),
max_positive));
let signed_fit =
cmp::max(abi::Integer::fit_signed(min_negative),
abi::Integer::fit_signed(max_positive.cast_signed()));
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>(
81 tcx: TyCtxt<'tcx>,
82 ty: Ty<'tcx>,
83 repr: &ReprOptions,
84 min_negative: i128,
85 max_positive: u128,
86 ) -> (abi::Integer, bool) {
87 assert!(
88 min_negative >= 0 || max_positive <= i128::MAX.cast_unsigned(),
89 "No type can represent the full range of {min_negative}..={max_positive}",
90 );
91
92 let unsigned_fit =
97 abi::Integer::fit_unsigned(cmp::max(min_negative.cast_unsigned(), max_positive));
98 let signed_fit = cmp::max(
99 abi::Integer::fit_signed(min_negative),
100 abi::Integer::fit_signed(max_positive.cast_signed()),
101 );
102
103 if let Some(ity) = repr.int {
104 let discr = abi::Integer::from_attr(&tcx, ity);
105 let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
106 if discr < fit {
107 bug!(
108 "Integer::repr_discr: `#[repr]` hint too small for \
109 discriminant range of enum `{}`",
110 ty
111 )
112 }
113 return (discr, ity.is_signed());
114 }
115
116 let at_least = if repr.c() {
117 tcx.data_layout().c_enum_min_size
120 } else {
121 abi::Integer::I8
123 };
124
125 if unsigned_fit <= signed_fit {
128 (cmp::max(unsigned_fit, at_least), false)
129 } else {
130 (cmp::max(signed_fit, at_least), true)
131 }
132 }
133}
134
135impl 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)]
136impl abi::Float {
137 #[inline]
138 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
139 use abi::Float::*;
140 match *self {
141 F16 => tcx.types.f16,
142 F32 => tcx.types.f32,
143 F64 => tcx.types.f64,
144 F128 => tcx.types.f128,
145 }
146 }
147
148 fn from_float_ty(fty: ty::FloatTy) -> Self {
149 use abi::Float::*;
150 match fty {
151 ty::FloatTy::F16 => F16,
152 ty::FloatTy::F32 => F32,
153 ty::FloatTy::F64 => F64,
154 ty::FloatTy::F128 => F128,
155 }
156 }
157}
158
159impl 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)]
160impl Primitive {
161 #[inline]
162 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
163 match *self {
164 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
165 Primitive::Float(f) => f.to_ty(tcx),
166 Primitive::Pointer(_) => Ty::new_mut_ptr(tcx, tcx.types.unit),
168 }
169 }
170
171 #[inline]
174 fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
175 match *self {
176 Primitive::Int(i, signed) => i.to_ty(tcx, signed),
177 Primitive::Pointer(_) => {
179 let signed = false;
180 tcx.data_layout().ptr_sized_integer().to_ty(tcx, signed)
181 }
182 Primitive::Float(_) => bug!("floats do not have an int type"),
183 }
184 }
185}
186
187pub const WIDE_PTR_ADDR: usize = 0;
192
193pub const WIDE_PTR_EXTRA: usize = 1;
198
199#[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)]
202pub enum ValidityRequirement {
203 Inhabited,
204 Zero,
205 UninitMitigated0x01Fill,
208 Uninit,
210}
211
212impl ValidityRequirement {
213 pub fn from_intrinsic(intrinsic: Symbol) -> Option<Self> {
214 match intrinsic {
215 sym::assert_inhabited => Some(Self::Inhabited),
216 sym::assert_zero_valid => Some(Self::Zero),
217 sym::assert_mem_uninitialized_valid => Some(Self::UninitMitigated0x01Fill),
218 _ => None,
219 }
220 }
221}
222
223impl fmt::Display for ValidityRequirement {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 match self {
226 Self::Inhabited => f.write_str("is inhabited"),
227 Self::Zero => f.write_str("allows being left zeroed"),
228 Self::UninitMitigated0x01Fill => f.write_str("allows being filled with 0x01"),
229 Self::Uninit => f.write_str("allows being left uninitialized"),
230 }
231 }
232}
233
234#[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<Limit>;
*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)]
235pub enum SimdLayoutError {
236 ZeroLength,
238 TooManyLanes(Limit),
241}
242
243#[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)]
244pub enum LayoutError<'tcx> {
245 Unknown(Ty<'tcx>),
253 SizeOverflow(Ty<'tcx>),
255 InvalidSimd { ty: Ty<'tcx>, kind: SimdLayoutError },
257 TooGeneric(Ty<'tcx>),
262 NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>),
270 ReferencesError(ErrorGuaranteed),
272}
273
274impl<'tcx> fmt::Display for LayoutError<'tcx> {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 match *self {
277 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"),
278 LayoutError::TooGeneric(ty) => {
279 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")
280 }
281 LayoutError::SizeOverflow(ty) => {
282 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")
283 }
284 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::TooManyLanes(max_lanes) } => {
285 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}")
286 }
287 LayoutError::InvalidSimd { ty, kind: SimdLayoutError::ZeroLength } => {
288 f.write_fmt(format_args!("the SIMD type `{0}` has zero elements", ty))write!(f, "the SIMD type `{ty}` has zero elements")
289 }
290 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!(
291 f,
292 "unable to determine layout for `{}` because `{}` cannot be normalized",
293 t,
294 e.get_type_for_failure()
295 ),
296 LayoutError::ReferencesError(_) => f.write_fmt(format_args!("the type has an unknown layout"))write!(f, "the type has an unknown layout"),
297 }
298 }
299}
300
301impl<'tcx> IntoDiagArg for LayoutError<'tcx> {
302 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
303 self.to_string().into_diag_arg(&mut None)
304 }
305}
306
307#[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)]
308pub struct LayoutCx<'tcx> {
309 pub calc: abi::LayoutCalculator<TyCtxt<'tcx>>,
310 pub typing_env: ty::TypingEnv<'tcx>,
311}
312
313impl<'tcx> LayoutCx<'tcx> {
314 pub fn new(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> Self {
315 Self { calc: abi::LayoutCalculator::new(tcx), typing_env }
316 }
317}
318
319#[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)]
324pub enum SizeSkeleton<'tcx> {
325 Known(Size, Option<Align>),
328
329 Pointer {
331 non_zero: bool,
333 tail: Ty<'tcx>,
337 },
338}
339
340impl<'tcx> SizeSkeleton<'tcx> {
341 pub fn compute(
342 ty: Ty<'tcx>,
343 tcx: TyCtxt<'tcx>,
344 typing_env: ty::TypingEnv<'tcx>,
345 span: Span,
346 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
347 Self::compute_inner(ty, tcx, typing_env, span, 0)
348 }
349
350 fn compute_inner(
351 ty: Ty<'tcx>,
352 tcx: TyCtxt<'tcx>,
353 typing_env: ty::TypingEnv<'tcx>,
354 span: Span,
355 depth: usize,
356 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
357 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());
358
359 let recursion_limit = tcx.recursion_limit();
364 if depth >= recursion_limit.0 {
365 let suggested_limit = match recursion_limit {
366 Limit(0) => Limit(2),
367 limit => limit * 2,
368 };
369 let reported = tcx.dcx().emit_err(crate::error::RecursionLimitReachedSizeSkeleton {
370 span,
371 ty,
372 suggested_limit,
373 });
374 return Err(tcx.arena.alloc(LayoutError::ReferencesError(reported)));
375 }
376
377 let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
379 Ok(layout) => {
380 if layout.is_sized() {
381 return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
382 } else {
383 return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
385 }
386 }
387 Err(err @ LayoutError::TooGeneric(_)) => err,
388 Err(
390 e @ LayoutError::Unknown(_)
391 | e @ LayoutError::SizeOverflow(_)
392 | e @ LayoutError::InvalidSimd { .. }
393 | e @ LayoutError::NormalizationFailure(..)
394 | e @ LayoutError::ReferencesError(_),
395 ) => return Err(e),
396 };
397
398 match *ty.kind() {
399 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
400 let non_zero = !ty.is_raw_ptr();
401
402 tcx.assert_fully_normalized(typing_env, pointee);
403 let tail = tcx.struct_tail_raw(
404 pointee,
405 &ObligationCause::dummy(),
406 |ty| match tcx.try_normalize_erasing_regions(typing_env, ty) {
407 Ok(ty) => ty,
408 Err(e) => Ty::new_error_with_message(
409 tcx,
410 DUMMY_SP,
411 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
e.get_type_for_failure()))
})format!(
412 "normalization failed for {} but no errors reported",
413 e.get_type_for_failure()
414 ),
415 ),
416 },
417 || {},
418 );
419
420 match tail.kind() {
421 ty::Param(_)
424 | ty::Alias(
425 _,
426 ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. },
427 ) => {
428 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());
429 Ok(SizeSkeleton::Pointer {
430 non_zero,
431 tail: tcx.erase_and_anonymize_regions(tail),
432 })
433 }
434 ty::Error(guar) => {
435 return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
437 }
438 _ => 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!(
439 "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
440 tail `{tail}` is not a type parameter or a projection",
441 ),
442 }
443 }
444 ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
445 let len_eval = len.try_to_target_usize(tcx);
446 if len_eval == Some(0) {
447 return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
448 }
449
450 match SizeSkeleton::compute_inner(inner, tcx, typing_env, span, depth + 1)? {
451 SizeSkeleton::Known(s, a) => {
454 if let Some(c) = len_eval {
455 let size = s
456 .bytes()
457 .checked_mul(c)
458 .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
459 return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
461 }
462 Err(err)
463 }
464 SizeSkeleton::Pointer { .. } => Err(err),
465 }
466 }
467
468 ty::Adt(def, args) => {
469 if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
471 return Err(err);
472 }
473 {
475 let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } =
480 def.repr();
481 let mut ignored_flags = ReprFlags::IS_TRANSPARENT
482 | ReprFlags::IS_LINEAR
483 | ReprFlags::RANDOMIZE_LAYOUT;
484 if def.is_struct() {
485 ignored_flags |= ReprFlags::IS_C;
490 }
491 if int.is_some()
492 || align.is_some()
493 || pack.is_some()
494 || flags.difference(ignored_flags) != ReprFlags::default()
495 || scalable.is_some()
496 {
497 return Err(err);
498 }
499 }
500
501 let zero_or_ptr_variant = |i| -> Result<Option<SizeSkeleton<'tcx>>, _> {
505 let i = VariantIdx::from_usize(i);
506 let fields = def.variant(i).fields.iter().map(|field| {
507 SizeSkeleton::compute_inner(
508 field.ty(tcx, args).skip_norm_wip(),
509 tcx,
510 typing_env,
511 span,
512 depth + 1,
513 )
514 });
515 let mut ptr = None;
516 for field in fields {
517 let field = field?;
518 match field {
519 SizeSkeleton::Known(size, align) => {
520 let is_1zst = size.bytes() == 0
521 && align.is_some_and(|align| align.bytes() == 1);
522 if !is_1zst {
523 return Err(err);
524 }
525 }
526 SizeSkeleton::Pointer { .. } => {
527 if ptr.is_some() {
528 return Err(err);
529 }
530 ptr = Some(field);
531 }
532 }
533 }
534 Ok(ptr)
535 };
536
537 let v0 = zero_or_ptr_variant(0)?;
538 if def.variants().len() == 1 {
541 if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
542 return Ok(SizeSkeleton::Pointer { non_zero, tail });
543 } else {
544 return Err(err);
545 }
546 }
547
548 let v1 = zero_or_ptr_variant(1)?;
549 match (v0, v1) {
553 (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
554 | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
555 Ok(SizeSkeleton::Pointer { non_zero: false, tail })
556 }
557 _ => Err(err),
558 }
559 }
560
561 ty::Alias(..) => {
562 let normalized =
563 tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
564 if ty == normalized {
565 Err(err)
566 } else {
567 SizeSkeleton::compute_inner(normalized, tcx, typing_env, span, depth + 1)
568 }
569 }
570
571 ty::Pat(base, pat) => {
572 let base = SizeSkeleton::compute_inner(base, tcx, typing_env, span, depth + 1);
574 match *pat {
575 ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
576 ty::PatternKind::NotNull => match base? {
579 SizeSkeleton::Known(..) => base,
580 SizeSkeleton::Pointer { non_zero: _, tail } => {
581 Ok(SizeSkeleton::Pointer { non_zero: true, tail })
582 }
583 },
584 }
585 }
586
587 _ => Err(err),
588 }
589 }
590
591 pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
592 match (self, other) {
593 (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
594 (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
595 a == b
596 }
597 _ => false,
598 }
599 }
600}
601
602pub trait HasTyCtxt<'tcx>: HasDataLayout {
603 fn tcx(&self) -> TyCtxt<'tcx>;
604}
605
606pub trait HasTypingEnv<'tcx> {
607 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
608}
609
610impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
611 #[inline]
612 fn data_layout(&self) -> &TargetDataLayout {
613 &self.data_layout
614 }
615}
616
617impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
618 fn target_spec(&self) -> &Target {
619 &self.sess.target
620 }
621}
622
623impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
624 fn x86_abi_opt(&self) -> X86Abi {
625 X86Abi {
626 regparm: self.sess.opts.unstable_opts.regparm,
627 reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
628 }
629 }
630}
631
632impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
633 #[inline]
634 fn tcx(&self) -> TyCtxt<'tcx> {
635 *self
636 }
637}
638
639impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
640 #[inline]
641 fn data_layout(&self) -> &TargetDataLayout {
642 &self.data_layout
643 }
644}
645
646impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
647 fn target_spec(&self) -> &Target {
648 &self.sess.target
649 }
650}
651
652impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
653 #[inline]
654 fn tcx(&self) -> TyCtxt<'tcx> {
655 **self
656 }
657}
658
659impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
660 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
661 self.typing_env
662 }
663}
664
665impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
666 fn data_layout(&self) -> &TargetDataLayout {
667 self.calc.cx.data_layout()
668 }
669}
670
671impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
672 fn target_spec(&self) -> &Target {
673 self.calc.cx.target_spec()
674 }
675}
676
677impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
678 fn x86_abi_opt(&self) -> X86Abi {
679 self.calc.cx.x86_abi_opt()
680 }
681}
682
683impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
684 fn tcx(&self) -> TyCtxt<'tcx> {
685 self.calc.cx
686 }
687}
688
689pub trait MaybeResult<T> {
690 type Error;
691
692 fn from(x: Result<T, Self::Error>) -> Self;
693 fn to_result(self) -> Result<T, Self::Error>;
694}
695
696impl<T> MaybeResult<T> for T {
697 type Error = !;
698
699 fn from(Ok(x): Result<T, Self::Error>) -> Self {
700 x
701 }
702 fn to_result(self) -> Result<T, Self::Error> {
703 Ok(self)
704 }
705}
706
707impl<T, E> MaybeResult<T> for Result<T, E> {
708 type Error = E;
709
710 fn from(x: Result<T, Self::Error>) -> Self {
711 x
712 }
713 fn to_result(self) -> Result<T, Self::Error> {
714 self
715 }
716}
717
718pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
719
720pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
723 type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
726
727 #[inline]
730 fn layout_tcx_at_span(&self) -> Span {
731 DUMMY_SP
732 }
733
734 fn handle_layout_err(
742 &self,
743 err: LayoutError<'tcx>,
744 span: Span,
745 ty: Ty<'tcx>,
746 ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
747}
748
749pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
751 #[inline]
754 fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
755 self.spanned_layout_of(ty, DUMMY_SP)
756 }
757
758 #[inline]
763 fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
764 let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
765 let tcx = self.tcx().at(span);
766
767 MaybeResult::from(
768 tcx.layout_of(self.typing_env().as_query_input(ty))
769 .map_err(|err| self.handle_layout_err(*err, span, ty)),
770 )
771 }
772}
773
774impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
775
776impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
777 type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
778
779 #[inline]
780 fn handle_layout_err(
781 &self,
782 err: LayoutError<'tcx>,
783 _: Span,
784 _: Ty<'tcx>,
785 ) -> &'tcx LayoutError<'tcx> {
786 self.tcx().arena.alloc(err)
787 }
788}
789
790impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
791where
792 C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
793{
794 fn ty_and_layout_for_variant(
795 this: TyAndLayout<'tcx>,
796 cx: &C,
797 variant_index: VariantIdx,
798 ) -> TyAndLayout<'tcx> {
799 let layout = match this.variants {
800 Variants::Single { index } if index == variant_index => {
802 return this;
803 }
804
805 Variants::Single { .. } | Variants::Empty => {
806 let tcx = cx.tcx();
811 let typing_env = cx.typing_env();
812
813 if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
815 {
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);
816 }
817
818 let fields = match this.ty.kind() {
819 ty::Adt(def, _) if def.variants().is_empty() => {
820 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)
821 }
822 ty::Adt(def, _) => def.variant(variant_index).fields.len(),
823 _ => 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),
824 };
825 tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
826 }
827
828 Variants::Multiple { .. } => {
829 cx.tcx().mk_layout(LayoutData::for_variant(&this, variant_index))
830 }
831 };
832
833 {
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 });
834
835 TyAndLayout { ty: this.ty, layout }
836 }
837
838 fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
839 enum TyMaybeWithLayout<'tcx> {
840 Ty(Ty<'tcx>),
841 TyAndLayout(TyAndLayout<'tcx>),
842 }
843
844 fn field_ty_or_layout<'tcx>(
845 this: TyAndLayout<'tcx>,
846 cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
847 i: usize,
848 ) -> TyMaybeWithLayout<'tcx> {
849 let tcx = cx.tcx();
850 let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
851 TyAndLayout {
852 layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
853 ty: tag.primitive().to_ty(tcx),
854 }
855 };
856
857 match *this.ty.kind() {
858 ty::Bool
859 | ty::Char
860 | ty::Int(_)
861 | ty::Uint(_)
862 | ty::Float(_)
863 | ty::FnPtr(..)
864 | ty::Never
865 | ty::FnDef(..)
866 | ty::CoroutineWitness(..)
867 | ty::Foreign(..)
868 | ty::Dynamic(_, _) => {
869 crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this)
870 }
871
872 ty::Pat(base, _) => {
873 {
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);
874 TyMaybeWithLayout::Ty(base)
875 }
876
877 ty::UnsafeBinder(bound_ty) => {
878 let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
879 field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
880 }
881
882 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
884 if !(i < this.fields.count()) {
::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
885
886 if i == 0 {
891 let nil = tcx.types.unit;
892 let unit_ptr_ty = if this.ty.is_raw_ptr() {
893 Ty::new_mut_ptr(tcx, nil)
894 } else {
895 Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
896 };
897
898 let typing_env = ty::TypingEnv::fully_monomorphized();
902 return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
903 ty: this.ty,
904 ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
905 });
906 }
907
908 let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
909 let min_count = ty::vtable_min_entries(
910 tcx,
911 principal.map(|principal| {
912 tcx.instantiate_bound_regions_with_erased(principal)
913 }),
914 );
915 Ty::new_imm_ref(
916 tcx,
917 tcx.lifetimes.re_static,
918 Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
920 )
921 };
922
923 let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
924 && !pointee.references_error()
927 {
928 let metadata = tcx.normalize_erasing_regions(
929 cx.typing_env(),
930 Unnormalized::new(Ty::new_projection(
931 tcx,
932 ty::IsRigid::No,
933 metadata_def_id,
934 [pointee],
935 )),
936 );
937
938 if let ty::Adt(def, args) = metadata.kind()
943 && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
944 && let ty::Dynamic(data, _) = args.type_at(0).kind()
945 {
946 mk_dyn_vtable(data.principal())
947 } else {
948 metadata
949 }
950 } else {
951 match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
952 ty::Slice(_) | ty::Str => tcx.types.usize,
953 ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
954 _ => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this),
955 }
956 };
957
958 TyMaybeWithLayout::Ty(metadata)
959 }
960
961 ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
963 ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
964
965 ty::Closure(_, args) => field_ty_or_layout(
967 TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
968 cx,
969 i,
970 ),
971
972 ty::CoroutineClosure(_, args) => field_ty_or_layout(
973 TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
974 cx,
975 i,
976 ),
977
978 ty::Coroutine(def_id, args) => match this.variants {
979 Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
980 Variants::Single { index } => TyMaybeWithLayout::Ty(
981 args.as_coroutine()
982 .state_tys(def_id, tcx)
983 .nth(index.as_usize())
984 .unwrap()
985 .nth(i)
986 .unwrap(),
987 ),
988 Variants::Multiple { tag, tag_field, .. } => {
989 if FieldIdx::from_usize(i) == tag_field {
990 TyMaybeWithLayout::TyAndLayout(tag_layout(tag))
991 } else {
992 TyMaybeWithLayout::Ty(args.as_coroutine().upvar_tys()[i])
993 }
994 }
995 },
996
997 ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
998
999 ty::Adt(def, args) => {
1001 match this.variants {
1002 Variants::Single { index } => {
1003 let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
1004 TyMaybeWithLayout::Ty(field.ty(tcx, args).skip_norm_wip())
1005 }
1006 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"),
1007
1008 Variants::Multiple { tag, .. } => {
1010 {
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);
1011 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
1012 }
1013 }
1014 }
1015
1016 ty::Alias(..)
1017 | ty::Bound(..)
1018 | ty::Placeholder(..)
1019 | ty::Param(_)
1020 | ty::Infer(_)
1021 | ty::Error(_) => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field: unexpected type `{0}`",
this.ty))bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
1022 }
1023 }
1024
1025 match field_ty_or_layout(this, cx, i) {
1026 TyMaybeWithLayout::Ty(field_ty) => {
1027 cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
1028 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!(
1029 "failed to get layout for `{field_ty}`: {e:?},\n\
1030 despite it being a field (#{i}) of an existing layout: {this:#?}",
1031 )
1032 })
1033 }
1034 TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
1035 }
1036 }
1037
1038 fn ty_and_layout_pointee_info_at(
1041 this: TyAndLayout<'tcx>,
1042 cx: &C,
1043 offset: Size,
1044 ) -> Option<PointeeInfo> {
1045 let tcx = cx.tcx();
1046 let typing_env = cx.typing_env();
1047
1048 let optimize = tcx.sess.opts.optimize != OptLevel::No;
1052
1053 let pointee_info = match *this.ty.kind() {
1054 ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
1055 Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
1056 }
1057 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
1058 tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
1059 let kind = match mt {
1060 hir::Mutability::Not => {
1061 let frozen = optimize && ty.is_freeze(tcx, typing_env);
1062 PointerKind::SharedRef { frozen }
1063 }
1064 hir::Mutability::Mut => {
1065 let unpin = optimize
1066 && ty.is_unpin(tcx, typing_env)
1067 && ty.is_unsafe_unpin(tcx, typing_env);
1068 PointerKind::MutableRef { unpin }
1069 }
1070 };
1071 PointeeInfo { safe: Some(kind), size: layout.size, align: layout.align.abi }
1072 })
1073 }
1074
1075 ty::Adt(..)
1076 if offset.bytes() == 0
1077 && let Some(pointee) = this.ty.boxed_ty() =>
1078 {
1079 tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1080 safe: Some(PointerKind::Box {
1081 unpin: optimize
1083 && pointee.is_unpin(tcx, typing_env)
1084 && pointee.is_unsafe_unpin(tcx, typing_env),
1085 global: this.ty.is_box_global(tcx),
1086 }),
1087 size: layout.size,
1088 align: layout.align.abi,
1089 })
1090 }
1091
1092 ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
1093 Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset).map(|info| {
1094 PointeeInfo {
1095 safe: None,
1098 size: Size::ZERO,
1100 align: info.align,
1102 }
1103 })
1104 }
1105
1106 _ => {
1107 let mut data_variant = match &this.variants {
1108 Variants::Multiple {
1118 tag_encoding:
1119 TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1120 tag_field,
1121 variants,
1122 ..
1123 } if variants.len() == 2
1124 && this.fields.offset(tag_field.as_usize()) == offset =>
1125 {
1126 let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1127 VariantIdx::from_u32(1)
1128 } else {
1129 VariantIdx::from_u32(0)
1130 };
1131 {
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);
1132 if *niche_start == 0 {
1133 Some(this.for_variant(cx, *untagged_variant))
1139 } else {
1140 None
1141 }
1142 }
1143 Variants::Multiple { .. } => None,
1144 Variants::Empty | Variants::Single { .. } => Some(this),
1145 };
1146
1147 if let Some(variant) = data_variant
1148 && let FieldsShape::Union(_) = variant.fields
1150 {
1151 data_variant = None;
1152 }
1153
1154 let mut result = None;
1155
1156 if let Some(variant) = data_variant {
1157 let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1160 for i in 0..variant.fields.count() {
1161 let field_start = variant.fields.offset(i);
1162 if field_start <= offset {
1163 let field = variant.field(cx, i);
1164 result = field.to_result().ok().and_then(|field| {
1165 if ptr_end <= field_start + field.size {
1166 let field_info =
1168 field.pointee_info_at(cx, offset - field_start);
1169 field_info
1170 } else {
1171 None
1172 }
1173 });
1174 if result.is_some() {
1175 break;
1176 }
1177 }
1178 }
1179 }
1180
1181 result
1182 }
1183 };
1184
1185 {
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:1185",
"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(1185u32),
::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!(
1186 "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1187 offset,
1188 this.ty.kind(),
1189 pointee_info
1190 );
1191
1192 pointee_info
1193 }
1194
1195 fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1196 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1197 }
1198
1199 fn is_never(this: TyAndLayout<'tcx>) -> bool {
1200 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Never => true,
_ => false,
}matches!(this.ty.kind(), ty::Never)
1201 }
1202
1203 fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1204 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1205 }
1206
1207 fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1208 #[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)
1209 }
1210
1211 fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1212 #[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())
1213 }
1214
1215 fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1216 this.ty.is_scalable_vector()
1217 }
1218
1219 fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1221 #[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))
1222 }
1223}
1224
1225#[inline]
1266#[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(1266u32),
::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))]
1267pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1268 if let Some(did) = fn_def_id {
1269 if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1271 return false;
1272 }
1273
1274 if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1279 return false;
1280 }
1281
1282 if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1287 && tcx.is_lang_item(did, LangItem::DropGlue)
1288 {
1289 return false;
1290 }
1291 }
1292
1293 use ExternAbi::*;
1300 match abi {
1301 C { unwind }
1302 | System { unwind }
1303 | Cdecl { unwind }
1304 | Stdcall { unwind }
1305 | Fastcall { unwind }
1306 | Vectorcall { unwind }
1307 | Thiscall { unwind }
1308 | Aapcs { unwind }
1309 | Win64 { unwind }
1310 | SysV64 { unwind } => unwind,
1311 PtxKernel
1312 | Msp430Interrupt
1313 | X86Interrupt
1314 | GpuKernel
1315 | EfiApi
1316 | AvrInterrupt
1317 | AvrNonBlockingInterrupt
1318 | CmseNonSecureCall
1319 | CmseNonSecureEntry
1320 | Custom
1321 | RiscvInterruptM
1322 | RiscvInterruptS
1323 | RustInvalid
1324 | Swift
1325 | Unadjusted => false,
1326 Rust | RustCall | RustCold | RustPreserveNone | RustTail => {
1327 tcx.sess.panic_strategy().unwinds()
1328 }
1329 }
1330}
1331
1332#[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)]
1334pub enum FnAbiError<'tcx> {
1335 Layout(LayoutError<'tcx>),
1337}
1338
1339impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1340 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1341 match self {
1342 Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1343 }
1344 }
1345}
1346
1347#[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)]
1350pub enum FnAbiRequest<'tcx> {
1351 OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1352 OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1353}
1354
1355pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1358 type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1361
1362 fn handle_fn_abi_err(
1370 &self,
1371 err: FnAbiError<'tcx>,
1372 span: Span,
1373 fn_abi_request: FnAbiRequest<'tcx>,
1374 ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1375}
1376
1377pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1379 #[inline]
1384 fn fn_abi_of_fn_ptr(
1385 &self,
1386 sig: ty::PolyFnSig<'tcx>,
1387 extra_args: &'tcx ty::List<Ty<'tcx>>,
1388 ) -> Self::FnAbiOfResult {
1389 let span = self.layout_tcx_at_span();
1391 let tcx = self.tcx().at(span);
1392
1393 MaybeResult::from(
1394 tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1395 |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1396 ),
1397 )
1398 }
1399
1400 #[inline]
1412 #[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(1412u32),
::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))]
1413 fn fn_abi_of_instance_no_deduced_attrs(
1414 &self,
1415 instance: ty::Instance<'tcx>,
1416 extra_args: &'tcx ty::List<Ty<'tcx>>,
1417 ) -> Self::FnAbiOfResult {
1418 let span = self.layout_tcx_at_span();
1420 let tcx = self.tcx().at(span);
1421
1422 MaybeResult::from(
1423 tcx.fn_abi_of_instance_no_deduced_attrs(
1424 self.typing_env().as_query_input((instance, extra_args)),
1425 )
1426 .map_err(|err| {
1427 let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1432 self.handle_fn_abi_err(
1433 *err,
1434 span,
1435 FnAbiRequest::OfInstance { instance, extra_args },
1436 )
1437 }),
1438 )
1439 }
1440
1441 #[inline]
1451 #[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(1451u32),
::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))]
1452 fn fn_abi_of_instance(
1453 &self,
1454 instance: ty::Instance<'tcx>,
1455 extra_args: &'tcx ty::List<Ty<'tcx>>,
1456 ) -> Self::FnAbiOfResult {
1457 let span = self.layout_tcx_at_span();
1459 let tcx = self.tcx().at(span);
1460
1461 MaybeResult::from(
1462 tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1463 .map_err(|err| {
1464 let span =
1469 if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1470 self.handle_fn_abi_err(
1471 *err,
1472 span,
1473 FnAbiRequest::OfInstance { instance, extra_args },
1474 )
1475 }),
1476 )
1477 }
1478}
1479
1480impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}