Skip to main content

rustc_codegen_llvm/debuginfo/
metadata.rs

1use std::borrow::Cow;
2use std::fmt::{self, Write};
3use std::hash::{Hash, Hasher};
4use std::path::PathBuf;
5use std::{assert_matches, iter, ptr};
6
7use libc::{c_longlong, c_uint};
8use rustc_abi::{Align, Endian, Layout, NumScalableVectors, Size};
9use rustc_ast::{IntTy, UintTy};
10use rustc_codegen_ssa::debuginfo::type_names::{VTableNameKind, cpp_like_debuginfo};
11use rustc_codegen_ssa::traits::*;
12use rustc_hir::def::{CtorKind, DefKind};
13use rustc_hir::def_id::{DefId, LOCAL_CRATE};
14use rustc_middle::ty::layout::{
15    HasTypingEnv, LayoutOf, TyAndLayout, WIDE_PTR_ADDR, WIDE_PTR_EXTRA,
16};
17use rustc_middle::ty::{
18    self, AdtDef, AdtKind, ExistentialTraitRef, Instance, Ty, TyCtxt, Unnormalized, Visibility,
19};
20use rustc_session::config::{self, DebugInfo, Lto};
21use rustc_span::{
22    DUMMY_SP, FileName, RemapPathScopeComponents, SourceFile, Span, Symbol, bug, hygiene,
23};
24use rustc_symbol_mangling::typeid_for_trait_ref;
25use rustc_target::spec::{Arch, DebuginfoKind, HasTargetSpec};
26use smallvec::smallvec;
27use tracing::{debug, instrument};
28
29pub(crate) use self::type_map::TypeMap;
30use self::type_map::{DINodeCreationResult, Stub, UniqueTypeId};
31use super::CodegenUnitDebugContext;
32use super::namespace::mangled_name_of_instance;
33use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
34use super::utils::{DIB, debug_context, get_namespace_for_item, is_node_local_to_unit};
35use crate::common::CodegenCx;
36use crate::debuginfo::metadata::type_map::build_type_with_children;
37use crate::debuginfo::utils::{WidePtrKind, create_DIArray, wide_pointer_kind};
38use crate::debuginfo::{DIBuilderExt, dwarf_const};
39use crate::llvm::debuginfo::{
40    DIBasicType, DIBuilder, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock,
41    DIScope, DIType, DebugEmissionKind, DebugNameTableKind,
42};
43use crate::llvm::{self, FromGeneric, Value};
44
45impl PartialEq for llvm::Metadata {
46    fn eq(&self, other: &Self) -> bool {
47        ptr::eq(self, other)
48    }
49}
50
51impl Eq for llvm::Metadata {}
52
53impl Hash for llvm::Metadata {
54    fn hash<H: Hasher>(&self, hasher: &mut H) {
55        (self as *const Self).hash(hasher);
56    }
57}
58
59impl fmt::Debug for llvm::Metadata {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        (self as *const Self).fmt(f)
62    }
63}
64
65pub(super) const UNKNOWN_LINE_NUMBER: c_uint = 0;
66pub(super) const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
67
68const NO_SCOPE_METADATA: Option<&DIScope> = None;
69/// A function that returns an empty list of generic parameter debuginfo nodes.
70const NO_GENERICS: for<'ll> fn(&CodegenCx<'ll, '_>) -> SmallVec<Option<&'ll DIType>> =
71    |_| SmallVec::new();
72
73// SmallVec is used quite a bit in this module, so create a shorthand.
74// The actual number of elements is not so important.
75type SmallVec<T> = smallvec::SmallVec<[T; 16]>;
76
77mod enums;
78mod type_map;
79
80/// Returns from the enclosing function if the type debuginfo node with the given
81/// unique ID can be found in the type map.
82macro_rules! return_if_di_node_created_in_meantime {
83    ($cx: expr, $unique_type_id: expr) => {
84        if let Some(di_node) = debug_context($cx).type_map.di_node_for_unique_id($unique_type_id) {
85            return DINodeCreationResult::new(di_node, true);
86        }
87    };
88}
89
90/// Extract size and alignment from a TyAndLayout.
91#[inline]
92fn size_and_align_of(ty_and_layout: TyAndLayout<'_>) -> (Size, Align) {
93    (ty_and_layout.size, ty_and_layout.align)
94}
95
96/// Creates debuginfo for a fixed size array (e.g. `[u64; 123]`).
97/// For slices (that is, "arrays" of unknown size) use [build_slice_type_di_node].
98fn build_fixed_size_array_di_node<'ll, 'tcx>(
99    cx: &CodegenCx<'ll, 'tcx>,
100    unique_type_id: UniqueTypeId<'tcx>,
101    array_type: Ty<'tcx>,
102    span: Span,
103) -> DINodeCreationResult<'ll> {
104    let ty::Array(element_type, len) = array_type.kind() else {
105        ::rustc_span::macros::bug_impl(None,
    format_args!("build_fixed_size_array_di_node() called with non-ty::Array type `{0:?}`",
        array_type), Location::caller())bug!("build_fixed_size_array_di_node() called with non-ty::Array type `{:?}`", array_type)
106    };
107
108    let element_type_di_node = spanned_type_di_node(cx, *element_type, span);
109
110    if let Some(di_node) =
        debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
    return DINodeCreationResult::new(di_node, true);
};return_if_di_node_created_in_meantime!(cx, unique_type_id);
111
112    let (size, align) = cx.spanned_size_and_align_of(array_type, span);
113
114    let upper_bound = len
115        .try_to_target_usize(cx.tcx)
116        .expect("expected monomorphic const in codegen") as c_longlong;
117
118    let subrange = unsafe { llvm::LLVMDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound) };
119    let subscripts = &[subrange];
120
121    let di_node = unsafe {
122        llvm::LLVMDIBuilderCreateArrayType(
123            DIB(cx),
124            size.bits(),
125            align.bits() as u32,
126            element_type_di_node,
127            subscripts.as_ptr(),
128            subscripts.len() as c_uint,
129        )
130    };
131
132    DINodeCreationResult::new(di_node, false)
133}
134
135/// Creates debuginfo for built-in pointer-like things:
136///
137///  - ty::Ref
138///  - ty::RawPtr
139///  - ty::Adt in the case it's Box
140///
141/// At some point we might want to remove the special handling of Box
142/// and treat it the same as other smart pointers (like Rc, Arc, ...).
143fn build_pointer_or_reference_di_node<'ll, 'tcx>(
144    cx: &CodegenCx<'ll, 'tcx>,
145    ptr_type: Ty<'tcx>,
146    pointee_type: Ty<'tcx>,
147    unique_type_id: UniqueTypeId<'tcx>,
148    span: Span,
149) -> DINodeCreationResult<'ll> {
150    // The debuginfo generated by this function is only valid if `ptr_type` is really just
151    // a (wide) pointer. Make sure it is not called for e.g. `Box<T, NonZSTAllocator>`.
152    {
    match (&cx.size_and_align_of(ptr_type),
            &cx.size_and_align_of(Ty::new_mut_ptr(cx.tcx, pointee_type))) {
        (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!(
153        cx.size_and_align_of(ptr_type),
154        cx.size_and_align_of(Ty::new_mut_ptr(cx.tcx, pointee_type))
155    );
156
157    let pointee_type_di_node = match pointee_type.kind() {
158        // `&[T]` will look like `{ data_ptr: *const T, length: usize }`
159        ty::Slice(element_type) => spanned_type_di_node(cx, *element_type, span),
160        // `&str` will look like `{ data_ptr: *const u8, length: usize }`
161        ty::Str => type_di_node(cx, cx.tcx.types.u8),
162
163        // `&dyn K` will look like `{ pointer: _, vtable: _}`
164        // any Adt `Foo` containing an unsized type (eg `&[_]` or `&dyn _`)
165        //   will look like `{ data_ptr: *const Foo, length: usize }`
166        // and thin pointers `&Foo` will just look like `*const Foo`.
167        //
168        // in all those cases, we just use the pointee_type
169        _ => spanned_type_di_node(cx, pointee_type, span),
170    };
171
172    if let Some(di_node) =
        debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
    return DINodeCreationResult::new(di_node, true);
};return_if_di_node_created_in_meantime!(cx, unique_type_id);
173
174    let data_layout = &cx.tcx.data_layout;
175    let pointer_size = data_layout.pointer_size();
176    let pointer_align = data_layout.pointer_align();
177    let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
178
179    match wide_pointer_kind(cx, pointee_type) {
180        None => {
181            // This is a thin pointer. Create a regular pointer type and give it the correct name.
182            {
    match (&(pointer_size, pointer_align), &cx.size_and_align_of(ptr_type)) {
        (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::Some(format_args!("ptr_type={0}, pointee_type={1}",
                            ptr_type, pointee_type)));
            }
        }
    }
};assert_eq!(
183                (pointer_size, pointer_align),
184                cx.size_and_align_of(ptr_type),
185                "ptr_type={ptr_type}, pointee_type={pointee_type}",
186            );
187
188            let di_node = create_pointer_type(
189                cx,
190                pointee_type_di_node,
191                pointer_size,
192                pointer_align,
193                &ptr_type_debuginfo_name,
194            );
195
196            DINodeCreationResult { di_node, already_stored_in_typemap: false }
197        }
198        Some(wide_pointer_kind) => {
199            type_map::build_type_with_children(
200                cx,
201                type_map::stub(
202                    cx,
203                    Stub::Struct,
204                    unique_type_id,
205                    &ptr_type_debuginfo_name,
206                    None,
207                    cx.size_and_align_of(ptr_type),
208                    NO_SCOPE_METADATA,
209                    DIFlags::FlagZero,
210                ),
211                |cx, owner| {
212                    // FIXME: If this wide pointer is a `Box` then we don't want to use its
213                    //        type layout and instead use the layout of the raw pointer inside
214                    //        of it.
215                    //        The proper way to handle this is to not treat Box as a pointer
216                    //        at all and instead emit regular struct debuginfo for it. We just
217                    //        need to make sure that we don't break existing debuginfo consumers
218                    //        by doing that (at least not without a warning period).
219                    let layout_type = if ptr_type.is_box() {
220                        // The assertion at the start of this function ensures we have a ZST
221                        // allocator. We'll make debuginfo "skip" all ZST allocators, not just the
222                        // default allocator.
223                        Ty::new_mut_ptr(cx.tcx, pointee_type)
224                    } else {
225                        ptr_type
226                    };
227
228                    let layout = cx.layout_of(layout_type);
229                    let addr_field = layout.field(cx, WIDE_PTR_ADDR);
230                    let extra_field = layout.field(cx, WIDE_PTR_EXTRA);
231
232                    let (addr_field_name, extra_field_name) = match wide_pointer_kind {
233                        WidePtrKind::Dyn => ("pointer", "vtable"),
234                        WidePtrKind::Slice => ("data_ptr", "length"),
235                    };
236
237                    {
    match (&WIDE_PTR_ADDR, &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!(WIDE_PTR_ADDR, 0);
238                    {
    match (&WIDE_PTR_EXTRA, &1) {
        (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!(WIDE_PTR_EXTRA, 1);
239
240                    // The data pointer type is a regular, thin pointer, regardless of whether this
241                    // is a slice or a trait object.
242                    let data_ptr_type_di_node = create_pointer_type(
243                        cx,
244                        pointee_type_di_node,
245                        addr_field.size,
246                        addr_field.align,
247                        "",
248                    );
249
250                    {
    let count = 0usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(build_field_di_node(cx, owner, addr_field_name, addr_field,
                layout.fields.offset(WIDE_PTR_ADDR), DIFlags::FlagZero,
                data_ptr_type_di_node, None));
        vec.push(build_field_di_node(cx, owner, extra_field_name, extra_field,
                layout.fields.offset(WIDE_PTR_EXTRA), DIFlags::FlagZero,
                type_di_node(cx, extra_field.ty), None));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [build_field_di_node(cx, owner, addr_field_name, addr_field,
                                layout.fields.offset(WIDE_PTR_ADDR), DIFlags::FlagZero,
                                data_ptr_type_di_node, None),
                            build_field_di_node(cx, owner, extra_field_name,
                                extra_field, layout.fields.offset(WIDE_PTR_EXTRA),
                                DIFlags::FlagZero, type_di_node(cx, extra_field.ty),
                                None)])))
    }
}smallvec![
251                        build_field_di_node(
252                            cx,
253                            owner,
254                            addr_field_name,
255                            addr_field,
256                            layout.fields.offset(WIDE_PTR_ADDR),
257                            DIFlags::FlagZero,
258                            data_ptr_type_di_node,
259                            None,
260                        ),
261                        build_field_di_node(
262                            cx,
263                            owner,
264                            extra_field_name,
265                            extra_field,
266                            layout.fields.offset(WIDE_PTR_EXTRA),
267                            DIFlags::FlagZero,
268                            type_di_node(cx, extra_field.ty),
269                            None,
270                        ),
271                    ]
272                },
273                NO_GENERICS,
274            )
275        }
276    }
277}
278
279fn build_subroutine_type_di_node<'ll, 'tcx>(
280    cx: &CodegenCx<'ll, 'tcx>,
281    unique_type_id: UniqueTypeId<'tcx>,
282) -> DINodeCreationResult<'ll> {
283    // It's possible to create a self-referential type in Rust by using 'impl trait':
284    //
285    // fn foo() -> impl Copy { foo }
286    //
287    // Unfortunately LLVM's API does not allow us to create recursive subroutine types.
288    // In order to work around that restriction we place a marker type in the type map,
289    // before creating the actual type. If the actual type is recursive, it will hit the
290    // marker type. So we end up with a type that looks like
291    //
292    // fn foo() -> <recursive_type>
293    //
294    // Once that is created, we replace the marker in the typemap with the actual type.
295    debug_context(cx)
296        .type_map
297        .unique_id_to_di_node
298        .borrow_mut()
299        .insert(unique_type_id, recursion_marker_type_di_node(cx));
300
301    let fn_ty = unique_type_id.expect_ty();
302    let signature =
303        cx.tcx.normalize_erasing_late_bound_regions(cx.typing_env(), fn_ty.fn_sig(cx.tcx));
304
305    let signature_di_nodes: SmallVec<_> = iter::once(
306        // return type
307        match signature.output().kind() {
308            ty::Tuple(tys) if tys.is_empty() => {
309                // this is a "void" function
310                None
311            }
312            _ => Some(type_di_node(cx, signature.output())),
313        },
314    )
315    .chain(
316        // regular arguments
317        signature.inputs().iter().map(|&argument_type| Some(type_di_node(cx, argument_type))),
318    )
319    .collect();
320
321    debug_context(cx).type_map.unique_id_to_di_node.borrow_mut().remove(&unique_type_id);
322
323    let fn_di_node = create_subroutine_type(cx, &signature_di_nodes[..]);
324
325    // This is actually a function pointer, so wrap it in pointer DI.
326    let name = compute_debuginfo_type_name(cx.tcx, fn_ty, false);
327    let (size, align) = match fn_ty.kind() {
328        ty::FnDef(..) => (Size::ZERO, Align::ONE),
329        ty::FnPtr(..) => (cx.tcx.data_layout.pointer_size(), cx.tcx.data_layout.pointer_align()),
330        _ => ::core::panicking::unreachable_default_msg()unreachable!(),
331    };
332    let di_node = create_pointer_type(cx, fn_di_node, size, align, &name);
333
334    DINodeCreationResult::new(di_node, false)
335}
336
337pub(super) fn create_subroutine_type<'ll>(
338    cx: &CodegenCx<'ll, '_>,
339    signature: &[Option<&'ll llvm::Metadata>],
340) -> &'ll DICompositeType {
341    unsafe {
342        llvm::LLVMDIBuilderCreateSubroutineType(
343            DIB(cx),
344            None, // ("File" is ignored and has no effect)
345            signature.as_ptr(),
346            signature.len() as c_uint,
347            DIFlags::FlagZero, // (default value)
348        )
349    }
350}
351
352fn create_pointer_type<'ll>(
353    cx: &CodegenCx<'ll, '_>,
354    pointee_ty: &'ll llvm::Metadata,
355    size: Size,
356    align: Align,
357    name: &str,
358) -> &'ll llvm::Metadata {
359    unsafe {
360        llvm::LLVMDIBuilderCreatePointerType(
361            DIB(cx),
362            pointee_ty,
363            size.bits(),
364            align.bits() as u32,
365            0, // Ignore DWARF address space.
366            name.as_ptr(),
367            name.len(),
368        )
369    }
370}
371
372/// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
373/// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
374fn build_dyn_type_di_node<'ll, 'tcx>(
375    cx: &CodegenCx<'ll, 'tcx>,
376    dyn_type: Ty<'tcx>,
377    unique_type_id: UniqueTypeId<'tcx>,
378) -> DINodeCreationResult<'ll> {
379    if let ty::Dynamic(..) = dyn_type.kind() {
380        let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
381        type_map::build_type_with_children(
382            cx,
383            type_map::stub(
384                cx,
385                Stub::Struct,
386                unique_type_id,
387                &type_name,
388                None,
389                cx.size_and_align_of(dyn_type),
390                NO_SCOPE_METADATA,
391                DIFlags::FlagZero,
392            ),
393            |_, _| ::smallvec::SmallVec::new()smallvec![],
394            NO_GENERICS,
395        )
396    } else {
397        ::rustc_span::macros::bug_impl(None,
    format_args!("Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {0:?} instead.",
        dyn_type), Location::caller())bug!(
398            "Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {:?} instead.",
399            dyn_type
400        )
401    }
402}
403
404/// Create debuginfo for `[T]` and `str`. These are unsized.
405fn build_slice_type_di_node<'ll, 'tcx>(
406    cx: &CodegenCx<'ll, 'tcx>,
407    slice_type: Ty<'tcx>,
408    unique_type_id: UniqueTypeId<'tcx>,
409    span: Span,
410) -> DINodeCreationResult<'ll> {
411    let element_type = match slice_type.kind() {
412        ty::Slice(element_type) => *element_type,
413        ty::Str => cx.tcx.types.u8,
414        _ => {
415            ::rustc_span::macros::bug_impl(None,
    format_args!("Only ty::Slice is valid for build_slice_type_di_node(). Found {0:?} instead.",
        slice_type), Location::caller())bug!(
416                "Only ty::Slice is valid for build_slice_type_di_node(). Found {:?} instead.",
417                slice_type
418            )
419        }
420    };
421
422    let element_type_di_node = type_di_node(cx, element_type);
423    if let Some(di_node) =
        debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
    return DINodeCreationResult::new(di_node, true);
};return_if_di_node_created_in_meantime!(cx, unique_type_id);
424    let (size, align) = cx.spanned_size_and_align_of(slice_type, span);
425    let subrange = unsafe { llvm::LLVMDIBuilderGetOrCreateSubrange(DIB(cx), 0, -1) };
426    let subscripts = &[subrange];
427    let di_node = unsafe {
428        llvm::LLVMDIBuilderCreateArrayType(
429            DIB(cx),
430            size.bits(),
431            align.bits() as u32,
432            element_type_di_node,
433            subscripts.as_ptr(),
434            subscripts.len() as c_uint,
435        )
436    };
437    DINodeCreationResult { di_node, already_stored_in_typemap: false }
438}
439
440/// Get the debuginfo node for the given type.
441///
442/// This function will look up the debuginfo node in the TypeMap. If it can't find it, it
443/// will create the node by dispatching to the corresponding `build_*_di_node()` function.
444pub(crate) fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
445    spanned_type_di_node(cx, t, DUMMY_SP)
446}
447
448pub(crate) fn spanned_type_di_node<'ll, 'tcx>(
449    cx: &CodegenCx<'ll, 'tcx>,
450    t: Ty<'tcx>,
451    span: Span,
452) -> &'ll DIType {
453    let unique_type_id = UniqueTypeId::for_ty(cx.tcx, t);
454
455    if let Some(existing_di_node) = debug_context(cx).type_map.di_node_for_unique_id(unique_type_id)
456    {
457        return existing_di_node;
458    }
459
460    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:460",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(460u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type_di_node: {0:?} kind: {1:?}",
                                                    t, t.kind()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("type_di_node: {:?} kind: {:?}", t, t.kind());
461
462    let DINodeCreationResult { di_node, already_stored_in_typemap } = match *t.kind() {
463        ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
464            build_basic_type_di_node(cx, t)
465        }
466        ty::Tuple(elements) if elements.is_empty() => build_basic_type_di_node(cx, t),
467        ty::Array(..) => build_fixed_size_array_di_node(cx, unique_type_id, t, span),
468        ty::Slice(_) | ty::Str => build_slice_type_di_node(cx, t, unique_type_id, span),
469        ty::Dynamic(..) => build_dyn_type_di_node(cx, t, unique_type_id),
470        ty::Foreign(..) => build_foreign_type_di_node(cx, t, unique_type_id),
471        ty::RawPtr(pointee_type, _) | ty::Ref(_, pointee_type, _) => {
472            build_pointer_or_reference_di_node(cx, t, pointee_type, unique_type_id, span)
473        }
474        // Some `Box` are newtyped pointers, make debuginfo aware of that.
475        // Only works if the allocator argument is a 1-ZST and hence irrelevant for layout
476        // (or if there is no allocator argument).
477        ty::Adt(def, args)
478            if def.is_box()
479                && args.get(1).is_none_or(|arg| cx.layout_of(arg.expect_ty()).is_1zst()) =>
480        {
481            build_pointer_or_reference_di_node(cx, t, t.expect_boxed_ty(), unique_type_id, span)
482        }
483        ty::FnDef(..) | ty::FnPtr(..) => build_subroutine_type_di_node(cx, unique_type_id),
484        ty::Closure(..) => build_closure_env_di_node(cx, unique_type_id),
485        ty::CoroutineClosure(..) => build_closure_env_di_node(cx, unique_type_id),
486        ty::Coroutine(..) => enums::build_coroutine_di_node(cx, unique_type_id),
487        ty::Adt(def, ..) => match def.adt_kind() {
488            AdtKind::Struct => build_struct_type_di_node(cx, unique_type_id, span),
489            AdtKind::Union => build_union_type_di_node(cx, unique_type_id, span),
490            AdtKind::Enum => enums::build_enum_type_di_node(cx, unique_type_id, span),
491        },
492        ty::Tuple(_) => build_tuple_type_di_node(cx, unique_type_id),
493        ty::Pat(base, _) => return type_di_node(cx, base),
494        ty::UnsafeBinder(_) => build_unsafe_binder_type_di_node(cx, t, unique_type_id),
495        ty::Alias(..)
496        | ty::Param(_)
497        | ty::Bound(..)
498        | ty::Infer(_)
499        | ty::Placeholder(_)
500        | ty::CoroutineWitness(..)
501        | ty::Error(_) => {
502            ::rustc_span::macros::bug_impl(None,
    format_args!("debuginfo: unexpected type in type_di_node(): {0:?}", t),
    Location::caller())bug!("debuginfo: unexpected type in type_di_node(): {:?}", t)
503        }
504    };
505
506    {
507        if already_stored_in_typemap {
508            // Make sure that we really do have a `TypeMap` entry for the unique type ID.
509            let di_node_for_uid =
510                match debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
511                    Some(di_node) => di_node,
512                    None => {
513                        ::rustc_span::macros::bug_impl(None,
    format_args!("expected type debuginfo node for unique type ID \'{0:?}\' to already be in the `debuginfo::TypeMap` but it was not.",
        unique_type_id), Location::caller());bug!(
514                            "expected type debuginfo node for unique \
515                               type ID '{:?}' to already be in \
516                               the `debuginfo::TypeMap` but it \
517                               was not.",
518                            unique_type_id,
519                        );
520                    }
521                };
522
523            {
    match (&(di_node_for_uid as *const _), &(di_node as *const _)) {
        (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!(di_node_for_uid as *const _, di_node as *const _);
524        } else {
525            debug_context(cx).type_map.insert(unique_type_id, di_node);
526        }
527    }
528
529    di_node
530}
531
532// FIXME(mw): Cache this via a regular UniqueTypeId instead of an extra field in the debug context.
533fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType {
534    *debug_context(cx).recursion_marker_type.get_or_init(move || {
535        // The choice of type here is pretty arbitrary -
536        // anything reading the debuginfo for a recursive
537        // type is going to see *something* weird - the only
538        // question is what exactly it will see.
539        //
540        // FIXME: the name `<recur_type>` does not fit the naming scheme
541        //        of other types.
542        //
543        // FIXME: it might make sense to use an actual pointer type here
544        //        so that debuggers can show the address.
545        create_basic_type(
546            cx,
547            "<recur_type>",
548            cx.tcx.data_layout.pointer_size(),
549            dwarf_const::DW_ATE_unsigned,
550        )
551    })
552}
553
554fn hex_encode(data: &[u8]) -> String {
555    let mut hex_string = String::with_capacity(data.len() * 2);
556    for byte in data.iter() {
557        (&mut hex_string).write_fmt(format_args!("{0:02x}", byte))write!(&mut hex_string, "{byte:02x}").unwrap();
558    }
559    hex_string
560}
561
562pub(crate) fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
563    let cache_key = Some((source_file.stable_id, source_file.src_hash));
564    return debug_context(cx)
565        .created_files
566        .borrow_mut()
567        .entry(cache_key)
568        .or_insert_with(|| alloc_new_file_metadata(cx, source_file));
569
570    {}
#[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("alloc_new_file_metadata",
                                    "rustc_codegen_llvm::debuginfo::metadata",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                    ::tracing_core::__macro_support::Option::Some(570u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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: &'ll DIFile = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:575",
                                    "rustc_codegen_llvm::debuginfo::metadata",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                    ::tracing_core::__macro_support::Option::Some(575u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_file.name")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_file.name");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_file.name)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let (directory, file_name) =
                match &source_file.name {
                    FileName::Real(filename) => {
                        let (working_directory, embeddable_name) =
                            filename.embeddable_name(RemapPathScopeComponents::DEBUGINFO);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:582",
                                                "rustc_codegen_llvm::debuginfo::metadata",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                                ::tracing_core::__macro_support::Option::Some(582u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("working_directory")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("working_directory");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("embeddable_name")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("embeddable_name");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&working_directory)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&embeddable_name)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        if let Ok(rel_path) =
                                embeddable_name.strip_prefix(working_directory) {
                            (working_directory.to_string_lossy(),
                                rel_path.to_string_lossy().into_owned())
                        } else {
                            ("".into(), embeddable_name.to_string_lossy().into_owned())
                        }
                    }
                    other => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:607",
                                                "rustc_codegen_llvm::debuginfo::metadata",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                                                ::tracing_core::__macro_support::Option::Some(607u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                                                ::tracing_core::field::FieldSet::new(&[{
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("other")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("other");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&other)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        ("".into(),
                            other.display(RemapPathScopeComponents::DEBUGINFO).to_string())
                    }
                };
            let hash_kind =
                match source_file.src_hash.kind {
                    rustc_span::SourceFileHashAlgorithm::Md5 =>
                        llvm::ChecksumKind::MD5,
                    rustc_span::SourceFileHashAlgorithm::Sha1 =>
                        llvm::ChecksumKind::SHA1,
                    rustc_span::SourceFileHashAlgorithm::Sha256 =>
                        llvm::ChecksumKind::SHA256,
                    rustc_span::SourceFileHashAlgorithm::Blake3 =>
                        llvm::ChecksumKind::None,
                };
            let hash_value = hex_encode(source_file.src_hash.hash_bytes());
            let mut source = None;
            let external_src;
            if cx.sess().opts.unstable_opts.embed_source {
                source = source_file.src.as_deref().map(String::as_str);
                if source.is_none() {
                    cx.tcx.sess.source_map().ensure_source_file_source_present(source_file);
                    external_src = source_file.external_src.read();
                    source = external_src.get_source();
                }
            }
            create_file(DIB(cx), &file_name, &directory, &hash_value,
                hash_kind, source)
        }
    }
}#[instrument(skip(cx, source_file), level = "debug")]
571    fn alloc_new_file_metadata<'ll>(
572        cx: &CodegenCx<'ll, '_>,
573        source_file: &SourceFile,
574    ) -> &'ll DIFile {
575        debug!(?source_file.name);
576
577        let (directory, file_name) = match &source_file.name {
578            FileName::Real(filename) => {
579                let (working_directory, embeddable_name) =
580                    filename.embeddable_name(RemapPathScopeComponents::DEBUGINFO);
581
582                debug!(?working_directory, ?embeddable_name);
583
584                if let Ok(rel_path) = embeddable_name.strip_prefix(working_directory) {
585                    // If the compiler's working directory (which also is the DW_AT_comp_dir of
586                    // the compilation unit) is a prefix of the path we are about to emit, then
587                    // only emit the part relative to the working directory. Because of path
588                    // remapping we sometimes see strange things here: `abs_path` might
589                    // actually look like a relative path (e.g.
590                    // `<crate-name-and-version>/src/lib.rs`), so if we emit it without taking
591                    // the working directory into account, downstream tooling will interpret it
592                    // as `<working-directory>/<crate-name-and-version>/src/lib.rs`, which
593                    // makes no sense. Usually in such cases the working directory will also be
594                    // remapped to `<crate-name-and-version>` or some other prefix of the path
595                    // we are remapping, so we end up with
596                    // `<crate-name-and-version>/<crate-name-and-version>/src/lib.rs`.
597                    //
598                    // By moving the working directory portion into the `directory` part of the
599                    // DIFile, we allow LLVM to emit just the relative path for DWARF, while
600                    // still emitting the correct absolute path for CodeView.
601                    (working_directory.to_string_lossy(), rel_path.to_string_lossy().into_owned())
602                } else {
603                    ("".into(), embeddable_name.to_string_lossy().into_owned())
604                }
605            }
606            other => {
607                debug!(?other);
608                ("".into(), other.display(RemapPathScopeComponents::DEBUGINFO).to_string())
609            }
610        };
611
612        let hash_kind = match source_file.src_hash.kind {
613            rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
614            rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
615            rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
616            rustc_span::SourceFileHashAlgorithm::Blake3 => llvm::ChecksumKind::None,
617        };
618        let hash_value = hex_encode(source_file.src_hash.hash_bytes());
619
620        let mut source = None;
621        let external_src;
622        if cx.sess().opts.unstable_opts.embed_source {
623            source = source_file.src.as_deref().map(String::as_str);
624            if source.is_none() {
625                cx.tcx.sess.source_map().ensure_source_file_source_present(source_file);
626                external_src = source_file.external_src.read();
627                source = external_src.get_source();
628            }
629        }
630
631        create_file(DIB(cx), &file_name, &directory, &hash_value, hash_kind, source)
632    }
633}
634
635fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
636    debug_context(cx).created_files.borrow_mut().entry(None).or_insert_with(|| {
637        create_file(DIB(cx), "<unknown>", "", "", llvm::ChecksumKind::None, None)
638    })
639}
640
641fn create_file<'ll>(
642    builder: &DIBuilder<'ll>,
643    file_name: &str,
644    directory: &str,
645    hash_value: &str,
646    hash_kind: llvm::ChecksumKind,
647    source: Option<&str>,
648) -> &'ll DIFile {
649    unsafe {
650        llvm::LLVMRustDIBuilderCreateFile(
651            builder,
652            file_name.as_ptr(),
653            file_name.len(),
654            directory.as_ptr(),
655            directory.len(),
656            hash_kind,
657            hash_value.as_ptr(),
658            hash_value.len(),
659            source.map_or(ptr::null(), |x| x.as_ptr()),
660            source.map_or(0, |x| x.len()),
661        )
662    }
663}
664
665trait MsvcBasicName {
666    fn msvc_basic_name(self) -> &'static str;
667}
668
669impl MsvcBasicName for ty::IntTy {
670    fn msvc_basic_name(self) -> &'static str {
671        match self {
672            ty::IntTy::Isize => "ptrdiff_t",
673            ty::IntTy::I8 => "__int8",
674            ty::IntTy::I16 => "__int16",
675            ty::IntTy::I32 => "__int32",
676            ty::IntTy::I64 => "__int64",
677            ty::IntTy::I128 => "__int128",
678        }
679    }
680}
681
682impl MsvcBasicName for ty::UintTy {
683    fn msvc_basic_name(self) -> &'static str {
684        match self {
685            ty::UintTy::Usize => "size_t",
686            ty::UintTy::U8 => "unsigned __int8",
687            ty::UintTy::U16 => "unsigned __int16",
688            ty::UintTy::U32 => "unsigned __int32",
689            ty::UintTy::U64 => "unsigned __int64",
690            ty::UintTy::U128 => "unsigned __int128",
691        }
692    }
693}
694
695/// `float_ty` must be a [`ty::Float`] and `bits_ty` must be a [`ty::Uint`].
696/// `cx.size_of(bits_ty) * bits_names.len()` must equal `cx.size_of(float_ty)`.
697fn build_cpp_float_struct_di_node<'ll, 'tcx>(
698    cx: &CodegenCx<'ll, 'tcx>,
699    float_ty: Ty<'tcx>,
700    bits_ty: Ty<'tcx>,
701    bits_names: &[&str],
702) -> DINodeCreationResult<'ll> {
703    if true {
    if !#[allow(non_exhaustive_omitted_patterns)] match bits_ty.kind() {
                ty::Uint(_) => true,
                _ => false,
            } {
        ::core::panicking::panic("assertion failed: matches!(bits_ty.kind(), ty::Uint(_))")
    };
};debug_assert!(matches!(bits_ty.kind(), ty::Uint(_)));
704    if true {
    {
        match (&(cx.size_of(bits_ty) * (bits_names.len() as u64)),
                &cx.size_of(float_ty)) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(cx.size_of(bits_ty) * (bits_names.len() as u64), cx.size_of(float_ty));
705    // MSVC has no native support for `f16` or `f128`. Instead, emit a struct containing the bits as
706    // field(s) to allow the value to be displayed using a Natvis visualiser in `intrinsic.natvis`.
707    let name = if let ty::Float(f) = float_ty.kind() {
708        f.name_str()
709    } else {
710        ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} was not a float", float_ty), Location::caller());bug!("{float_ty:?} was not a float");
711    };
712    type_map::build_type_with_children(
713        cx,
714        type_map::stub(
715            cx,
716            Stub::Struct,
717            UniqueTypeId::for_ty(cx.tcx, float_ty),
718            name,
719            None,
720            cx.size_and_align_of(float_ty),
721            NO_SCOPE_METADATA,
722            DIFlags::FlagZero,
723        ),
724        // Fields:
725        |cx, float_di_node| {
726            let bits_layout = cx.layout_of(bits_ty);
727            let bits_node = type_di_node(cx, bits_ty);
728            bits_names
729                .iter()
730                .copied()
731                .enumerate()
732                .map(|(i, field_name)| {
733                    build_field_di_node(
734                        cx,
735                        float_di_node,
736                        field_name,
737                        bits_layout,
738                        bits_layout.size * (i as u64),
739                        DIFlags::FlagZero,
740                        bits_node,
741                        None,
742                    )
743                })
744                .collect()
745        },
746        NO_GENERICS,
747    )
748}
749
750fn build_basic_type_di_node<'ll, 'tcx>(
751    cx: &CodegenCx<'ll, 'tcx>,
752    t: Ty<'tcx>,
753) -> DINodeCreationResult<'ll> {
754    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:754",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(754u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_basic_type_di_node: {0:?}",
                                                    t) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_basic_type_di_node: {:?}", t);
