1use std::ops::Bound;
2use std::{cmp, fmt};
3
4use rustc_abi as abi;
5use rustc_abi::{
6 AddressSpace, Align, ExternAbi, FieldIdx, FieldsShape, HasDataLayout, LayoutData, PointeeInfo,
7 PointerKind, Primitive, ReprFlags, ReprOptions, Scalar, Size, TagEncoding, TargetDataLayout,
8 TyAbiInterface, VariantIdx, Variants,
9};
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::{HashStable, 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<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for ValidityRequirement {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
ValidityRequirement::Inhabited => {}
ValidityRequirement::Zero => {}
ValidityRequirement::UninitMitigated0x01Fill => {}
ValidityRequirement::Uninit => {}
}
}
}
};HashStable)]
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<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for SimdLayoutError {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
SimdLayoutError::ZeroLength => {}
SimdLayoutError::TooManyLanes(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable, 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, '__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for LayoutError<'tcx> {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
LayoutError::Unknown(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
LayoutError::SizeOverflow(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
LayoutError::InvalidSimd {
ty: ref __binding_0, kind: ref __binding_1 } => {
{ __binding_0.hash_stable(__hcx, __hasher); }
{ __binding_1.hash_stable(__hcx, __hasher); }
}
LayoutError::TooGeneric(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
LayoutError::NormalizationFailure(ref __binding_0,
ref __binding_1) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
{ __binding_1.hash_stable(__hcx, __hasher); }
}
LayoutError::ReferencesError(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable, 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 ) -> Result<SizeSkeleton<'tcx>, &'tcx LayoutError<'tcx>> {
337 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());
338
339 let err = match tcx.layout_of(typing_env.as_query_input(ty)) {
341 Ok(layout) => {
342 if layout.is_sized() {
343 return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
344 } else {
345 return Err(tcx.arena.alloc(LayoutError::Unknown(ty)));
347 }
348 }
349 Err(err @ LayoutError::TooGeneric(_)) => err,
350 Err(
352 e @ LayoutError::Unknown(_)
353 | e @ LayoutError::SizeOverflow(_)
354 | e @ LayoutError::InvalidSimd { .. }
355 | e @ LayoutError::NormalizationFailure(..)
356 | e @ LayoutError::ReferencesError(_),
357 ) => return Err(e),
358 };
359
360 match *ty.kind() {
361 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
362 let non_zero = !ty.is_raw_ptr();
363
364 let tail = tcx.struct_tail_raw(
365 pointee,
366 &ObligationCause::dummy(),
367 |ty| match tcx
368 .try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty))
369 {
370 Ok(ty) => ty,
371 Err(e) => Ty::new_error_with_message(
372 tcx,
373 DUMMY_SP,
374 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("normalization failed for {0} but no errors reported",
e.get_type_for_failure()))
})format!(
375 "normalization failed for {} but no errors reported",
376 e.get_type_for_failure()
377 ),
378 ),
379 },
380 || {},
381 );
382
383 match tail.kind() {
384 ty::Param(_)
385 | ty::Alias(ty::AliasTy {
386 kind: ty::Projection { .. } | ty::Inherent { .. },
387 ..
388 }) => {
389 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());
390 Ok(SizeSkeleton::Pointer {
391 non_zero,
392 tail: tcx.erase_and_anonymize_regions(tail),
393 })
394 }
395 ty::Error(guar) => {
396 return Err(tcx.arena.alloc(LayoutError::ReferencesError(*guar)));
398 }
399 _ => 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!(
400 "SizeSkeleton::compute({ty}): layout errored ({err:?}), yet \
401 tail `{tail}` is not a type parameter or a projection",
402 ),
403 }
404 }
405 ty::Array(inner, len) if tcx.features().transmute_generic_consts() => {
406 let len_eval = len.try_to_target_usize(tcx);
407 if len_eval == Some(0) {
408 return Ok(SizeSkeleton::Known(Size::from_bytes(0), None));
409 }
410
411 match SizeSkeleton::compute(inner, tcx, typing_env)? {
412 SizeSkeleton::Known(s, a) => {
415 if let Some(c) = len_eval {
416 let size = s
417 .bytes()
418 .checked_mul(c)
419 .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?;
420 return Ok(SizeSkeleton::Known(Size::from_bytes(size), a));
422 }
423 Err(err)
424 }
425 SizeSkeleton::Pointer { .. } => Err(err),
426 }
427 }
428
429 ty::Adt(def, args) => {
430 if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 {
432 return Err(err);
433 }
434
435 let zero_or_ptr_variant = |i| {
437 let i = VariantIdx::from_usize(i);
438 let fields =
439 def.variant(i).fields.iter().map(|field| {
440 SizeSkeleton::compute(field.ty(tcx, args), tcx, typing_env)
441 });
442 let mut ptr = None;
443 for field in fields {
444 let field = field?;
445 match field {
446 SizeSkeleton::Known(size, align) => {
447 let is_1zst = size.bytes() == 0
448 && align.is_some_and(|align| align.bytes() == 1);
449 if !is_1zst {
450 return Err(err);
451 }
452 }
453 SizeSkeleton::Pointer { .. } => {
454 if ptr.is_some() {
455 return Err(err);
456 }
457 ptr = Some(field);
458 }
459 }
460 }
461 Ok(ptr)
462 };
463
464 let v0 = zero_or_ptr_variant(0)?;
465 if def.variants().len() == 1 {
467 if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
468 return Ok(SizeSkeleton::Pointer {
469 non_zero: non_zero
470 || match tcx.layout_scalar_valid_range(def.did()) {
471 (Bound::Included(start), Bound::Unbounded) => start > 0,
472 (Bound::Included(start), Bound::Included(end)) => {
473 0 < start && start < end
474 }
475 _ => false,
476 },
477 tail,
478 });
479 } else {
480 return Err(err);
481 }
482 }
483
484 let v1 = zero_or_ptr_variant(1)?;
485 match (v0, v1) {
487 (Some(SizeSkeleton::Pointer { non_zero: true, tail }), None)
488 | (None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
489 Ok(SizeSkeleton::Pointer { non_zero: false, tail })
490 }
491 _ => Err(err),
492 }
493 }
494
495 ty::Alias(..) => {
496 let normalized =
497 tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
498 if ty == normalized {
499 Err(err)
500 } else {
501 SizeSkeleton::compute(normalized, tcx, typing_env)
502 }
503 }
504
505 ty::Pat(base, pat) => {
506 let base = SizeSkeleton::compute(base, tcx, typing_env);
508 match *pat {
509 ty::PatternKind::Range { .. } | ty::PatternKind::Or(_) => base,
510 ty::PatternKind::NotNull => match base? {
513 SizeSkeleton::Known(..) => base,
514 SizeSkeleton::Pointer { non_zero: _, tail } => {
515 Ok(SizeSkeleton::Pointer { non_zero: true, tail })
516 }
517 },
518 }
519 }
520
521 _ => Err(err),
522 }
523 }
524
525 pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool {
526 match (self, other) {
527 (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b,
528 (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => {
529 a == b
530 }
531 _ => false,
532 }
533 }
534}
535
536pub trait HasTyCtxt<'tcx>: HasDataLayout {
537 fn tcx(&self) -> TyCtxt<'tcx>;
538}
539
540pub trait HasTypingEnv<'tcx> {
541 fn typing_env(&self) -> ty::TypingEnv<'tcx>;
542
543 fn param_env(&self) -> ty::ParamEnv<'tcx> {
546 self.typing_env().param_env
547 }
548}
549
550impl<'tcx> HasDataLayout for TyCtxt<'tcx> {
551 #[inline]
552 fn data_layout(&self) -> &TargetDataLayout {
553 &self.data_layout
554 }
555}
556
557impl<'tcx> HasTargetSpec for TyCtxt<'tcx> {
558 fn target_spec(&self) -> &Target {
559 &self.sess.target
560 }
561}
562
563impl<'tcx> HasX86AbiOpt for TyCtxt<'tcx> {
564 fn x86_abi_opt(&self) -> X86Abi {
565 X86Abi {
566 regparm: self.sess.opts.unstable_opts.regparm,
567 reg_struct_return: self.sess.opts.unstable_opts.reg_struct_return,
568 }
569 }
570}
571
572impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> {
573 #[inline]
574 fn tcx(&self) -> TyCtxt<'tcx> {
575 *self
576 }
577}
578
579impl<'tcx> HasDataLayout for TyCtxtAt<'tcx> {
580 #[inline]
581 fn data_layout(&self) -> &TargetDataLayout {
582 &self.data_layout
583 }
584}
585
586impl<'tcx> HasTargetSpec for TyCtxtAt<'tcx> {
587 fn target_spec(&self) -> &Target {
588 &self.sess.target
589 }
590}
591
592impl<'tcx> HasTyCtxt<'tcx> for TyCtxtAt<'tcx> {
593 #[inline]
594 fn tcx(&self) -> TyCtxt<'tcx> {
595 **self
596 }
597}
598
599impl<'tcx> HasTypingEnv<'tcx> for LayoutCx<'tcx> {
600 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
601 self.typing_env
602 }
603}
604
605impl<'tcx> HasDataLayout for LayoutCx<'tcx> {
606 fn data_layout(&self) -> &TargetDataLayout {
607 self.calc.cx.data_layout()
608 }
609}
610
611impl<'tcx> HasTargetSpec for LayoutCx<'tcx> {
612 fn target_spec(&self) -> &Target {
613 self.calc.cx.target_spec()
614 }
615}
616
617impl<'tcx> HasX86AbiOpt for LayoutCx<'tcx> {
618 fn x86_abi_opt(&self) -> X86Abi {
619 self.calc.cx.x86_abi_opt()
620 }
621}
622
623impl<'tcx> HasTyCtxt<'tcx> for LayoutCx<'tcx> {
624 fn tcx(&self) -> TyCtxt<'tcx> {
625 self.calc.cx
626 }
627}
628
629pub trait MaybeResult<T> {
630 type Error;
631
632 fn from(x: Result<T, Self::Error>) -> Self;
633 fn to_result(self) -> Result<T, Self::Error>;
634}
635
636impl<T> MaybeResult<T> for T {
637 type Error = !;
638
639 fn from(Ok(x): Result<T, Self::Error>) -> Self {
640 x
641 }
642 fn to_result(self) -> Result<T, Self::Error> {
643 Ok(self)
644 }
645}
646
647impl<T, E> MaybeResult<T> for Result<T, E> {
648 type Error = E;
649
650 fn from(x: Result<T, Self::Error>) -> Self {
651 x
652 }
653 fn to_result(self) -> Result<T, Self::Error> {
654 self
655 }
656}
657
658pub type TyAndLayout<'tcx> = rustc_abi::TyAndLayout<'tcx, Ty<'tcx>>;
659
660pub trait LayoutOfHelpers<'tcx>: HasDataLayout + HasTyCtxt<'tcx> + HasTypingEnv<'tcx> {
663 type LayoutOfResult: MaybeResult<TyAndLayout<'tcx>> = TyAndLayout<'tcx>;
666
667 #[inline]
670 fn layout_tcx_at_span(&self) -> Span {
671 DUMMY_SP
672 }
673
674 fn handle_layout_err(
682 &self,
683 err: LayoutError<'tcx>,
684 span: Span,
685 ty: Ty<'tcx>,
686 ) -> <Self::LayoutOfResult as MaybeResult<TyAndLayout<'tcx>>>::Error;
687}
688
689pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> {
691 #[inline]
694 fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult {
695 self.spanned_layout_of(ty, DUMMY_SP)
696 }
697
698 #[inline]
703 fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult {
704 let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() };
705 let tcx = self.tcx().at(span);
706
707 MaybeResult::from(
708 tcx.layout_of(self.typing_env().as_query_input(ty))
709 .map_err(|err| self.handle_layout_err(*err, span, ty)),
710 )
711 }
712}
713
714impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {}
715
716impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx> {
717 type LayoutOfResult = Result<TyAndLayout<'tcx>, &'tcx LayoutError<'tcx>>;
718
719 #[inline]
720 fn handle_layout_err(
721 &self,
722 err: LayoutError<'tcx>,
723 _: Span,
724 _: Ty<'tcx>,
725 ) -> &'tcx LayoutError<'tcx> {
726 self.tcx().arena.alloc(err)
727 }
728}
729
730impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx>
731where
732 C: HasTyCtxt<'tcx> + HasTypingEnv<'tcx>,
733{
734 fn ty_and_layout_for_variant(
735 this: TyAndLayout<'tcx>,
736 cx: &C,
737 variant_index: VariantIdx,
738 ) -> TyAndLayout<'tcx> {
739 let layout = match this.variants {
740 Variants::Single { index } if index == variant_index => {
742 return this;
743 }
744
745 Variants::Single { .. } | Variants::Empty => {
746 let tcx = cx.tcx();
751 let typing_env = cx.typing_env();
752
753 if let Ok(original_layout) = tcx.layout_of(typing_env.as_query_input(this.ty)) {
755 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);
756 }
757
758 let fields = match this.ty.kind() {
759 ty::Adt(def, _) if def.variants().is_empty() => {
760 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)
761 }
762 ty::Adt(def, _) => def.variant(variant_index).fields.len(),
763 _ => 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),
764 };
765 tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields))
766 }
767
768 Variants::Multiple { ref variants, .. } => {
769 cx.tcx().mk_layout(variants[variant_index].clone())
770 }
771 };
772
773 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 });
774
775 TyAndLayout { ty: this.ty, layout }
776 }
777
778 fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> {
779 enum TyMaybeWithLayout<'tcx> {
780 Ty(Ty<'tcx>),
781 TyAndLayout(TyAndLayout<'tcx>),
782 }
783
784 fn field_ty_or_layout<'tcx>(
785 this: TyAndLayout<'tcx>,
786 cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
787 i: usize,
788 ) -> TyMaybeWithLayout<'tcx> {
789 let tcx = cx.tcx();
790 let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> {
791 TyAndLayout {
792 layout: tcx.mk_layout(LayoutData::scalar(cx, tag)),
793 ty: tag.primitive().to_ty(tcx),
794 }
795 };
796
797 match *this.ty.kind() {
798 ty::Bool
799 | ty::Char
800 | ty::Int(_)
801 | ty::Uint(_)
802 | ty::Float(_)
803 | ty::FnPtr(..)
804 | ty::Never
805 | ty::FnDef(..)
806 | ty::CoroutineWitness(..)
807 | ty::Foreign(..)
808 | ty::Dynamic(_, _) => {
809 crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this)
810 }
811
812 ty::Pat(base, _) => {
813 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);
814 TyMaybeWithLayout::Ty(base)
815 }
816
817 ty::UnsafeBinder(bound_ty) => {
818 let ty = tcx.instantiate_bound_regions_with_erased(bound_ty.into());
819 field_ty_or_layout(TyAndLayout { ty, ..this }, cx, i)
820 }
821
822 ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
824 if !(i < this.fields.count()) {
::core::panicking::panic("assertion failed: i < this.fields.count()")
};assert!(i < this.fields.count());
825
826 if i == 0 {
831 let nil = tcx.types.unit;
832 let unit_ptr_ty = if this.ty.is_raw_ptr() {
833 Ty::new_mut_ptr(tcx, nil)
834 } else {
835 Ty::new_mut_ref(tcx, tcx.lifetimes.re_static, nil)
836 };
837
838 let typing_env = ty::TypingEnv::fully_monomorphized();
842 return TyMaybeWithLayout::TyAndLayout(TyAndLayout {
843 ty: this.ty,
844 ..tcx.layout_of(typing_env.as_query_input(unit_ptr_ty)).unwrap()
845 });
846 }
847
848 let mk_dyn_vtable = |principal: Option<ty::PolyExistentialTraitRef<'tcx>>| {
849 let min_count = ty::vtable_min_entries(
850 tcx,
851 principal.map(|principal| {
852 tcx.instantiate_bound_regions_with_erased(principal)
853 }),
854 );
855 Ty::new_imm_ref(
856 tcx,
857 tcx.lifetimes.re_static,
858 Ty::new_array(tcx, tcx.types.usize, min_count.try_into().unwrap()),
860 )
861 };
862
863 let metadata = if let Some(metadata_def_id) = tcx.lang_items().metadata_type()
864 && !pointee.references_error()
867 {
868 let metadata = tcx.normalize_erasing_regions(
869 cx.typing_env(),
870 Unnormalized::new(Ty::new_projection(tcx, metadata_def_id, [pointee])),
871 );
872
873 if let ty::Adt(def, args) = metadata.kind()
878 && tcx.is_lang_item(def.did(), LangItem::DynMetadata)
879 && let ty::Dynamic(data, _) = args.type_at(0).kind()
880 {
881 mk_dyn_vtable(data.principal())
882 } else {
883 metadata
884 }
885 } else {
886 match tcx.struct_tail_for_codegen(pointee, cx.typing_env()).kind() {
887 ty::Slice(_) | ty::Str => tcx.types.usize,
888 ty::Dynamic(data, _) => mk_dyn_vtable(data.principal()),
889 _ => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field({0:?}): not applicable",
this))bug!("TyAndLayout::field({:?}): not applicable", this),
890 }
891 };
892
893 TyMaybeWithLayout::Ty(metadata)
894 }
895
896 ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element),
898 ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8),
899
900 ty::Closure(_, args) => field_ty_or_layout(
902 TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this },
903 cx,
904 i,
905 ),
906
907 ty::CoroutineClosure(_, args) => field_ty_or_layout(
908 TyAndLayout { ty: args.as_coroutine_closure().tupled_upvars_ty(), ..this },
909 cx,
910 i,
911 ),
912
913 ty::Coroutine(def_id, args) => match this.variants {
914 Variants::Empty => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
915 Variants::Single { index } => TyMaybeWithLayout::Ty(
916 args.as_coroutine()
917 .state_tys(def_id, tcx)
918 .nth(index.as_usize())
919 .unwrap()
920 .nth(i)
921 .unwrap(),
922 ),
923 Variants::Multiple { tag, tag_field, .. } => {
924 if FieldIdx::from_usize(i) == tag_field {
925 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
926 }
927 TyMaybeWithLayout::Ty(args.as_coroutine().prefix_tys()[i])
928 }
929 },
930
931 ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]),
932
933 ty::Adt(def, args) => {
935 match this.variants {
936 Variants::Single { index } => {
937 let field = &def.variant(index).fields[FieldIdx::from_usize(i)];
938 TyMaybeWithLayout::Ty(field.ty(tcx, args))
939 }
940 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"),
941
942 Variants::Multiple { tag, .. } => {
944 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);
945 return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
946 }
947 }
948 }
949
950 ty::Alias(..)
951 | ty::Bound(..)
952 | ty::Placeholder(..)
953 | ty::Param(_)
954 | ty::Infer(_)
955 | ty::Error(_) => crate::util::bug::bug_fmt(format_args!("TyAndLayout::field: unexpected type `{0}`",
this.ty))bug!("TyAndLayout::field: unexpected type `{}`", this.ty),
956 }
957 }
958
959 match field_ty_or_layout(this, cx, i) {
960 TyMaybeWithLayout::Ty(field_ty) => {
961 cx.tcx().layout_of(cx.typing_env().as_query_input(field_ty)).unwrap_or_else(|e| {
962 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!(
963 "failed to get layout for `{field_ty}`: {e:?},\n\
964 despite it being a field (#{i}) of an existing layout: {this:#?}",
965 )
966 })
967 }
968 TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout,
969 }
970 }
971
972 fn ty_and_layout_pointee_info_at(
975 this: TyAndLayout<'tcx>,
976 cx: &C,
977 offset: Size,
978 ) -> Option<PointeeInfo> {
979 let tcx = cx.tcx();
980 let typing_env = cx.typing_env();
981
982 let optimize = tcx.sess.opts.optimize != OptLevel::No;
986
987 let pointee_info = match *this.ty.kind() {
988 ty::RawPtr(_, _) | ty::FnPtr(..) if offset.bytes() == 0 => {
989 Some(PointeeInfo { safe: None, size: Size::ZERO, align: Align::ONE })
990 }
991 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
992 tcx.layout_of(typing_env.as_query_input(ty)).ok().map(|layout| {
993 let (size, kind);
994 match mt {
995 hir::Mutability::Not => {
996 let frozen = optimize && ty.is_freeze(tcx, typing_env);
997
998 size = if frozen { layout.size } else { Size::ZERO };
1002
1003 kind = PointerKind::SharedRef { frozen };
1004 }
1005 hir::Mutability::Mut => {
1006 let unpin = optimize
1007 && ty.is_unpin(tcx, typing_env)
1008 && ty.is_unsafe_unpin(tcx, typing_env);
1009
1010 size = if unpin { layout.size } else { Size::ZERO };
1015
1016 kind = PointerKind::MutableRef { unpin };
1017 }
1018 };
1019 PointeeInfo { safe: Some(kind), size, align: layout.align.abi }
1020 })
1021 }
1022
1023 ty::Adt(..)
1024 if offset.bytes() == 0
1025 && let Some(pointee) = this.ty.boxed_ty() =>
1026 {
1027 tcx.layout_of(typing_env.as_query_input(pointee)).ok().map(|layout| PointeeInfo {
1028 safe: Some(PointerKind::Box {
1029 unpin: optimize
1031 && pointee.is_unpin(tcx, typing_env)
1032 && pointee.is_unsafe_unpin(tcx, typing_env),
1033 global: this.ty.is_box_global(tcx),
1034 }),
1035
1036 size: Size::ZERO,
1040
1041 align: layout.align.abi,
1042 })
1043 }
1044
1045 ty::Adt(adt_def, ..) if adt_def.is_maybe_dangling() => {
1046 Self::ty_and_layout_pointee_info_at(this.field(cx, 0), cx, offset).map(|info| {
1047 PointeeInfo {
1048 safe: None,
1051 size: Size::ZERO,
1053 align: info.align,
1055 }
1056 })
1057 }
1058
1059 _ => {
1060 let mut data_variant = match &this.variants {
1061 Variants::Multiple {
1071 tag_encoding:
1072 TagEncoding::Niche { untagged_variant, niche_variants, niche_start },
1073 tag_field,
1074 variants,
1075 ..
1076 } if variants.len() == 2
1077 && this.fields.offset(tag_field.as_usize()) == offset =>
1078 {
1079 let tagged_variant = if *untagged_variant == VariantIdx::ZERO {
1080 VariantIdx::from_u32(1)
1081 } else {
1082 VariantIdx::from_u32(0)
1083 };
1084 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());
1085 if *niche_start == 0 {
1086 Some(this.for_variant(cx, *untagged_variant))
1092 } else {
1093 None
1094 }
1095 }
1096 Variants::Multiple { .. } => None,
1097 Variants::Empty | Variants::Single { .. } => Some(this),
1098 };
1099
1100 if let Some(variant) = data_variant
1101 && let FieldsShape::Union(_) = variant.fields
1103 {
1104 data_variant = None;
1105 }
1106
1107 let mut result = None;
1108
1109 if let Some(variant) = data_variant {
1110 let ptr_end = offset + Primitive::Pointer(AddressSpace::ZERO).size(cx);
1113 for i in 0..variant.fields.count() {
1114 let field_start = variant.fields.offset(i);
1115 if field_start <= offset {
1116 let field = variant.field(cx, i);
1117 result = field.to_result().ok().and_then(|field| {
1118 if ptr_end <= field_start + field.size {
1119 let field_info =
1121 field.pointee_info_at(cx, offset - field_start);
1122 field_info
1123 } else {
1124 None
1125 }
1126 });
1127 if result.is_some() {
1128 break;
1129 }
1130 }
1131 }
1132 }
1133
1134 result
1135 }
1136 };
1137
1138 {
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:1138",
"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(1138u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("pointee_info_at (offset={0:?}, type kind: {1:?}) => {2:?}",
offset, this.ty.kind(), pointee_info) as &dyn Value))])
});
} else { ; }
};debug!(
1139 "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}",
1140 offset,
1141 this.ty.kind(),
1142 pointee_info
1143 );
1144
1145 pointee_info
1146 }
1147
1148 fn is_adt(this: TyAndLayout<'tcx>) -> bool {
1149 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Adt(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Adt(..))
1150 }
1151
1152 fn is_never(this: TyAndLayout<'tcx>) -> bool {
1153 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Never => true,
_ => false,
}matches!(this.ty.kind(), ty::Never)
1154 }
1155
1156 fn is_tuple(this: TyAndLayout<'tcx>) -> bool {
1157 #[allow(non_exhaustive_omitted_patterns)] match this.ty.kind() {
ty::Tuple(..) => true,
_ => false,
}matches!(this.ty.kind(), ty::Tuple(..))
1158 }
1159
1160 fn is_unit(this: TyAndLayout<'tcx>) -> bool {
1161 #[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)
1162 }
1163
1164 fn is_transparent(this: TyAndLayout<'tcx>) -> bool {
1165 #[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())
1166 }
1167
1168 fn is_scalable_vector(this: TyAndLayout<'tcx>) -> bool {
1169 this.ty.is_scalable_vector()
1170 }
1171
1172 fn is_pass_indirectly_in_non_rustic_abis_flag_set(this: TyAndLayout<'tcx>) -> bool {
1174 #[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))
1175 }
1176}
1177
1178#[inline]
1219#[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(1219u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&["fn_def_id", "abi"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&abi)
as &dyn 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::DropInPlace) {
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 | Unadjusted
=> false,
Rust | RustCall | RustCold | RustPreserveNone =>
tcx.sess.panic_strategy().unwinds(),
}
}
}
}#[tracing::instrument(level = "debug", skip(tcx))]
1220pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: ExternAbi) -> bool {
1221 if let Some(did) = fn_def_id {
1222 if tcx.codegen_fn_attrs(did).flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) {
1224 return false;
1225 }
1226
1227 if !tcx.sess.panic_strategy().unwinds() && !tcx.is_foreign_item(did) {
1232 return false;
1233 }
1234
1235 if !tcx.sess.opts.unstable_opts.panic_in_drop.unwinds()
1240 && tcx.is_lang_item(did, LangItem::DropInPlace)
1241 {
1242 return false;
1243 }
1244 }
1245
1246 use ExternAbi::*;
1253 match abi {
1254 C { unwind }
1255 | System { unwind }
1256 | Cdecl { unwind }
1257 | Stdcall { unwind }
1258 | Fastcall { unwind }
1259 | Vectorcall { unwind }
1260 | Thiscall { unwind }
1261 | Aapcs { unwind }
1262 | Win64 { unwind }
1263 | SysV64 { unwind } => unwind,
1264 PtxKernel
1265 | Msp430Interrupt
1266 | X86Interrupt
1267 | GpuKernel
1268 | EfiApi
1269 | AvrInterrupt
1270 | AvrNonBlockingInterrupt
1271 | CmseNonSecureCall
1272 | CmseNonSecureEntry
1273 | Custom
1274 | RiscvInterruptM
1275 | RiscvInterruptS
1276 | RustInvalid
1277 | Unadjusted => false,
1278 Rust | RustCall | RustCold | RustPreserveNone => tcx.sess.panic_strategy().unwinds(),
1279 }
1280}
1281
1282#[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, '__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
for FnAbiError<'tcx> {
#[inline]
fn hash_stable(&self,
__hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
match *self {
FnAbiError::Layout(ref __binding_0) => {
{ __binding_0.hash_stable(__hcx, __hasher); }
}
}
}
}
};HashStable)]
1284pub enum FnAbiError<'tcx> {
1285 Layout(LayoutError<'tcx>),
1287}
1288
1289impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1290 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
1291 match self {
1292 Self::Layout(e) => Diag::new(dcx, level, e.to_string()),
1293 }
1294 }
1295}
1296
1297#[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)]
1300pub enum FnAbiRequest<'tcx> {
1301 OfFnPtr { sig: ty::PolyFnSig<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1302 OfInstance { instance: ty::Instance<'tcx>, extra_args: &'tcx ty::List<Ty<'tcx>> },
1303}
1304
1305pub trait FnAbiOfHelpers<'tcx>: LayoutOfHelpers<'tcx> {
1308 type FnAbiOfResult: MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>> = &'tcx FnAbi<'tcx, Ty<'tcx>>;
1311
1312 fn handle_fn_abi_err(
1320 &self,
1321 err: FnAbiError<'tcx>,
1322 span: Span,
1323 fn_abi_request: FnAbiRequest<'tcx>,
1324 ) -> <Self::FnAbiOfResult as MaybeResult<&'tcx FnAbi<'tcx, Ty<'tcx>>>>::Error;
1325}
1326
1327pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> {
1329 #[inline]
1334 fn fn_abi_of_fn_ptr(
1335 &self,
1336 sig: ty::PolyFnSig<'tcx>,
1337 extra_args: &'tcx ty::List<Ty<'tcx>>,
1338 ) -> Self::FnAbiOfResult {
1339 let span = self.layout_tcx_at_span();
1341 let tcx = self.tcx().at(span);
1342
1343 MaybeResult::from(
1344 tcx.fn_abi_of_fn_ptr(self.typing_env().as_query_input((sig, extra_args))).map_err(
1345 |err| self.handle_fn_abi_err(*err, span, FnAbiRequest::OfFnPtr { sig, extra_args }),
1346 ),
1347 )
1348 }
1349
1350 #[inline]
1362 #[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(1362u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&["instance",
"extra_args"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
as &dyn 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))]
1363 fn fn_abi_of_instance_no_deduced_attrs(
1364 &self,
1365 instance: ty::Instance<'tcx>,
1366 extra_args: &'tcx ty::List<Ty<'tcx>>,
1367 ) -> Self::FnAbiOfResult {
1368 let span = self.layout_tcx_at_span();
1370 let tcx = self.tcx().at(span);
1371
1372 MaybeResult::from(
1373 tcx.fn_abi_of_instance_no_deduced_attrs(
1374 self.typing_env().as_query_input((instance, extra_args)),
1375 )
1376 .map_err(|err| {
1377 let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1382 self.handle_fn_abi_err(
1383 *err,
1384 span,
1385 FnAbiRequest::OfInstance { instance, extra_args },
1386 )
1387 }),
1388 )
1389 }
1390
1391 #[inline]
1401 #[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(1401u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::layout"),
::tracing_core::field::FieldSet::new(&["instance",
"extra_args"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&extra_args)
as &dyn 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))]
1402 fn fn_abi_of_instance(
1403 &self,
1404 instance: ty::Instance<'tcx>,
1405 extra_args: &'tcx ty::List<Ty<'tcx>>,
1406 ) -> Self::FnAbiOfResult {
1407 let span = self.layout_tcx_at_span();
1409 let tcx = self.tcx().at(span);
1410
1411 MaybeResult::from(
1412 tcx.fn_abi_of_instance(self.typing_env().as_query_input((instance, extra_args)))
1413 .map_err(|err| {
1414 let span =
1419 if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) };
1420 self.handle_fn_abi_err(
1421 *err,
1422 span,
1423 FnAbiRequest::OfInstance { instance, extra_args },
1424 )
1425 }),
1426 )
1427 }
1428}
1429
1430impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {}