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