755
756    // When targeting MSVC, emit MSVC style type names for compatibility with
757    // .natvis visualizers (and perhaps other existing native debuggers?)
758    let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
759
760    use dwarf_const::{DW_ATE_UTF, DW_ATE_boolean, DW_ATE_float, DW_ATE_signed, DW_ATE_unsigned};
761
762    let (name, encoding) = match t.kind() {
763        ty::Never => ("!", DW_ATE_unsigned),
764        ty::Tuple(elements) if elements.is_empty() => {
765            if cpp_like_debuginfo {
766                return build_tuple_type_di_node(cx, UniqueTypeId::for_ty(cx.tcx, t));
767            } else {
768                ("()", DW_ATE_unsigned)
769            }
770        }
771        ty::Bool => ("bool", DW_ATE_boolean),
772        ty::Char => ("char", DW_ATE_UTF),
773        ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
774        ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
775        ty::Float(ty::FloatTy::F16) if cpp_like_debuginfo => {
776            return build_cpp_float_struct_di_node(cx, t, cx.tcx.types.u16, &["bits"]);
777        }
778        ty::Float(ty::FloatTy::F128) if cpp_like_debuginfo => {
779            // All MSVC architectures are little endian.
780            {
    match (&cx.target_spec().endian, &Endian::Little) {
        (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!(cx.target_spec().endian, Endian::Little);
781            return build_cpp_float_struct_di_node(
782                cx,
783                t,
784                cx.tcx.types.u64,
785                &["low_bits", "high_bits"],
786            );
787        }
788        ty::Float(ty::FloatTy::F32) if cpp_like_debuginfo => ("float", DW_ATE_float),
789        ty::Float(ty::FloatTy::F64) if cpp_like_debuginfo => ("double", DW_ATE_float),
790        ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
791        ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
792        ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
793        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("debuginfo::build_basic_type_di_node - `t` is invalid type"),
    Location::caller())bug!("debuginfo::build_basic_type_di_node - `t` is invalid type"),
794    };
795
796    // Around LLDB 21 or 22, LLDB started using prebuilt Clang type nodes for primitives rather than
797    // reading the full DWARF data. These nodes are based on the size and signedness of the
798    // primitive, and ignore pretty much all other fields. This causes 2 issues:
799    // 1. type names get normalized to C-style names which isn't ideal. The normalization occurs
800    // even in generic args.
801    // 2. if you have a generic type `S<T>`, and 2 instantiations are `S<u64>`
802    // and `S<usize>` (on a 64-bit target), the use of prebuilt nodes causes a name collision.
803    // Whichever instantiation is interacted with first will work fine, all others will break a
804    // bunch of stuff in the LLDB pipeline. To avoid this, we explicitly treat `usize` and `isize`
805    // as typedefs of their equivalent types. For more info see: llvm/llvm-project#196812
806
807    let mut needs_typedef = cpp_like_debuginfo;
808
809    let ty_di_node = match t.kind() {
810        ty::Uint(UintTy::Usize) => {
811            needs_typedef = true;
812
813            let equivalent = match t.primitive_size(cx.tcx).bits() {
814                8 => cx.tcx.types.u8,
815                16 => cx.tcx.types.u16,
816                32 => cx.tcx.types.u32,
817                64 => cx.tcx.types.u64,
818                128 => cx.tcx.types.u128,
819                x => ::rustc_span::macros::bug_impl(None,
    format_args!("Unexpected signed int size {0}", x), Location::caller())bug!("Unexpected signed int size {x}"),
820            };
821            type_di_node(cx, equivalent)
822        }
823        ty::Int(IntTy::Isize) => {
824            needs_typedef = true;
825
826            let equivalent = match t.primitive_size(cx.tcx).bits() {
827                8 => cx.tcx.types.i8,
828                16 => cx.tcx.types.i16,
829                32 => cx.tcx.types.i32,
830                64 => cx.tcx.types.i64,
831                128 => cx.tcx.types.i128,
832                x => ::rustc_span::macros::bug_impl(None,
    format_args!("Unexpected signed int size: {0}", x), Location::caller())bug!("Unexpected signed int size: {x}"),
833            };
834            type_di_node(cx, equivalent)
835        }
836        _ => create_basic_type(cx, name, cx.size_of(t), encoding),
837    };
838
839    if !needs_typedef {
840        return DINodeCreationResult::new(ty_di_node, false);
841    }
842
843    let typedef_name = match t.kind() {
844        ty::Int(int_ty) => int_ty.name_str(),
845        ty::Uint(uint_ty) => uint_ty.name_str(),
846        ty::Float(float_ty) => float_ty.name_str(),
847        _ => return DINodeCreationResult::new(ty_di_node, false),
848    };
849
850    let typedef_di_node = unsafe {
851        llvm::LLVMDIBuilderCreateTypedef(
852            DIB(cx),
853            ty_di_node,
854            typedef_name.as_ptr(),
855            typedef_name.len(),
856            unknown_file_metadata(cx),
857            0,    // (no line number)
858            None, // (no scope)
859            0u32, // (no alignment specified)
860        )
861    };
862
863    DINodeCreationResult::new(typedef_di_node, false)
864}
865
866fn create_basic_type<'ll, 'tcx>(
867    cx: &CodegenCx<'ll, 'tcx>,
868    name: &str,
869    size: Size,
870    encoding: u32,
871) -> &'ll DIBasicType {
872    unsafe {
873        llvm::LLVMDIBuilderCreateBasicType(
874            DIB(cx),
875            name.as_ptr(),
876            name.len(),
877            size.bits(),
878            encoding,
879            DIFlags::FlagZero,
880        )
881    }
882}
883
884fn build_foreign_type_di_node<'ll, 'tcx>(
885    cx: &CodegenCx<'ll, 'tcx>,
886    t: Ty<'tcx>,
887    unique_type_id: UniqueTypeId<'tcx>,
888) -> DINodeCreationResult<'ll> {
889    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:889",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(889u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_foreign_type_di_node: {0:?}",
                                                    t) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_foreign_type_di_node: {:?}", t);
