Skip to main content

rustc_sanitizers/cfi/typeid/itanium_cxx_abi/
encode.rs

1//! Encodes type metadata identifiers for LLVM CFI and cross-language LLVM CFI support using Itanium
2//! C++ ABI mangling for encoding with vendor extended type qualifiers and types for Rust types that
3//! are not used across the FFI boundary.
4//!
5//! For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler,
6//! see design document in the tracking issue #89653.
7
8use std::fmt::Write as _;
9
10use rustc_abi::{ExternAbi, Integer};
11use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, CASE_INSENSITIVE, ToBaseN};
12use rustc_data_structures::fx::FxHashMap;
13use rustc_hir as hir;
14use rustc_hir::find_attr;
15use rustc_middle::bug;
16use rustc_middle::ty::layout::IntegerExt;
17use rustc_middle::ty::{
18    self, Const, ExistentialPredicate, FloatTy, FnSig, GenericArg, GenericArgKind, GenericArgsRef,
19    IntTy, List, Region, RegionKind, TermKind, Ty, TyCtxt, TypeFoldable, UintTy,
20};
21use rustc_span::def_id::DefId;
22use tracing::instrument;
23
24use crate::cfi::typeid::TypeIdOptions;
25use crate::cfi::typeid::itanium_cxx_abi::transform::{TransformTy, TransformTyOptions};
26
27/// Options for encode_ty.
28pub(crate) type EncodeTyOptions = TypeIdOptions;
29
30/// Substitution dictionary key.
31#[derive(#[automatically_derived]
impl<'tcx> ::core::cmp::Eq for DictKey<'tcx> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Ty<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<TyQ>;
        let _: ::core::cmp::AssertParamIsEq<Region<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<Const<'tcx>>;
        let _: ::core::cmp::AssertParamIsEq<ExistentialPredicate<'tcx>>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for DictKey<'tcx> {
    #[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);
        match self {
            DictKey::Ty(__self_0, __self_1) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state)
            }
            DictKey::Region(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            DictKey::Const(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            DictKey::Predicate(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for DictKey<'tcx> {
    #[inline]
    fn eq(&self, other: &DictKey<'tcx>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (DictKey::Ty(__self_0, __self_1),
                    DictKey::Ty(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (DictKey::Region(__self_0), DictKey::Region(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (DictKey::Const(__self_0), DictKey::Const(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (DictKey::Predicate(__self_0), DictKey::Predicate(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
32pub(crate) enum DictKey<'tcx> {
33    Ty(Ty<'tcx>, TyQ),
34    Region(Region<'tcx>),
35    Const(Const<'tcx>),
36    Predicate(ExistentialPredicate<'tcx>),
37}
38
39/// Type and extended type qualifiers.
40#[derive(#[automatically_derived]
impl ::core::cmp::Eq for TyQ {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for TyQ {
    #[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, #[automatically_derived]
impl ::core::cmp::PartialEq for TyQ {
    #[inline]
    fn eq(&self, other: &TyQ) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
41pub(crate) enum TyQ {
42    None,
43    Const,
44    Mut,
45}
46
47/// Substitutes a component if found in the substitution dictionary (see
48/// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-compression>).
49fn compress<'tcx>(
50    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
51    key: DictKey<'tcx>,
52    comp: &mut String,
53) {
54    match dict.get(&key) {
55        Some(num) => {
56            comp.clear();
57            let _ = comp.write_fmt(format_args!("S{0}_", to_seq_id(*num)))write!(comp, "S{}_", to_seq_id(*num));
58        }
59        None => {
60            dict.insert(key, dict.len());
61        }
62    }
63}
64
65/// Encodes args using the Itanium C++ ABI with vendor extended type qualifiers and types for Rust
66/// types that are not used at the FFI boundary.
67fn encode_args<'tcx>(
68    tcx: TyCtxt<'tcx>,
69    args: GenericArgsRef<'tcx>,
70    for_def: DefId,
71    has_erased_self: bool,
72    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
73    options: EncodeTyOptions,
74) -> String {
75    // [I<subst1..substN>E] as part of vendor extended type
76    let mut s = String::new();
77    let args: Vec<GenericArg<'_>> = args.iter().collect();
78    if !args.is_empty() {
79        s.push('I');
80        let def_generics = tcx.generics_of(for_def);
81        for (n, arg) in args.iter().enumerate() {
82            match arg.kind() {
83                GenericArgKind::Lifetime(region) => {
84                    s.push_str(&encode_region(region, dict));
85                }
86                GenericArgKind::Type(ty) => {
87                    s.push_str(&encode_ty(tcx, ty, dict, options));
88                }
89                GenericArgKind::Const(c) => {
90                    let n = n + (has_erased_self as usize);
91                    let ct_ty = tcx
92                        .type_of(def_generics.param_at(n, tcx).def_id)
93                        .instantiate_identity()
94                        .skip_norm_wip();
95                    s.push_str(&encode_const(tcx, c, ct_ty, dict, options));
96                }
97            }
98        }
99        s.push('E');
100    }
101    s
102}
103
104/// Encodes a const using the Itanium C++ ABI as a literal argument (see
105/// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.literal>).
106fn encode_const<'tcx>(
107    tcx: TyCtxt<'tcx>,
108    ct: Const<'tcx>,
109    ct_ty: Ty<'tcx>,
110    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
111    options: EncodeTyOptions,
112) -> String {
113    // L<element-type>[n][<element-value>]E as literal argument
114    let mut s = String::from('L');
115
116    match ct.kind() {
117        // Const parameters
118        ty::ConstKind::Param(..) => {
119            // L<element-type>E as literal argument
120
121            // Element type
122            s.push_str(&encode_ty(tcx, ct_ty, dict, options));
123        }
124
125        // Literal arguments
126        ty::ConstKind::Value(cv) => {
127            // L<element-type>[n]<element-value>E as literal argument
128
129            // Element type
130            s.push_str(&encode_ty(tcx, cv.ty, dict, options));
131
132            // Element value
133            s.push_str(&encode_const_value(tcx, cv, dict, options));
134        }
135
136        _ => {
137            ::rustc_middle::util::bug::bug_fmt(format_args!("encode_const: unexpected kind `{0:?}`",
        ct.kind()));bug!("encode_const: unexpected kind `{:?}`", ct.kind());
138        }
139    }
140
141    // Close the "L..E" pair
142    s.push('E');
143
144    compress(dict, DictKey::Const(ct), &mut s);
145
146    s
147}
148
149/// Encodes a const value using the Itanium C++ ABI as the element value of a literal argument (see
150/// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.literal>).
151fn encode_const_value<'tcx>(
152    tcx: TyCtxt<'tcx>,
153    cv: ty::Value<'tcx>,
154    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
155    options: EncodeTyOptions,
156) -> String {
157    let mut s = String::new();
158
159    match cv.ty.kind() {
160        // Primitive types
161
162        // The bool value false is encoded as 0 and true as 1.
163        ty::Bool => {
164            let val = cv.try_to_bool().expect("expected monomorphic const in cfi");
165            s.push(if val { '1' } else { '0' });
166        }
167
168        // Integer values are encoded as their decimal values, with negative values preceded by n.
169        ty::Int(ity) => {
170            let bits = cv
171                .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
172                .expect("expected monomorphic const in cfi");
173            let val = Integer::from_int_ty(&tcx, *ity).size().sign_extend(bits) as i128;
174            if val < 0 {
175                s.push('n');
176            }
177            let _ = s.write_fmt(format_args!("{0}", val.unsigned_abs()))write!(s, "{}", val.unsigned_abs());
178        }
179
180        ty::Uint(..) => {
181            let val = cv
182                .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
183                .expect("expected monomorphic const in cfi");
184            let _ = s.write_fmt(format_args!("{0}", val))write!(s, "{val}");
185        }
186
187        // char values are encoded as their Unicode scalar values (i.e., as their decimal u32
188        // values).
189        ty::Char => {
190            let val = cv
191                .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
192                .expect("expected monomorphic const in cfi");
193            let _ = s.write_fmt(format_args!("{0}", val))write!(s, "{val}");
194        }
195
196        // str values are encoded as their UTF-8 encodings in hexadecimal.
197        ty::Str => {
198            // Hide the str type behind a reference for try_to_raw_bytes (i.e., the valtree of a
199            // str value is the valtree of its reference).
200            let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, cv.ty);
201            let cv = ty::Value { ty: ref_ty, valtree: cv.valtree };
202            let bytes = cv.try_to_raw_bytes(tcx).expect("expected monomorphic const in cfi");
203            for byte in bytes {
204                let _ = s.write_fmt(format_args!("{0:02x}", byte))write!(s, "{byte:02x}");
205            }
206        }
207
208        // Sequence types
209        // Array, slice, and tuple values are encoded as their element values as literal arguments.
210        ty::Array(..) | ty::Slice(..) | ty::Tuple(..) => {
211            for field in cv.to_branch() {
212                let ty::ConstKind::Value(field_cv) = field.kind() else {
213                    ::rustc_middle::util::bug::bug_fmt(format_args!("encode_const_value: unexpected kind `{0:?}`",
        field.kind()));bug!("encode_const_value: unexpected kind `{:?}`", field.kind());
214                };
215                s.push_str(&encode_const(tcx, *field, field_cv.ty, dict, options));
216            }
217        }
218
219        // User-defined types
220        // Struct and enum values are encoded as their field values as literal arguments, preceded
221        // by V<variant-index> for enum values.
222        ty::Adt(adt_def, ..) => {
223            let contents = cv.destructure_adt_const();
224            if adt_def.is_enum() {
225                let _ = s.write_fmt(format_args!("V{0}", contents.variant.as_u32()))write!(s, "V{}", contents.variant.as_u32());
226            }
227            for field in contents.fields {
228                let ty::ConstKind::Value(field_cv) = field.kind() else {
229                    ::rustc_middle::util::bug::bug_fmt(format_args!("encode_const_value: unexpected kind `{0:?}`",
        field.kind()));bug!("encode_const_value: unexpected kind `{:?}`", field.kind());
230                };
231                s.push_str(&encode_const(tcx, *field, field_cv.ty, dict, options));
232            }
233        }
234
235        // Pointer types
236        // Reference values are encoded as the values of their referents (i.e., the valtree of a
237        // reference value is the valtree of its referent).
238        ty::Ref(_, ty0, ..) => {
239            let cv = ty::Value { ty: *ty0, valtree: cv.valtree };
240            s.push_str(&encode_const_value(tcx, cv, dict, options));
241        }
242
243        // Unexpected types
244        ty::Float(..)
245        | ty::Never
246        | ty::Foreign(..)
247        | ty::Pat(..)
248        | ty::FnDef(..)
249        | ty::FnPtr(..)
250        | ty::RawPtr(..)
251        | ty::Closure(..)
252        | ty::CoroutineClosure(..)
253        | ty::Coroutine(..)
254        | ty::CoroutineWitness(..)
255        | ty::Dynamic(..)
256        | ty::UnsafeBinder(..)
257        | ty::Param(..)
258        | ty::Alias(..)
259        | ty::Bound(..)
260        | ty::Error(..)
261        | ty::Infer(..)
262        | ty::Placeholder(..) => {
263            ::rustc_middle::util::bug::bug_fmt(format_args!("encode_const_value: unexpected type `{0:?}`",
        cv.ty));bug!("encode_const_value: unexpected type `{:?}`", cv.ty);
264        }
265    }
266
267    s
268}
269
270/// Encodes a FnSig using the Itanium C++ ABI with vendor extended type qualifiers and types for
271/// Rust types that are not used at the FFI boundary.
272fn encode_fnsig<'tcx>(
273    tcx: TyCtxt<'tcx>,
274    fn_sig: &FnSig<'tcx>,
275    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
276    options: TypeIdOptions,
277) -> String {
278    // Function types are delimited by an "F..E" pair
279    let mut s = String::from("F");
280
281    let mut encode_ty_options = EncodeTyOptions::from_bits(options.bits())
282        .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("encode_fnsig: invalid option(s) `{0:?}`",
        options.bits()))bug!("encode_fnsig: invalid option(s) `{:?}`", options.bits()));
283    match fn_sig.abi() {
284        ExternAbi::C { .. } => {
285            encode_ty_options.insert(EncodeTyOptions::GENERALIZE_REPR_C);
286        }
287        _ => {
288            encode_ty_options.remove(EncodeTyOptions::GENERALIZE_REPR_C);
289        }
290    }
291
292    // Encode the return type
293    let transform_ty_options = TransformTyOptions::from_bits(options.bits())
294        .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("encode_fnsig: invalid option(s) `{0:?}`",
        options.bits()))bug!("encode_fnsig: invalid option(s) `{:?}`", options.bits()));
295    let mut type_folder = TransformTy::new(tcx, transform_ty_options);
296    let ty = fn_sig.output().fold_with(&mut type_folder);
297    s.push_str(&encode_ty(tcx, ty, dict, encode_ty_options));
298
299    // Encode the parameter types
300    let tys = fn_sig.inputs();
301    if !tys.is_empty() {
302        for ty in tys {
303            let ty = ty.fold_with(&mut type_folder);
304            s.push_str(&encode_ty(tcx, ty, dict, encode_ty_options));
305        }
306
307        if fn_sig.c_variadic() {
308            s.push('z');
309        }
310    } else if fn_sig.c_variadic() {
311        s.push('z');
312    } else {
313        // Empty parameter lists, whether declared as () or conventionally as (void), are
314        // encoded with a void parameter specifier "v".
315        s.push('v')
316    }
317
318    // Close the "F..E" pair
319    s.push('E');
320
321    s
322}
323
324/// Encodes a predicate using the Itanium C++ ABI with vendor extended type qualifiers and types for
325/// Rust types that are not used at the FFI boundary.
326fn encode_predicate<'tcx>(
327    tcx: TyCtxt<'tcx>,
328    predicate: ty::PolyExistentialPredicate<'tcx>,
329    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
330    options: EncodeTyOptions,
331) -> String {
332    // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>, as vendor
333    // extended type.
334    let mut s = String::new();
335    match predicate.as_ref().skip_binder() {
336        ty::ExistentialPredicate::Trait(trait_ref) => {
337            let name = encode_ty_name(tcx, trait_ref.def_id);
338            let _ = s.write_fmt(format_args!("u{0}{1}", name.len(), name))write!(s, "u{}{}", name.len(), name);
339            s.push_str(&encode_args(tcx, trait_ref.args, trait_ref.def_id, true, dict, options));
340        }
341        ty::ExistentialPredicate::Projection(projection) => {
342            let name = encode_ty_name(tcx, projection.def_id);
343            let _ = s.write_fmt(format_args!("u{0}{1}", name.len(), name))write!(s, "u{}{}", name.len(), name);
344            s.push_str(&encode_args(tcx, projection.args, projection.def_id, true, dict, options));
345            match projection.term.kind() {
346                TermKind::Ty(ty) => s.push_str(&encode_ty(tcx, ty, dict, options)),
347                TermKind::Const(c) => s.push_str(&encode_const(
348                    tcx,
349                    c,
350                    tcx.type_of(projection.def_id)
351                        .instantiate(tcx, projection.args)
352                        .skip_norm_wip(),
353                    dict,
354                    options,
355                )),
356            }
357        }
358        ty::ExistentialPredicate::AutoTrait(def_id) => {
359            let name = encode_ty_name(tcx, *def_id);
360            let _ = s.write_fmt(format_args!("u{0}{1}", name.len(), name))write!(s, "u{}{}", name.len(), name);
361        }
362    };
363    compress(dict, DictKey::Predicate(*predicate.as_ref().skip_binder()), &mut s);
364    s
365}
366
367/// Encodes predicates using the Itanium C++ ABI with vendor extended type qualifiers and types for
368/// Rust types that are not used at the FFI boundary.
369fn encode_predicates<'tcx>(
370    tcx: TyCtxt<'tcx>,
371    predicates: &List<ty::PolyExistentialPredicate<'tcx>>,
372    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
373    options: EncodeTyOptions,
374) -> String {
375    // <predicate1[..predicateN]>E as part of vendor extended type
376    let mut s = String::new();
377    let predicates: Vec<ty::PolyExistentialPredicate<'tcx>> = predicates.iter().collect();
378    for predicate in predicates {
379        s.push_str(&encode_predicate(tcx, predicate, dict, options));
380    }
381    s
382}
383
384/// Encodes a region using the Itanium C++ ABI as a vendor extended type.
385fn encode_region<'tcx>(region: Region<'tcx>, dict: &mut FxHashMap<DictKey<'tcx>, usize>) -> String {
386    // u6region[I[<region-disambiguator>][<region-index>]E] as vendor extended type
387    let mut s = String::new();
388    match region.kind() {
389        RegionKind::ReBound(ty::BoundVarIndexKind::Bound(debruijn), r) => {
390            s.push_str("u6regionI");
391            // Debruijn index, which identifies the binder, as region disambiguator
392            let num = debruijn.index() as u64;
393            if num > 0 {
394                s.push_str(&to_disambiguator(num));
395            }
396            // Index within the binder
397            let _ = s.write_fmt(format_args!("{0}", r.var.index() as u64))write!(s, "{}", r.var.index() as u64);
398            s.push('E');
399            compress(dict, DictKey::Region(region), &mut s);
400        }
401        RegionKind::ReErased => {
402            s.push_str("u6region");
403            compress(dict, DictKey::Region(region), &mut s);
404        }
405        RegionKind::ReBound(ty::BoundVarIndexKind::Canonical, _)
406        | RegionKind::ReEarlyParam(..)
407        | RegionKind::ReLateParam(..)
408        | RegionKind::ReStatic
409        | RegionKind::ReError(_)
410        | RegionKind::ReVar(..)
411        | RegionKind::RePlaceholder(..) => {
412            ::rustc_middle::util::bug::bug_fmt(format_args!("encode_region: unexpected `{0:?}`",
        region.kind()));bug!("encode_region: unexpected `{:?}`", region.kind());
413        }
414    }
415    s
416}
417
418/// Encodes a ty:Ty using the Itanium C++ ABI with vendor extended type qualifiers and types for
419/// Rust types that are not used at the FFI boundary.
420#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_ty",
                                    "rustc_sanitizers::cfi::typeid::itanium_cxx_abi::encode",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs"),
                                    ::tracing_core::__macro_support::Option::Some(420u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_sanitizers::cfi::typeid::itanium_cxx_abi::encode"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("options")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("options");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&options)
                                                            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: String = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut typeid = String::new();
            match ty.kind() {
                ty::Bool => { typeid.push('b'); }
                ty::Int(..) | ty::Uint(..) => {
                    let mut s =
                        String::from(match ty.kind() {
                                ty::Int(IntTy::I8) => "u2i8",
                                ty::Int(IntTy::I16) => "u3i16",
                                ty::Int(IntTy::I32) => "u3i32",
                                ty::Int(IntTy::I64) => "u3i64",
                                ty::Int(IntTy::I128) => "u4i128",
                                ty::Int(IntTy::Isize) => "u5isize",
                                ty::Uint(UintTy::U8) => "u2u8",
                                ty::Uint(UintTy::U16) => "u3u16",
                                ty::Uint(UintTy::U32) => "u3u32",
                                ty::Uint(UintTy::U64) => "u3u64",
                                ty::Uint(UintTy::U128) => "u4u128",
                                ty::Uint(UintTy::Usize) => "u5usize",
                                _ =>
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("encode_ty: unexpected `{0:?}`",
                                            ty.kind())),
                            });
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Float(float_ty) => {
                    typeid.push_str(match float_ty {
                            FloatTy::F16 => "Dh",
                            FloatTy::F32 => "f",
                            FloatTy::F64 => "d",
                            FloatTy::F128 => "g",
                        });
                }
                ty::Char => {
                    let mut s = String::from("u4char");
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Str => {
                    let mut s = String::from("u3str");
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Never => {
                    let mut s = String::from("u5never");
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                _ if ty.is_unit() => { typeid.push('v'); }
                ty::Tuple(tys) => {
                    let mut s = String::from("u5tupleI");
                    for ty in tys.iter() {
                        s.push_str(&encode_ty(tcx, ty, dict, options));
                    }
                    s.push('E');
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Array(ty0, len) => {
                    let len =
                        len.try_to_target_usize(tcx).expect("expected monomorphic const in cfi");
                    let mut s = String::from("A");
                    let _ = s.write_fmt(format_args!("{0}", len));
                    s.push_str(&encode_ty(tcx, *ty0, dict, options));
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Pat(ty0, pat) => {
                    let mut s = String::from("u3patI");
                    s.push_str(&encode_ty(tcx, *ty0, dict, options));
                    s.write_fmt(format_args!("{0:?}", **pat)).unwrap();
                    s.push('E');
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Slice(ty0) => {
                    let mut s = String::from("u5sliceI");
                    s.push_str(&encode_ty(tcx, *ty0, dict, options));
                    s.push('E');
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Adt(adt_def, args) => {
                    let mut s = String::new();
                    let def_id = adt_def.did();
                    if let Some(encoding) =
                            {
                                {
                                    'done:
                                        {
                                        for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx)
                                            {
                                            #[allow(unused_imports)]
                                            use ::rustc_attr_ir::AttributeKind::*;
                                            let i: &::rustc_attr_ir::Attribute = i;
                                            match i {
                                                ::rustc_attr_ir::Attribute::Parsed(CfiEncoding { encoding })
                                                    => {
                                                    break 'done Some(encoding);
                                                }
                                                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                    {}
                                                    #[deny(unreachable_patterns)]
                                                    _ => {}
                                            }
                                        }
                                        None
                                    }
                                }
                            } {
                        let encoding = encoding.as_str().trim();
                        s.push_str(&encoding);
                        let builtin_types =
                            ["v", "w", "b", "c", "a", "h", "s", "t", "i", "j", "l", "m",
                                    "x", "y", "n", "o", "f", "d", "e", "g", "z", "Dh"];
                        if !builtin_types.contains(&encoding) {
                            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                        }
                    } else if options.contains(EncodeTyOptions::GENERALIZE_REPR_C)
                            && adt_def.repr().c() {
                        let name = tcx.item_name(def_id).to_string();
                        let _ =
                            s.write_fmt(format_args!("{0}{1}", name.len(), name));
                        compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    } else {
                        let name = encode_ty_name(tcx, def_id);
                        let _ =
                            s.write_fmt(format_args!("u{0}{1}", name.len(), name));
                        s.push_str(&encode_args(tcx, args, def_id, false, dict,
                                    options));
                        compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    }
                    typeid.push_str(&s);
                }
                ty::Foreign(def_id) => {
                    let mut s = String::new();
                    if let Some(encoding) =
                            {
                                {
                                    'done:
                                        {
                                        for i in ::rustc_attr_ir::HasAttrs::get_attrs(*def_id, &tcx)
                                            {
                                            #[allow(unused_imports)]
                                            use ::rustc_attr_ir::AttributeKind::*;
                                            let i: &::rustc_attr_ir::Attribute = i;
                                            match i {
                                                ::rustc_attr_ir::Attribute::Parsed(CfiEncoding { encoding })
                                                    => {
                                                    break 'done Some(encoding);
                                                }
                                                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                    {}
                                                    #[deny(unreachable_patterns)]
                                                    _ => {}
                                            }
                                        }
                                        None
                                    }
                                }
                            } {
                        s.push_str(encoding.as_str().trim());
                    } else {
                        let name = tcx.item_name(*def_id).to_string();
                        let _ =
                            s.write_fmt(format_args!("{0}{1}", name.len(), name));
                    }
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Closure(def_id, args) => {
                    let mut s = String::new();
                    let name = encode_ty_name(tcx, *def_id);
                    let _ =
                        s.write_fmt(format_args!("u{0}{1}", name.len(), name));
                    s.push_str(&encode_args(tcx, args, *def_id, false, dict,
                                options));
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::FnDef(def_id, args) => {
                    let mut s = String::new();
                    let name = encode_ty_name(tcx, *def_id);
                    let _ =
                        s.write_fmt(format_args!("u{0}{1}", name.len(), name));
                    s.push_str(&encode_args(tcx, args.no_bound_vars().unwrap(),
                                *def_id, false, dict, options));
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::CoroutineClosure(def_id, args) => {
                    let mut s = String::new();
                    let name = encode_ty_name(tcx, *def_id);
                    let _ =
                        s.write_fmt(format_args!("u{0}{1}", name.len(), name));
                    let parent_args =
                        tcx.mk_args(args.as_coroutine_closure().parent_args());
                    s.push_str(&encode_args(tcx, parent_args, *def_id, false,
                                dict, options));
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Coroutine(def_id, args, ..) => {
                    let mut s = String::new();
                    let name = encode_ty_name(tcx, *def_id);
                    let _ =
                        s.write_fmt(format_args!("u{0}{1}", name.len(), name));
                    s.push_str(&encode_args(tcx,
                                tcx.mk_args(args.as_coroutine().parent_args()), *def_id,
                                false, dict, options));
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Ref(region, ty0, ..) => {
                    let mut s = String::new();
                    s.push_str("u3refI");
                    s.push_str(&encode_ty(tcx, *ty0, dict, options));
                    s.push('E');
                    compress(dict,
                        DictKey::Ty(Ty::new_imm_ref(tcx, *region, *ty0), TyQ::None),
                        &mut s);
                    if ty.is_mutable_ptr() {
                        s =
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0}{1}", "U3mut", s))
                                });
                        compress(dict, DictKey::Ty(ty, TyQ::Mut), &mut s);
                    }
                    typeid.push_str(&s);
                }
                ty::RawPtr(ptr_ty, _mutbl) => {
                    let mut s = String::new();
                    s.push_str(&encode_ty(tcx, *ptr_ty, dict, options));
                    if !ty.is_mutable_ptr() {
                        s =
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0}{1}", "K", s))
                                });
                        compress(dict, DictKey::Ty(*ptr_ty, TyQ::Const), &mut s);
                    };
                    s =
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("{0}{1}", "P", s))
                            });
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::FnPtr(sig_tys, hdr) => {
                    let mut s = String::from("P");
                    s.push_str(&encode_fnsig(tcx,
                                &sig_tys.with(*hdr).skip_binder(), dict,
                                TypeIdOptions::empty()));
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::UnsafeBinder(_) => {
                    ::core::panicking::panic("not implemented")
                }
                ty::Dynamic(predicates, region) => {
                    let mut s = String::from("u3dynI");
                    s.push_str(&encode_predicates(tcx, predicates, dict,
                                options));
                    s.push_str(&encode_region(*region, dict));
                    s.push('E');
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Param(..) => {
                    let mut s = String::from("u5param");
                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
                    typeid.push_str(&s);
                }
                ty::Alias(..) | ty::Bound(..) | ty::Error(..) |
                    ty::CoroutineWitness(..) | ty::Infer(..) |
                    ty::Placeholder(..) => {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("encode_ty: unexpected `{0:?}`",
                            ty.kind()));
                }
            };
            typeid
        }
    }
}#[instrument(level = "trace", skip(tcx, dict))]
421pub(crate) fn encode_ty<'tcx>(
422    tcx: TyCtxt<'tcx>,
423    ty: Ty<'tcx>,
424    dict: &mut FxHashMap<DictKey<'tcx>, usize>,
425    options: EncodeTyOptions,
426) -> String {
427    let mut typeid = String::new();
428
429    match ty.kind() {
430        // Primitive types
431
432        // Rust's bool has the same layout as C17's _Bool, that is, its size and alignment are
433        // implementation-defined. Any bool can be cast into an integer, taking on the values 1
434        // (true) or 0 (false).
435        //
436        // (See https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#bool.)
437        ty::Bool => {
438            typeid.push('b');
439        }
440
441        ty::Int(..) | ty::Uint(..) => {
442            // u<length><type-name> as vendor extended type
443            let mut s = String::from(match ty.kind() {
444                ty::Int(IntTy::I8) => "u2i8",
445                ty::Int(IntTy::I16) => "u3i16",
446                ty::Int(IntTy::I32) => "u3i32",
447                ty::Int(IntTy::I64) => "u3i64",
448                ty::Int(IntTy::I128) => "u4i128",
449                ty::Int(IntTy::Isize) => "u5isize",
450                ty::Uint(UintTy::U8) => "u2u8",
451                ty::Uint(UintTy::U16) => "u3u16",
452                ty::Uint(UintTy::U32) => "u3u32",
453                ty::Uint(UintTy::U64) => "u3u64",
454                ty::Uint(UintTy::U128) => "u4u128",
455                ty::Uint(UintTy::Usize) => "u5usize",
456                _ => bug!("encode_ty: unexpected `{:?}`", ty.kind()),
457            });
458            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
459            typeid.push_str(&s);
460        }
461
462        // Rust's f16, f32, f64, and f126 half (16-bit), single (32-bit), double (64-bit), and
463        // quad (128-bit)  precision floating-point types have IEEE-754 binary16, binary32,
464        // binary64, and binary128 floating-point layouts, respectively.
465        //
466        // (See https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#fixed-width-floating-point-types.)
467        ty::Float(float_ty) => {
468            typeid.push_str(match float_ty {
469                FloatTy::F16 => "Dh",
470                FloatTy::F32 => "f",
471                FloatTy::F64 => "d",
472                FloatTy::F128 => "g",
473            });
474        }
475
476        ty::Char => {
477            // u4char as vendor extended type
478            let mut s = String::from("u4char");
479            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
480            typeid.push_str(&s);
481        }
482
483        ty::Str => {
484            // u3str as vendor extended type
485            let mut s = String::from("u3str");
486            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
487            typeid.push_str(&s);
488        }
489
490        ty::Never => {
491            // u5never as vendor extended type
492            let mut s = String::from("u5never");
493            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
494            typeid.push_str(&s);
495        }
496
497        // Compound types
498        // () in Rust is equivalent to void return type in C
499        _ if ty.is_unit() => {
500            typeid.push('v');
501        }
502
503        // Sequence types
504        ty::Tuple(tys) => {
505            // u5tupleI<element-type1..element-typeN>E as vendor extended type
506            let mut s = String::from("u5tupleI");
507            for ty in tys.iter() {
508                s.push_str(&encode_ty(tcx, ty, dict, options));
509            }
510            s.push('E');
511            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
512            typeid.push_str(&s);
513        }
514
515        ty::Array(ty0, len) => {
516            // A<array-length><element-type>
517            let len = len.try_to_target_usize(tcx).expect("expected monomorphic const in cfi");
518            let mut s = String::from("A");
519            let _ = write!(s, "{len}");
520            s.push_str(&encode_ty(tcx, *ty0, dict, options));
521            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
522            typeid.push_str(&s);
523        }
524
525        ty::Pat(ty0, pat) => {
526            // u3patI<element-type><pattern>E as vendor extended type
527            let mut s = String::from("u3patI");
528            s.push_str(&encode_ty(tcx, *ty0, dict, options));
529            write!(s, "{:?}", **pat).unwrap();
530            s.push('E');
531            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
532            typeid.push_str(&s);
533        }
534
535        ty::Slice(ty0) => {
536            // u5sliceI<element-type>E as vendor extended type
537            let mut s = String::from("u5sliceI");
538            s.push_str(&encode_ty(tcx, *ty0, dict, options));
539            s.push('E');
540            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
541            typeid.push_str(&s);
542        }
543
544        // User-defined types
545        ty::Adt(adt_def, args) => {
546            let mut s = String::new();
547            let def_id = adt_def.did();
548            if let Some(encoding) = find_attr!(tcx, def_id, CfiEncoding { encoding } => encoding) {
549                let encoding = encoding.as_str().trim();
550                // Use user-defined CFI encoding for type
551                s.push_str(&encoding);
552                // Don't compress user-defined builtin types (see
553                // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-builtin and
554                // https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-compression).
555                let builtin_types = [
556                    "v", "w", "b", "c", "a", "h", "s", "t", "i", "j", "l", "m", "x", "y", "n", "o",
557                    "f", "d", "e", "g", "z", "Dh",
558                ];
559                if !builtin_types.contains(&encoding) {
560                    compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
561                }
562            } else if options.contains(EncodeTyOptions::GENERALIZE_REPR_C) && adt_def.repr().c() {
563                // For cross-language LLVM CFI support, the encoding must be compatible at the FFI
564                // boundary. For instance:
565                //
566                //     struct type1 {};
567                //     void foo(struct type1* bar) {}
568                //
569                // Is encoded as:
570                //
571                //     _ZTSFvP5type1E
572                //
573                // So, encode any repr(C) user-defined type for extern function types with the "C"
574                // calling convention (or extern types [i.e., ty::Foreign]) as <length><name>, where
575                // <name> is <unscoped-name>.
576                let name = tcx.item_name(def_id).to_string();
577                let _ = write!(s, "{}{}", name.len(), name);
578                compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
579            } else {
580                // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is
581                // <subst>, as vendor extended type.
582                let name = encode_ty_name(tcx, def_id);
583                let _ = write!(s, "u{}{}", name.len(), name);
584                s.push_str(&encode_args(tcx, args, def_id, false, dict, options));
585                compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
586            }
587            typeid.push_str(&s);
588        }
589
590        ty::Foreign(def_id) => {
591            // <length><name>, where <name> is <unscoped-name>
592            let mut s = String::new();
593
594            if let Some(encoding) = find_attr!(tcx, *def_id, CfiEncoding {encoding} => encoding) {
595                // Use user-defined CFI encoding for type
596                s.push_str(encoding.as_str().trim());
597            } else {
598                let name = tcx.item_name(*def_id).to_string();
599                let _ = write!(s, "{}{}", name.len(), name);
600            }
601            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
602            typeid.push_str(&s);
603        }
604
605        // Function types
606        ty::Closure(def_id, args) => {
607            // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
608            // as vendor extended type.
609            let mut s = String::new();
610            let name = encode_ty_name(tcx, *def_id);
611            let _ = write!(s, "u{}{}", name.len(), name);
612            s.push_str(&encode_args(tcx, args, *def_id, false, dict, options));
613            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
614            typeid.push_str(&s);
615        }
616
617        // FIXME: could stand to merge this and the prior match arm
618        ty::FnDef(def_id, args) => {
619            let mut s = String::new();
620            let name = encode_ty_name(tcx, *def_id);
621            let _ = write!(s, "u{}{}", name.len(), name);
622            s.push_str(&encode_args(
623                tcx,
624                args.no_bound_vars().unwrap(),
625                *def_id,
626                false,
627                dict,
628                options,
629            ));
630            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
631            typeid.push_str(&s);
632        }
633
634        ty::CoroutineClosure(def_id, args) => {
635            // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
636            // as vendor extended type.
637            let mut s = String::new();
638            let name = encode_ty_name(tcx, *def_id);
639            let _ = write!(s, "u{}{}", name.len(), name);
640            let parent_args = tcx.mk_args(args.as_coroutine_closure().parent_args());
641            s.push_str(&encode_args(tcx, parent_args, *def_id, false, dict, options));
642            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
643            typeid.push_str(&s);
644        }
645
646        ty::Coroutine(def_id, args, ..) => {
647            // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>,
648            // as vendor extended type.
649            let mut s = String::new();
650            let name = encode_ty_name(tcx, *def_id);
651            let _ = write!(s, "u{}{}", name.len(), name);
652            // Encode parent args only
653            s.push_str(&encode_args(
654                tcx,
655                tcx.mk_args(args.as_coroutine().parent_args()),
656                *def_id,
657                false,
658                dict,
659                options,
660            ));
661            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
662            typeid.push_str(&s);
663        }
664
665        // Pointer types
666        ty::Ref(region, ty0, ..) => {
667            // [U3mut]u3refI<element-type>E as vendor extended type qualifier and type
668            let mut s = String::new();
669            s.push_str("u3refI");
670            s.push_str(&encode_ty(tcx, *ty0, dict, options));
671            s.push('E');
672            compress(dict, DictKey::Ty(Ty::new_imm_ref(tcx, *region, *ty0), TyQ::None), &mut s);
673            if ty.is_mutable_ptr() {
674                s = format!("{}{}", "U3mut", s);
675                compress(dict, DictKey::Ty(ty, TyQ::Mut), &mut s);
676            }
677            typeid.push_str(&s);
678        }
679
680        ty::RawPtr(ptr_ty, _mutbl) => {
681            // FIXME: This can definitely not be so spaghettified.
682            // P[K]<element-type>
683            let mut s = String::new();
684            s.push_str(&encode_ty(tcx, *ptr_ty, dict, options));
685            if !ty.is_mutable_ptr() {
686                s = format!("{}{}", "K", s);
687                compress(dict, DictKey::Ty(*ptr_ty, TyQ::Const), &mut s);
688            };
689            s = format!("{}{}", "P", s);
690            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
691            typeid.push_str(&s);
692        }
693
694        ty::FnPtr(sig_tys, hdr) => {
695            // PF<return-type><parameter-type1..parameter-typeN>E
696            let mut s = String::from("P");
697            s.push_str(&encode_fnsig(
698                tcx,
699                &sig_tys.with(*hdr).skip_binder(),
700                dict,
701                TypeIdOptions::empty(),
702            ));
703            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
704            typeid.push_str(&s);
705        }
706
707        // FIXME(unsafe_binders): Implement this.
708        ty::UnsafeBinder(_) => {
709            unimplemented!()
710        }
711
712        // Trait types
713        ty::Dynamic(predicates, region) => {
714            // u3dynI<element-type1[..element-typeN]>E, where <element-type> is <predicate>, as
715            // vendor extended type.
716            let mut s = String::from("u3dynI");
717            s.push_str(&encode_predicates(tcx, predicates, dict, options));
718            s.push_str(&encode_region(*region, dict));
719            s.push('E');
720            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
721            typeid.push_str(&s);
722        }
723
724        // Type parameters
725        ty::Param(..) => {
726            // u5param as vendor extended type
727            let mut s = String::from("u5param");
728            compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
729            typeid.push_str(&s);
730        }
731
732        // Unexpected types
733        ty::Alias(..)
734        | ty::Bound(..)
735        | ty::Error(..)
736        | ty::CoroutineWitness(..)
737        | ty::Infer(..)
738        | ty::Placeholder(..) => {
739            bug!("encode_ty: unexpected `{:?}`", ty.kind());
740        }
741    };
742
743    typeid
744}
745
746/// Encodes a ty:Ty name, including its crate and path disambiguators and names.
747fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
748    // Encode <name> for use in u<length><name>[I<element-type1..element-typeN>E], where
749    // <element-type> is <subst>, using v0's <path> without v0's extended form of paths:
750    //
751    // N<namespace-tagN>..N<namespace-tag1>
752    // C<crate-disambiguator><crate-name>
753    // <path-disambiguator1><path-name1>..<path-disambiguatorN><path-nameN>
754    //
755    // With additional tags for DefPathData::Impl and DefPathData::ForeignMod. For instance:
756    //
757    //     pub type Type1 = impl Send;
758    //     let _: Type1 = <Struct1<i32>>::foo;
759    //     fn foo1(_: Type1) { }
760    //
761    //     pub type Type2 = impl Send;
762    //     let _: Type2 = <Trait1<i32>>::foo;
763    //     fn foo2(_: Type2) { }
764    //
765    //     pub type Type3 = impl Send;
766    //     let _: Type3 = <i32 as Trait1<i32>>::foo;
767    //     fn foo3(_: Type3) { }
768    //
769    //     pub type Type4 = impl Send;
770    //     let _: Type4 = <Struct1<i32> as Trait1<i32>>::foo;
771    //     fn foo3(_: Type4) { }
772    //
773    // Are encoded as:
774    //
775    //     _ZTSFvu29NvNIC1234_5crate8{{impl}}3fooIu3i32EE
776    //     _ZTSFvu27NvNtC1234_5crate6Trait13fooIu3dynIu21NtC1234_5crate6Trait1Iu3i32Eu6regionES_EE
777    //     _ZTSFvu27NvNtC1234_5crate6Trait13fooIu3i32S_EE
778    //     _ZTSFvu27NvNtC1234_5crate6Trait13fooIu22NtC1234_5crate7Struct1Iu3i32ES_EE
779    //
780    // The reason for not using v0's extended form of paths is to use a consistent and simpler
781    // encoding, as the reasoning for using it isn't relevant for type metadata identifiers (i.e.,
782    // keep symbol names close to how methods are represented in error messages). See
783    // https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html#methods.
784    let mut s = String::new();
785
786    // Start and namespace tags
787    let mut def_path = tcx.def_path(def_id);
788    def_path.data.reverse();
789    for disambiguated_data in &def_path.data {
790        s.push('N');
791        s.push_str(match disambiguated_data.data {
792            hir::definitions::DefPathData::Impl => "I", // Not specified in v0's <namespace>
793            hir::definitions::DefPathData::ForeignMod => "F", // Not specified in v0's <namespace>
794            hir::definitions::DefPathData::TypeNs(..) => "t",
795            hir::definitions::DefPathData::ValueNs(..) => "v",
796            hir::definitions::DefPathData::Closure => "C",
797            hir::definitions::DefPathData::Ctor => "c",
798            hir::definitions::DefPathData::AnonConst => "K",
799            hir::definitions::DefPathData::OpaqueTy => "i",
800            hir::definitions::DefPathData::SyntheticCoroutineBody => "s",
801            hir::definitions::DefPathData::NestedStatic => "n",
802            hir::definitions::DefPathData::CrateRoot
803            | hir::definitions::DefPathData::Use
804            | hir::definitions::DefPathData::GlobalAsm
805            | hir::definitions::DefPathData::MacroNs(..)
806            | hir::definitions::DefPathData::OpaqueLifetime(..)
807            | hir::definitions::DefPathData::LifetimeNs(..)
808            | hir::definitions::DefPathData::AnonAssocTy(..) => {
809                ::rustc_middle::util::bug::bug_fmt(format_args!("encode_ty_name: unexpected `{0:?}`",
        disambiguated_data.data));bug!("encode_ty_name: unexpected `{:?}`", disambiguated_data.data);
810            }
811        });
812    }
813
814    // Crate disambiguator and name
815    s.push('C');
816    s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).as_u64()));
817    let crate_name = tcx.crate_name(def_path.krate).to_string();
818    let _ = s.write_fmt(format_args!("{0}{1}", crate_name.len(), crate_name))write!(s, "{}{}", crate_name.len(), crate_name);
819
820    // Disambiguators and names
821    def_path.data.reverse();
822    for disambiguated_data in &def_path.data {
823        let num = disambiguated_data.disambiguator as u64;
824        if num > 0 {
825            s.push_str(&to_disambiguator(num));
826        }
827
828        let name = disambiguated_data.data.to_string();
829        let _ = s.write_fmt(format_args!("{0}", name.len()))write!(s, "{}", name.len());
830
831        // Prepend a '_' if name starts with a digit or '_'
832        if let Some(first) = name.as_bytes().first() {
833            if first.is_ascii_digit() || *first == b'_' {
834                s.push('_');
835            }
836        } else {
837            ::rustc_middle::util::bug::bug_fmt(format_args!("encode_ty_name: invalid name `{0:?}`",
        name));bug!("encode_ty_name: invalid name `{:?}`", name);
838        }
839
840        s.push_str(&name);
841    }
842
843    s
844}
845
846/// Converts a number to a disambiguator (see
847/// <https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html>).
848fn to_disambiguator(num: u64) -> String {
849    if let Some(num) = num.checked_sub(1) {
850        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("s{0}_",
                num.to_base(ALPHANUMERIC_ONLY)))
    })format!("s{}_", num.to_base(ALPHANUMERIC_ONLY))
851    } else {
852        "s_".to_string()
853    }
854}
855
856/// Converts a number to a sequence number (see
857/// <https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.seq-id>).
858fn to_seq_id(num: usize) -> String {
859    if let Some(num) = num.checked_sub(1) {
860        (num as u64).to_base(CASE_INSENSITIVE).to_uppercase()
861    } else {
862        "".to_string()
863    }
864}