890
891    let &ty::Foreign(def_id) = unique_type_id.expect_ty().kind() else {
892        ::rustc_span::macros::bug_impl(None,
    format_args!("build_foreign_type_di_node() called with unexpected type: {0:?}",
        unique_type_id.expect_ty()), Location::caller());bug!(
893            "build_foreign_type_di_node() called with unexpected type: {:?}",
894            unique_type_id.expect_ty()
895        );
896    };
897
898    build_type_with_children(
899        cx,
900        type_map::stub(
901            cx,
902            Stub::Struct,
903            unique_type_id,
904            &compute_debuginfo_type_name(cx.tcx, t, false),
905            None,
906            cx.size_and_align_of(t),
907            Some(get_namespace_for_item(cx, def_id)),
908            DIFlags::FlagZero,
909        ),
910        |_, _| ::smallvec::SmallVec::new()smallvec![],
911        NO_GENERICS,
912    )
913}
914
915pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
916    tcx: TyCtxt<'tcx>,
917    codegen_unit_name: &str,
918    debug_context: &CodegenUnitDebugContext<'ll, 'tcx>,
919) -> &'ll DIDescriptor {
920    let mut name_in_debuginfo = tcx
921        .sess
922        .local_crate_source_file()
923        .map(|src| src.path(RemapPathScopeComponents::DEBUGINFO).to_path_buf())
924        .unwrap_or_else(|| PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()));
925
926    // To avoid breaking split DWARF, we need to ensure that each codegen unit
927    // has a unique `DW_AT_name`. This is because there's a remote chance that
928    // different codegen units for the same module will have entirely
929    // identical DWARF entries for the purpose of the DWO ID, which would
930    // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
931    // specification. LLVM uses the algorithm specified in section 7.32 "Type
932    // Signature Computation" to compute the DWO ID, which does not include
933    // any fields that would distinguish compilation units. So we must embed
934    // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
935    //
936    // Additionally, the OSX linker has an idiosyncrasy where it will ignore
937    // some debuginfo if multiple object files with the same `DW_AT_name` are
938    // linked together.
939    //
940    // As a workaround for these two issues, we generate unique names for each
941    // object file. Those do not correspond to an actual source file but that
942    // is harmless.
943    name_in_debuginfo.push("@");
944    name_in_debuginfo.push(codegen_unit_name);
945
946    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs:946",
                        "rustc_codegen_llvm::debuginfo::metadata",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/63931fb6b6bc05c38a5111ed7b32fe7648d22b1c/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs"),
                        ::tracing_core::__macro_support::Option::Some(946u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo::metadata"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_compile_unit_di_node: {0:?}",
                                                    name_in_debuginfo) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo);
947    let rustc_producer = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc version {0}",
                tcx.sess.cfg_version))
    })format!("rustc version {}", tcx.sess.cfg_version);
948    // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
949    let producer = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("clang LLVM ({0})", rustc_producer))
    })format!("clang LLVM ({rustc_producer})");
950
951    let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
952    let work_dir = tcx.sess.psess.source_map().working_dir();
953    let output_filenames = tcx.output_filenames(());
954    let split_name = if tcx.sess.target_can_use_split_dwarf()
955        && let Some(f) = output_filenames.split_dwarf_path(
956            tcx.sess.split_debuginfo(),
957            tcx.sess.opts.unstable_opts.split_dwarf_kind,
958            codegen_unit_name,
959        ) {
960        // We get a path relative to the working directory from split_dwarf_path
961        Some(tcx.sess.source_map().path_mapping().to_real_filename(work_dir, f))
962    } else {
963        None
964    };
965    let split_name = split_name
966        .as_ref()
967        .map(|f| f.path(RemapPathScopeComponents::DEBUGINFO).to_string_lossy())
968        .unwrap_or_default();
969    let work_dir = work_dir.path(RemapPathScopeComponents::DEBUGINFO).to_string_lossy();
970    let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
971
972    let dwarf_version = tcx.sess.dwarf_version();
973    let is_dwarf_kind =
974        #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.target.debuginfo_kind
    {
    DebuginfoKind::Dwarf | DebuginfoKind::DwarfDsym => true,
    _ => false,
}matches!(tcx.sess.target.debuginfo_kind, DebuginfoKind::Dwarf | DebuginfoKind::DwarfDsym);
975    // Don't emit `.debug_pubnames` and `.debug_pubtypes` on DWARFv4 or lower.
976    let debug_name_table_kind = if is_dwarf_kind && dwarf_version <= 4 {
977        DebugNameTableKind::None
978    } else {
979        DebugNameTableKind::Default
980    };
981
982    unsafe {
983        let compile_unit_file = create_file(
984            debug_context.builder.as_ref(),
985            &name_in_debuginfo,
986            &work_dir,
987            "",
988            llvm::ChecksumKind::None,
989            None,
990        );
991        let flags = c"";
992
993        let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
994            debug_context.builder.as_ref(),
995            dwarf_const::DW_LANG_Rust,
996            compile_unit_file,
997            producer.as_ptr(),
998            producer.len(),
999            tcx.sess.opts.optimize != config::OptLevel::No,
1000            flags.as_ptr(),
1001            0,
1002            // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1003            // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1004            // output(s).
1005            split_name.as_ptr(),
1006            split_name.len(),
1007            kind,
1008            0,
1009            tcx.sess.opts.unstable_opts.split_dwarf_inlining,
1010            debug_name_table_kind,
1011        );
1012
1013        return unit_metadata;
1014    };
1015}
1016
1017/// Creates a `DW_TAG_member` entry inside the DIE represented by the given `type_di_node`.
1018fn build_field_di_node<'ll, 'tcx>(
1019    cx: &CodegenCx<'ll, 'tcx>,
1020    owner: &'ll DIScope,
1021    name: &str,
1022    layout: TyAndLayout<'tcx>,
1023    offset: Size,
1024    flags: DIFlags,
1025    type_di_node: &'ll DIType,
1026    def_id: Option<DefId>,
1027) -> &'ll DIType {
1028    let (file_metadata, line_number) = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers
1029    {
1030        file_metadata_from_def_id(cx, def_id)
1031    } else {
1032        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1033    };
1034    create_member_type(
1035        cx,
1036        owner,
1037        name,
1038        file_metadata,
1039        line_number,
1040        layout,
1041        offset,
1042        flags,
1043        type_di_node,
1044    )
1045}
1046
1047fn create_member_type<'ll, 'tcx>(
1048    cx: &CodegenCx<'ll, 'tcx>,
1049    owner: &'ll DIScope,
1050    name: &str,
1051    file_metadata: &'ll DIType,
1052    line_number: u32,
1053    layout: TyAndLayout<'tcx>,
1054    offset: Size,
1055    flags: DIFlags,
1056    type_di_node: &'ll DIType,
1057) -> &'ll DIType {
1058    unsafe {
1059        llvm::LLVMDIBuilderCreateMemberType(
1060            DIB(cx),
1061            owner,
1062            name.as_ptr(),
1063            name.len(),
1064            file_metadata,
1065            line_number,
1066            layout.size.bits(),
1067            layout.align.bits() as u32,
1068            offset.bits(),
1069            flags,
1070            type_di_node,
1071        )
1072    }
1073}
1074
1075/// Returns the `DIFlags` corresponding to the visibility of the item identified by `did`.
1076///
1077/// `DIFlags::Flag{Public,Protected,Private}` correspond to `DW_AT_accessibility`
1078/// (public/protected/private) aren't exactly right for Rust, but neither is `DW_AT_visibility`
1079/// (local/exported/qualified), and there's no way to set `DW_AT_visibility` in LLVM's API.
1080fn visibility_di_flags<'ll, 'tcx>(
1081    cx: &CodegenCx<'ll, 'tcx>,
1082    did: DefId,
1083    type_did: DefId,
1084) -> DIFlags {
1085    let parent_did = cx.tcx.parent(type_did);
1086    let visibility = cx.tcx.visibility(did);
1087    match visibility {
1088        Visibility::Public => DIFlags::FlagPublic,
1089        // Private fields have a restricted visibility of the module containing the type.
1090        Visibility::Restricted(did) if did.to_def_id() == parent_did => DIFlags::FlagPrivate,
1091        // `pub(crate)`/`pub(super)` visibilities are any other restricted visibility.
1092        Visibility::Restricted(..) => DIFlags::FlagProtected,
1093    }
1094}
1095
1096/// Creates the debuginfo node for a Rust struct type. Maybe be a regular struct or a tuple-struct.
1097fn build_struct_type_di_node<'ll, 'tcx>(
1098    cx: &CodegenCx<'ll, 'tcx>,
1099    unique_type_id: UniqueTypeId<'tcx>,
1100    span: Span,
1101) -> DINodeCreationResult<'ll> {
1102    let struct_type = unique_type_id.expect_ty();
1103
1104    let ty::Adt(adt_def, _) = struct_type.kind() else {
1105        ::rustc_span::macros::bug_impl(None,
    format_args!("build_struct_type_di_node() called with non-struct-type: {0:?}",
        struct_type), Location::caller());bug!("build_struct_type_di_node() called with non-struct-type: {:?}", struct_type);
1106    };
1107    if !adt_def.is_struct() {
    ::core::panicking::panic("assertion failed: adt_def.is_struct()")
};assert!(adt_def.is_struct());
1108    let containing_scope = get_namespace_for_item(cx, adt_def.did());
1109    let struct_type_and_layout = cx.spanned_layout_of(struct_type, span);
1110    let variant_def = adt_def.non_enum_variant();
1111    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1112        Some(file_metadata_from_def_id(cx, Some(adt_def.did())))
1113    } else {
1114        None
1115    };
1116    let name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1117
1118    if struct_type.is_scalable_vector() {
1119        let parts = struct_type.scalable_vector_parts(cx.tcx).unwrap();
1120        return build_scalable_vector_di_node(
1121            cx,
1122            unique_type_id,
1123            name,
1124            *adt_def,
1125            parts,
1126            struct_type_and_layout.layout,
1127            def_location,
1128            containing_scope,
1129        );
1130    }
1131
1132    type_map::build_type_with_children(
1133        cx,
1134        type_map::stub(
1135            cx,
1136            Stub::Struct,
1137            unique_type_id,
1138            &name,
1139            def_location,
1140            size_and_align_of(struct_type_and_layout),
1141            Some(containing_scope),
1142            visibility_di_flags(cx, adt_def.did(), adt_def.did()),
1143        ),
1144        // Fields:
1145        |cx, owner| {
1146            variant_def
1147                .fields
1148                .iter()
1149                .enumerate()
1150                .map(|(i, f)| {
1151                    let field_name = if variant_def.ctor_kind() == Some(CtorKind::Fn) {
1152                        // This is a tuple struct
1153                        tuple_field_name(i)
1154                    } else {
1155                        // This is struct with named fields
1156                        Cow::Borrowed(f.name.as_str())
1157                    };
1158                    let field_layout = struct_type_and_layout.field(cx, i);
1159                    let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1160                        Some(f.did)
1161                    } else {
1162                        None
1163                    };
1164                    build_field_di_node(
1165                        cx,
1166                        owner,
1167                        &field_name[..],
1168                        field_layout,
1169                        struct_type_and_layout.fields.offset(i),
1170                        visibility_di_flags(cx, f.did, adt_def.did()),
1171                        type_di_node(cx, field_layout.ty),
1172                        def_id,
1173                    )
1174                })
1175                .collect()
1176        },
1177        |cx| build_generic_type_param_di_nodes(cx, struct_type),
1178    )
1179}
1180
1181/// Generate debuginfo for a `#[rustc_scalable_vector]` type.
1182///
1183/// Debuginfo for a scalable vector uses a derived type based on a composite type. The composite
1184/// type has the  `DIFlagVector` flag set and is based on the element type of the scalable vector.
1185/// The composite type has a subrange from 0 to an expression that calculates the number of
1186/// elements in the vector.
1187///
1188/// ```text,ignore
1189/// !1 = !DIDerivedType(tag: DW_TAG_typedef, name: "svint16_t", ..., baseType: !2, ...)
1190/// !2 = !DICompositeType(tag: DW_TAG_array_type, baseType: !3, ..., flags: DIFlagVector, elements: !4)
1191/// !3 = !DIBasicType(name: "i16", size: 16, encoding: DW_ATE_signed)
1192/// !4 = !{!5}
1193/// !5 = !DISubrange(lowerBound: 0, upperBound: !DIExpression(DW_OP_constu, 4, DW_OP_bregx, 46, 0, DW_OP_mul, DW_OP_constu, 1, DW_OP_minus))
1194/// ```
1195///
1196/// See the `CodegenType::CreateType(const BuiltinType *BT)` implementation in Clang for how this
1197/// is generated for C and C++.
1198fn build_scalable_vector_di_node<'ll, 'tcx>(
1199    cx: &CodegenCx<'ll, 'tcx>,
1200    unique_type_id: UniqueTypeId<'tcx>,
1201    name: String,
1202    adt_def: AdtDef<'tcx>,
1203    (element_count, element_ty, number_of_vectors): (u16, Ty<'tcx>, NumScalableVectors),
1204    layout: Layout<'tcx>,
1205    def_location: Option<DefinitionLocation<'ll>>,
1206    containing_scope: &'ll DIScope,
1207) -> DINodeCreationResult<'ll> {
1208    use dwarf_const::{DW_OP_bregx, DW_OP_constu, DW_OP_minus, DW_OP_mul};
1209    if !adt_def.repr().scalable() {
    ::core::panicking::panic("assertion failed: adt_def.repr().scalable()")
};assert!(adt_def.repr().scalable());
1210    // This logic is specific to AArch64 for the moment, but can be extended for other architectures
1211    // later.
1212    {
    match cx.tcx.sess.target.arch {
        Arch::AArch64 => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Arch::AArch64", ::core::option::Option::None);
        }
    }
};assert_matches!(cx.tcx.sess.target.arch, Arch::AArch64);
1213
1214    let (file_metadata, line_number) = if let Some(def_location) = def_location {
1215        (def_location.0, def_location.1)
1216    } else {
1217        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1218    };
1219
1220    let (bitstride, element_di_node) = if element_ty.is_bool() {
1221        (Some(llvm::LLVMValueAsMetadata(cx.const_i64(1))), type_di_node(cx, cx.tcx.types.u8))
1222    } else {
1223        (None, type_di_node(cx, element_ty))
1224    };
1225
1226    let number_of_elements: u64 = (element_count as u64) * (number_of_vectors.0 as u64);
1227    let number_of_elements_per_vg = number_of_elements / 2;
1228    let mut expr = smallvec::SmallVec::<[u64; 9]>::new();
1229    // `($number_of_elements_per_vector_granule * (value_of_register(AArch64::VG) + 0)) - 1`
1230    expr.push(DW_OP_constu); // Push a constant onto the stack
1231    expr.push(number_of_elements_per_vg);
1232    expr.push(DW_OP_bregx); // Push the value of a register + offset on to the stack
1233    expr.push(/* AArch64::VG */ 46u64);
1234    expr.push(0u64);
1235    expr.push(DW_OP_mul); // Multiply top two values on stack
1236    expr.push(DW_OP_constu); // Push a constant onto the stack
1237    expr.push(1u64);
1238    expr.push(DW_OP_minus); // Subtract top two values on stack
1239
1240    let di_builder = DIB(cx);
1241    let metadata = unsafe {
1242        let upper = llvm::LLVMDIBuilderCreateExpression(di_builder, expr.as_ptr(), expr.len());
1243        let subrange = llvm::LLVMRustDIGetOrCreateSubrange(
1244            di_builder,
1245            /* CountNode */ None,
1246            llvm::LLVMValueAsMetadata(cx.const_i64(0)),
1247            upper,
1248            /* Stride */ None,
1249        );
1250        let subscripts = create_DIArray(di_builder, &[Some(subrange)]);
1251        let vector_ty = llvm::LLVMRustDICreateVectorType(
1252            di_builder,
1253            /* Size */ 0,
1254            layout.align.bits() as u32,
1255            element_di_node,
1256            subscripts,
1257            bitstride,
1258        );
1259        llvm::LLVMDIBuilderCreateTypedef(
1260            di_builder,
1261            vector_ty,
1262            name.as_ptr(),
1263            name.len(),
1264            file_metadata,
1265            line_number,
1266            Some(containing_scope),
1267            layout.align.bits() as u32,
1268        )
1269    };
1270
1271    debug_context(cx).type_map.insert(unique_type_id, metadata);
1272    DINodeCreationResult { di_node: metadata, already_stored_in_typemap: true }
1273}
1274
1275//=-----------------------------------------------------------------------------
1276// Tuples
1277//=-----------------------------------------------------------------------------
1278
1279/// Builds the DW_TAG_member debuginfo nodes for the upvars of a closure or coroutine.
1280/// For a coroutine, this will handle upvars shared by all states.
1281fn build_upvar_field_di_nodes<'ll, 'tcx>(
1282    cx: &CodegenCx<'ll, 'tcx>,
1283    closure_or_coroutine_ty: Ty<'tcx>,
1284    closure_or_coroutine_di_node: &'ll DIType,
1285) -> SmallVec<&'ll DIType> {
1286    let (&def_id, up_var_tys) = match closure_or_coroutine_ty.kind() {
1287        ty::Coroutine(def_id, args) => (def_id, args.as_coroutine().upvar_tys()),
1288        ty::Closure(def_id, args) => (def_id, args.as_closure().upvar_tys()),
1289        ty::CoroutineClosure(def_id, args) => (def_id, args.as_coroutine_closure().upvar_tys()),
1290        _ => {
1291            ::rustc_span::macros::bug_impl(None,
    format_args!("build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {0:?}",
        closure_or_coroutine_ty), Location::caller())bug!(
1292                "build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {:?}",
1293                closure_or_coroutine_ty
1294            )
1295        }
1296    };
1297
1298    for ty in up_var_tys.iter() {
1299        cx.tcx.assert_fully_normalized(cx.typing_env(), ty);
1300    }
1301
1302    let capture_names = cx.tcx.closure_saved_names_of_captured_variables(def_id);
1303    let layout = cx.layout_of(closure_or_coroutine_ty);
1304
1305    up_var_tys
1306        .into_iter()
1307        .zip(capture_names.iter())
1308        .enumerate()
1309        .map(|(index, (up_var_ty, capture_name))| {
1310            build_field_di_node(
1311                cx,
1312                closure_or_coroutine_di_node,
1313                capture_name.as_str(),
1314                cx.layout_of(up_var_ty),
1315                layout.fields.offset(index),
1316                DIFlags::FlagZero,
1317                type_di_node(cx, up_var_ty),
1318                None,
1319            )
1320        })
1321        .collect()
1322}
1323
1324/// Builds the DW_TAG_structure_type debuginfo node for a Rust tuple type.
1325fn build_tuple_type_di_node<'ll, 'tcx>(
1326    cx: &CodegenCx<'ll, 'tcx>,
1327    unique_type_id: UniqueTypeId<'tcx>,
1328) -> DINodeCreationResult<'ll> {
1329    let tuple_type = unique_type_id.expect_ty();
1330    let &ty::Tuple(component_types) = tuple_type.kind() else {
1331        ::rustc_span::macros::bug_impl(None,
    format_args!("build_tuple_type_di_node() called with non-tuple-type: {0:?}",
        tuple_type), Location::caller())bug!("build_tuple_type_di_node() called with non-tuple-type: {:?}", tuple_type)
1332    };
1333
1334    let tuple_type_and_layout = cx.layout_of(tuple_type);
1335    let type_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1336
1337    type_map::build_type_with_children(
1338        cx,
1339        type_map::stub(
1340            cx,
1341            Stub::Struct,
1342            unique_type_id,
1343            &type_name,
1344            None,
1345            size_and_align_of(tuple_type_and_layout),
1346            NO_SCOPE_METADATA,
1347            DIFlags::FlagZero,
1348        ),
1349        // Fields:
1350        |cx, tuple_di_node| {
1351            component_types
1352                .into_iter()
1353                .enumerate()
1354                .map(|(index, component_type)| {
1355                    build_field_di_node(
1356                        cx,
1357                        tuple_di_node,
1358                        &tuple_field_name(index),
1359                        cx.layout_of(component_type),
1360                        tuple_type_and_layout.fields.offset(index),
1361                        DIFlags::FlagZero,
1362                        type_di_node(cx, component_type),
1363                        None,
1364                    )
1365                })
1366                .collect()
1367        },
1368        NO_GENERICS,
1369    )
1370}
1371
1372/// Builds the debuginfo node for a closure environment.
1373fn build_closure_env_di_node<'ll, 'tcx>(
1374    cx: &CodegenCx<'ll, 'tcx>,
1375    unique_type_id: UniqueTypeId<'tcx>,
1376) -> DINodeCreationResult<'ll> {
1377    let closure_env_type = unique_type_id.expect_ty();
1378    let &(ty::Closure(def_id, _) | ty::CoroutineClosure(def_id, _)) = closure_env_type.kind()
1379    else {
1380        ::rustc_span::macros::bug_impl(None,
    format_args!("build_closure_env_di_node() called with non-closure-type: {0:?}",
        closure_env_type), Location::caller())bug!("build_closure_env_di_node() called with non-closure-type: {:?}", closure_env_type)
1381    };
1382    let containing_scope = get_namespace_for_item(cx, def_id);
1383    let type_name = compute_debuginfo_type_name(cx.tcx, closure_env_type, false);
1384
1385    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1386        Some(file_metadata_from_def_id(cx, Some(def_id)))
1387    } else {
1388        None
1389    };
1390
1391    type_map::build_type_with_children(
1392        cx,
1393        type_map::stub(
1394            cx,
1395            Stub::Struct,
1396            unique_type_id,
1397            &type_name,
1398            def_location,
1399            cx.size_and_align_of(closure_env_type),
1400            Some(containing_scope),
1401            DIFlags::FlagZero,
1402        ),
1403        // Fields:
1404        |cx, owner| build_upvar_field_di_nodes(cx, closure_env_type, owner),
1405        NO_GENERICS,
1406    )
1407}
1408
1409/// Build the debuginfo node for a Rust `union` type.
1410fn build_union_type_di_node<'ll, 'tcx>(
1411    cx: &CodegenCx<'ll, 'tcx>,
1412    unique_type_id: UniqueTypeId<'tcx>,
1413    span: Span,
1414) -> DINodeCreationResult<'ll> {
1415    let union_type = unique_type_id.expect_ty();
1416    let (union_def_id, variant_def) = match union_type.kind() {
1417        ty::Adt(def, _) => (def.did(), def.non_enum_variant()),
1418        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("build_union_type_di_node on a non-ADT"), Location::caller())bug!("build_union_type_di_node on a non-ADT"),
1419    };
1420    let containing_scope = get_namespace_for_item(cx, union_def_id);
1421    let union_ty_and_layout = cx.spanned_layout_of(union_type, span);
1422    let type_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1423    let def_location = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1424        Some(file_metadata_from_def_id(cx, Some(union_def_id)))
1425    } else {
1426        None
1427    };
1428
1429    type_map::build_type_with_children(
1430        cx,
1431        type_map::stub(
1432            cx,
1433            Stub::Union,
1434            unique_type_id,
1435            &type_name,
1436            def_location,
1437            size_and_align_of(union_ty_and_layout),
1438            Some(containing_scope),
1439            DIFlags::FlagZero,
1440        ),
1441        // Fields:
1442        |cx, owner| {
1443            variant_def
1444                .fields
1445                .iter()
1446                .enumerate()
1447                .map(|(i, f)| {
1448                    let field_layout = union_ty_and_layout.field(cx, i);
1449                    let def_id = if cx.sess().opts.unstable_opts.debug_info_type_line_numbers {
1450                        Some(f.did)
1451                    } else {
1452                        None
1453                    };
1454                    build_field_di_node(
1455                        cx,
1456                        owner,
1457                        f.name.as_str(),
1458                        field_layout,
1459                        Size::ZERO,
1460                        DIFlags::FlagZero,
1461                        type_di_node(cx, field_layout.ty),
1462                        def_id,
1463                    )
1464                })
1465                .collect()
1466        },
1467        // Generics:
1468        |cx| build_generic_type_param_di_nodes(cx, union_type),
1469    )
1470}
1471
1472/// Computes the type parameters for a type, if any, for the given metadata.
1473fn build_generic_type_param_di_nodes<'ll, 'tcx>(
1474    cx: &CodegenCx<'ll, 'tcx>,
1475    ty: Ty<'tcx>,
1476) -> SmallVec<Option<&'ll DIType>> {
1477    if let ty::Adt(def, args) = *ty.kind() {
1478        // FIXME: also do consts?
1479        if args.types().next().is_some() {
1480            let generics = cx.tcx.generics_of(def.did());
1481            let names = get_parameter_names(cx, generics);
1482            let template_params: SmallVec<_> = iter::zip(args, names)
1483                .filter_map(|(kind, name)| {
1484                    kind.as_type().map(|ty| {
1485                        let actual_type = cx
1486                            .tcx
1487                            .normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(ty));
1488                        let actual_type_di_node = type_di_node(cx, actual_type);
1489                        Some(cx.create_template_type_parameter(name.as_str(), actual_type_di_node))
1490                    })
1491                })
1492                .collect();
1493
1494            return template_params;
1495        }
1496    }
1497
1498    return ::smallvec::SmallVec::new()smallvec![];
1499
1500    fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
1501        let mut names = generics
1502            .parent
1503            .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
1504        names.extend(generics.own_params.iter().map(|param| param.name));
1505        names
1506    }
1507}
1508
1509/// Creates debug information for the given global variable.
1510///
1511/// Adds the created debuginfo nodes directly to the crate's IR.
1512pub(crate) fn build_global_var_di_node<'ll>(
1513    cx: &CodegenCx<'ll, '_>,
1514    def_id: DefId,
1515    global: &'ll Value,
1516) {
1517    if cx.dbg_cx.is_none() {
1518        return;
1519    }
1520
1521    // Only create type information if full debuginfo is enabled
1522    if cx.sess().opts.debuginfo != DebugInfo::Full {
1523        return;
1524    }
1525
1526    let tcx = cx.tcx;
1527
1528    // We may want to remove the namespace scope if we're in an extern block (see
1529    // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
1530    let var_scope = get_namespace_for_item(cx, def_id);
1531    let (file_metadata, line_number) = file_metadata_from_def_id(cx, Some(def_id));
1532
1533    let is_local_to_unit = is_node_local_to_unit(cx, def_id);
1534
1535    let DefKind::Static { nested, .. } = cx.tcx.def_kind(def_id) else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!() };
1536    if nested {
1537        return;
1538    }
1539    let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, cx.typing_env());
1540    let type_di_node = type_di_node(cx, variable_type);
1541    let var_name = tcx.item_name(def_id);
1542    let var_name = var_name.as_str();
1543    let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
1544    // When empty, linkage_name field is omitted,
1545    // which is what we want for no_mangle statics
1546    let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
1547
1548    let global_align = cx.align_of(variable_type);
1549
1550    DIB(cx).create_static_variable(
1551        Some(var_scope),
1552        var_name,
1553        linkage_name,
1554        file_metadata,
1555        line_number,
1556        type_di_node,
1557        is_local_to_unit,
1558        global, // (value)
1559        None,   // (decl)
1560        Some(global_align),
1561    );
1562}
1563
1564/// Generates LLVM debuginfo for a vtable.
1565///
1566/// The vtable type looks like a struct with a field for each function pointer and super-trait
1567/// pointer it contains (plus the `size` and `align` fields).
1568///
1569/// Except for `size`, `align`, and `drop_in_place`, the field names don't try to mirror
1570/// the name of the method they implement. This can be implemented in the future once there
1571/// is a proper disambiguation scheme for dealing with methods from different traits that have
1572/// the same name.
1573fn build_vtable_type_di_node<'ll, 'tcx>(
1574    cx: &CodegenCx<'ll, 'tcx>,
1575    ty: Ty<'tcx>,
1576    poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1577) -> &'ll DIType {
1578    let tcx = cx.tcx;
1579
1580    let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
1581        let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
1582        let trait_ref = tcx.erase_and_anonymize_regions(trait_ref);
1583
1584        tcx.vtable_entries(trait_ref)
1585    } else {
1586        TyCtxt::COMMON_VTABLE_ENTRIES
1587    };
1588
1589    // All function pointers are described as opaque pointers. This could be improved in the future
1590    // by describing them as actual function pointers.
1591    let void_pointer_ty = Ty::new_imm_ptr(tcx, tcx.types.unit);
1592    let void_pointer_type_di_node = type_di_node(cx, void_pointer_ty);
1593    let usize_di_node = type_di_node(cx, tcx.types.usize);
1594    let pointer_layout = cx.layout_of(void_pointer_ty);
1595    let pointer_size = pointer_layout.size;
1596    let pointer_align = pointer_layout.align;
1597    // If `usize` is not pointer-sized and -aligned then the size and alignment computations
1598    // for the vtable as a whole would be wrong. Let's make sure this holds even on weird
1599    // platforms.
1600    {
    match (&cx.size_and_align_of(tcx.types.usize),
            &(pointer_size, pointer_align)) {
        (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!(cx.size_and_align_of(tcx.types.usize), (pointer_size, pointer_align));
1601
1602    let vtable_type_name =
1603        compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
1604    let unique_type_id = UniqueTypeId::for_vtable_ty(tcx, ty, poly_trait_ref);
1605    let size = pointer_size * vtable_entries.len() as u64;
1606
1607    // This gets mapped to a DW_AT_containing_type attribute which allows GDB to correlate
1608    // the vtable to the type it is for.
1609    let vtable_holder = type_di_node(cx, ty);
1610
1611    build_type_with_children(
1612        cx,
1613        type_map::stub(
1614            cx,
1615            Stub::VTableTy { vtable_holder },
1616            unique_type_id,
1617            &vtable_type_name,
1618            None,
1619            (size, pointer_align),
1620            NO_SCOPE_METADATA,
1621            DIFlags::FlagArtificial,
1622        ),
1623        |cx, vtable_type_di_node| {
1624            vtable_entries
1625                .iter()
1626                .enumerate()
1627                .filter_map(|(index, vtable_entry)| {
1628                    let (field_name, field_type_di_node) = match vtable_entry {
1629                        ty::VtblEntry::MetadataDropInPlace => {
1630                            ("drop_in_place".to_string(), void_pointer_type_di_node)
1631                        }
1632                        ty::VtblEntry::Method(_) => {
1633                            // Note: This code does not try to give a proper name to each method
1634                            //       because their might be multiple methods with the same name
1635                            //       (coming from different traits).
1636                            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__method{0}", index))
    })format!("__method{index}"), void_pointer_type_di_node)
1637                        }
1638                        ty::VtblEntry::TraitVPtr(_) => {
1639                            (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__super_trait_ptr{0}", index))
    })format!("__super_trait_ptr{index}"), void_pointer_type_di_node)
1640                        }
1641                        ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_di_node),
1642                        ty::VtblEntry::MetadataSize => ("size".to_string(), usize_di_node),
1643                        ty::VtblEntry::Vacant => return None,
1644                    };
1645
1646                    let field_offset = pointer_size * index as u64;
1647
1648                    Some(build_field_di_node(
1649                        cx,
1650                        vtable_type_di_node,
1651                        &field_name,
1652                        pointer_layout,
1653                        field_offset,
1654                        DIFlags::FlagZero,
1655                        field_type_di_node,
1656                        None,
1657                    ))
1658                })
1659                .collect()
1660        },
1661        NO_GENERICS,
1662    )
1663    .di_node
1664}
1665
1666/// Creates the debuginfo node for `unsafe<'a> T` binder types.
1667///
1668/// We treat an unsafe binder like a struct with a single field named `inner`
1669/// rather than delegating to the inner type's DI node directly. This way the
1670/// debugger shows the binder's own type name, and the wrapped value is still
1671/// accessible through the `inner` field.
1672fn build_unsafe_binder_type_di_node<'ll, 'tcx>(
1673    cx: &CodegenCx<'ll, 'tcx>,
1674    binder_type: Ty<'tcx>,
1675    unique_type_id: UniqueTypeId<'tcx>,
1676) -> DINodeCreationResult<'ll> {
1677    let ty::UnsafeBinder(inner) = binder_type.kind() else {
1678        ::rustc_span::macros::bug_impl(None,
    format_args!("Only ty::UnsafeBinder is valid for build_unsafe_binder_type_di_node. Found {0:?} instead.",
        binder_type), Location::caller())bug!(
1679            "Only ty::UnsafeBinder is valid for build_unsafe_binder_type_di_node. Found {:?} instead.",
1680            binder_type
1681        )
1682    };
1683    let inner_type = cx.tcx.instantiate_bound_regions_with_erased((*inner).into());
1684    let inner_type_di_node = type_di_node(cx, inner_type);
1685
1686    let type_name = compute_debuginfo_type_name(cx.tcx, binder_type, true);
1687    type_map::build_type_with_children(
1688        cx,
1689        type_map::stub(
1690            cx,
1691            Stub::Struct,
1692            unique_type_id,
1693            &type_name,
1694            None,
1695            cx.size_and_align_of(binder_type),
1696            NO_SCOPE_METADATA,
1697            DIFlags::FlagZero,
1698        ),
1699        |cx, unsafe_binder_type_di_node| {
1700            let inner_layout = cx.layout_of(inner_type);
1701            {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(build_field_di_node(cx, unsafe_binder_type_di_node, "inner",
                inner_layout, Size::ZERO, DIFlags::FlagZero,
                inner_type_di_node, None));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [build_field_di_node(cx, unsafe_binder_type_di_node,
                                "inner", inner_layout, Size::ZERO, DIFlags::FlagZero,
                                inner_type_di_node, None)])))
    }
}smallvec![build_field_di_node(
1702                cx,
1703                unsafe_binder_type_di_node,
1704                "inner",
1705                inner_layout,
1706                Size::ZERO,
1707                DIFlags::FlagZero,
1708                inner_type_di_node,
1709                None,
1710            )]
1711        },
1712        NO_GENERICS,
1713    )
1714}
1715
1716/// Get the global variable for the vtable.
1717///
1718/// When using global variables, we may have created an addrspacecast to get a pointer to the
1719/// default address space if global variables are created in a different address space.
1720/// For modifying the vtable, we need the real global variable. This function accepts either a
1721/// global variable (which is simply returned), or an addrspacecast constant expression.
1722/// If the given value is an addrspacecast, the cast is removed and the global variable behind
1723/// the cast is returned.
1724fn find_vtable_behind_cast<'ll>(vtable: &'ll Value) -> &'ll Value {
1725    // The vtable is a global variable, which may be behind an addrspacecast.
1726    unsafe {
1727        if let Some(c) = llvm::LLVMIsAConstantExpr(vtable) {
1728            if llvm::LLVMGetConstOpcode(c) == llvm::Opcode::AddrSpaceCast {
1729                return llvm::LLVMGetOperand(c, 0).unwrap();
1730            }
1731        }
1732    }
1733    vtable
1734}
1735
1736pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>(
1737    cx: &CodegenCx<'ll, 'tcx>,
1738    ty: Ty<'tcx>,
1739    trait_ref: Option<ExistentialTraitRef<'tcx>>,
1740    vtable: &'ll Value,
1741) {
1742    // FIXME(flip1995): The virtual function elimination optimization only works with full LTO in
1743    // LLVM at the moment.
1744    if !cx.sess().opts.unstable_opts.virtual_function_elimination || cx.sess().lto() != Lto::Fat {
1745        return;
1746    }
1747
1748    enum VCallVisibility {
1749        Public = 0,
1750        LinkageUnit = 1,
1751        TranslationUnit = 2,
1752    }
1753
1754    let Some(trait_ref) = trait_ref else { return };
1755
1756    // Unwrap potential addrspacecast
1757    let vtable = find_vtable_behind_cast(vtable);
1758    let trait_ref_self = trait_ref.with_self_ty(cx.tcx, ty);
1759    let trait_def_id = trait_ref_self.def_id;
1760    let trait_vis = cx.tcx.visibility(trait_def_id);
1761
1762    let cgus = cx.sess().codegen_units().as_usize();
1763    let single_cgu = cgus == 1;
1764
1765    let lto = cx.sess().lto();
1766
1767    // Since LLVM requires full LTO for the virtual function elimination optimization to apply,
1768    // only the `Lto::Fat` cases are relevant currently.
1769    let vcall_visibility = match (lto, trait_vis, single_cgu) {
1770        // If there is not LTO and the visibility in public, we have to assume that the vtable can
1771        // be seen from anywhere. With multiple CGUs, the vtable is quasi-public.
1772        (Lto::No | Lto::ThinLocal, Visibility::Public, _)
1773        | (Lto::No, Visibility::Restricted(_), false) => VCallVisibility::Public,
1774        // With LTO and a quasi-public visibility, the usages of the functions of the vtable are
1775        // all known by the `LinkageUnit`.
1776        // FIXME: LLVM only supports this optimization for `Lto::Fat` currently. Once it also
1777        // supports `Lto::Thin` the `VCallVisibility` may have to be adjusted for those.
1778        (Lto::Fat | Lto::Thin, Visibility::Public, _)
1779        | (Lto::ThinLocal | Lto::Thin | Lto::Fat, Visibility::Restricted(_), false) => {
1780            VCallVisibility::LinkageUnit
1781        }
1782        // If there is only one CGU, private vtables can only be seen by that CGU/translation unit
1783        // and therefore we know of all usages of functions in the vtable.
1784        (_, Visibility::Restricted(_), true) => VCallVisibility::TranslationUnit,
1785    };
1786
1787    let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref);
1788    let typeid = cx.create_metadata(trait_ref_typeid.as_bytes());
1789
1790    let type_ = [llvm::LLVMValueAsMetadata(cx.const_usize(0)), typeid];
1791    cx.global_add_metadata_node(vtable, llvm::MD_type, &type_);
1792
1793    let vcall_visibility = [llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64))];
1794    cx.global_set_metadata_node(vtable, llvm::MD_vcall_visibility, &vcall_visibility);
1795}
1796
1797/// Creates debug information for the given vtable, which is for the
1798/// given type.
1799///
1800/// Adds the created metadata nodes directly to the crate's IR.
1801pub(crate) fn create_vtable_di_node<'ll, 'tcx>(
1802    cx: &CodegenCx<'ll, 'tcx>,
1803    ty: Ty<'tcx>,
1804    poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
1805    vtable: &'ll Value,
1806) {
1807    if cx.dbg_cx.is_none() {
1808        return;
1809    }
1810
1811    // Only create type information if full debuginfo is enabled
1812    if cx.sess().opts.debuginfo != DebugInfo::Full {
1813        return;
1814    }
1815
1816    // Unwrap potential addrspacecast
1817    let vtable = find_vtable_behind_cast(vtable);
1818
1819    // When full debuginfo is enabled, we want to try and prevent vtables from being
1820    // merged. Otherwise debuggers will have a hard time mapping from dyn pointer
1821    // to concrete type.
1822    llvm::set_unnamed_address(vtable, llvm::UnnamedAddr::No);
1823
1824    let vtable_name =
1825        compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
1826    let vtable_type_di_node = build_vtable_type_di_node(cx, ty, poly_trait_ref);
1827
1828    DIB(cx).create_static_variable(
1829        NO_SCOPE_METADATA,
1830        &vtable_name,
1831        "", // (linkage_name)
1832        unknown_file_metadata(cx),
1833        UNKNOWN_LINE_NUMBER,
1834        vtable_type_di_node,
1835        true,   // (is_local_to_unit)
1836        vtable, // (value)
1837        None,   // (decl)
1838        None::<Align>,
1839    );
1840}
1841
1842/// Creates an "extension" of an existing `DIScope` into another file.
1843pub(crate) fn extend_scope_to_file<'ll>(
1844    cx: &CodegenCx<'ll, '_>,
1845    scope_metadata: &'ll DIScope,
1846    file: &SourceFile,
1847) -> &'ll DILexicalBlock {
1848    let file_metadata = file_metadata(cx, file);
1849    unsafe {
1850        llvm::LLVMDIBuilderCreateLexicalBlockFile(
1851            DIB(cx),
1852            scope_metadata,
1853            file_metadata,
1854            /* Discriminator (default) */ 0u32,
1855        )
1856    }
1857}
1858
1859fn tuple_field_name(field_index: usize) -> Cow<'static, str> {
1860    const TUPLE_FIELD_NAMES: [&'static str; 16] = [
1861        "__0", "__1", "__2", "__3", "__4", "__5", "__6", "__7", "__8", "__9", "__10", "__11",
1862        "__12", "__13", "__14", "__15",
1863    ];
1864    TUPLE_FIELD_NAMES
1865        .get(field_index)
1866        .map(|s| Cow::from(*s))
1867        .unwrap_or_else(|| Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__{0}", field_index))
    })format!("__{field_index}")))
1868}
1869
1870pub(crate) type DefinitionLocation<'ll> = (&'ll DIFile, c_uint);
1871
1872pub(crate) fn file_metadata_from_def_id<'ll>(
1873    cx: &CodegenCx<'ll, '_>,
1874    def_id: Option<DefId>,
1875) -> DefinitionLocation<'ll> {
1876    if let Some(def_id) = def_id
1877        && let span = hygiene::walk_chain_collapsed(cx.tcx.def_span(def_id), DUMMY_SP)
1878        && !span.is_dummy()
1879    {
1880        let loc = cx.lookup_debug_loc(span.lo());
1881        (file_metadata(cx, &loc.file), loc.line)
1882    } else {
1883        (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1884    }
1885}