1 use self::MemberDescriptionFactory::*;
2 use self::RecursiveTypeDescription::*;
4 use super::namespace::mangled_name_of_instance;
5 use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
7 create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB,
9 use super::CrateDebugContext;
12 use crate::common::CodegenCx;
13 use crate::debuginfo::utils::fat_pointer_kind;
14 use crate::debuginfo::utils::FatPtrKind;
16 use crate::llvm::debuginfo::{
17 DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
20 use crate::value::Value;
23 use rustc_codegen_ssa::debuginfo::type_names::cpp_like_debuginfo;
24 use rustc_codegen_ssa::traits::*;
25 use rustc_data_structures::fingerprint::Fingerprint;
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
28 use rustc_fs_util::path_to_c_string;
29 use rustc_hir::def::CtorKind;
30 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
31 use rustc_index::vec::{Idx, IndexVec};
32 use rustc_middle::bug;
33 use rustc_middle::mir::{self, GeneratorLayout};
34 use rustc_middle::ty::layout::{self, IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout};
35 use rustc_middle::ty::subst::GenericArgKind;
36 use rustc_middle::ty::{
37 self, AdtKind, GeneratorSubsts, Instance, ParamEnv, Ty, TyCtxt, COMMON_VTABLE_ENTRIES,
39 use rustc_query_system::ich::NodeIdHashingMode;
40 use rustc_session::config::{self, DebugInfo};
41 use rustc_span::symbol::Symbol;
42 use rustc_span::FileNameDisplayPreference;
43 use rustc_span::{self, SourceFile, SourceFileHash};
44 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, TagEncoding};
45 use rustc_target::abi::{Int, Pointer, F32, F64};
46 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
49 use libc::{c_longlong, c_uint};
50 use std::collections::hash_map::Entry;
51 use std::fmt::{self, Write};
52 use std::hash::{Hash, Hasher};
54 use std::path::{Path, PathBuf};
57 impl PartialEq for llvm::Metadata {
58 fn eq(&self, other: &Self) -> bool {
63 impl Eq for llvm::Metadata {}
65 impl Hash for llvm::Metadata {
66 fn hash<H: Hasher>(&self, hasher: &mut H) {
67 (self as *const Self).hash(hasher);
71 impl fmt::Debug for llvm::Metadata {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 (self as *const Self).fmt(f)
78 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
79 const DW_LANG_RUST: c_uint = 0x1c;
80 #[allow(non_upper_case_globals)]
81 const DW_ATE_boolean: c_uint = 0x02;
82 #[allow(non_upper_case_globals)]
83 const DW_ATE_float: c_uint = 0x04;
84 #[allow(non_upper_case_globals)]
85 const DW_ATE_signed: c_uint = 0x05;
86 #[allow(non_upper_case_globals)]
87 const DW_ATE_unsigned: c_uint = 0x07;
88 #[allow(non_upper_case_globals)]
89 const DW_ATE_unsigned_char: c_uint = 0x08;
91 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
92 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
94 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
98 use rustc_arena::DroplessArena;
100 #[derive(Copy, Hash, Eq, PartialEq, Clone)]
101 pub(super) struct UniqueTypeId(u32);
103 // The `&'static str`s in this type actually point into the arena.
105 // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
106 // found that to regress performance up to 2% in some cases. This might be
107 // revisited after further improvements to `indexmap`.
109 pub(super) struct TypeIdInterner {
110 arena: DroplessArena,
111 names: FxHashMap<&'static str, UniqueTypeId>,
112 strings: Vec<&'static str>,
115 impl TypeIdInterner {
117 pub(super) fn intern(&mut self, string: &str) -> UniqueTypeId {
118 if let Some(&name) = self.names.get(string) {
122 let name = UniqueTypeId(self.strings.len() as u32);
124 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
127 unsafe { std::str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
128 // It is safe to extend the arena allocation to `'static` because we only access
129 // these while the arena is still alive.
130 let string: &'static str = unsafe { &*(string as *const str) };
131 self.strings.push(string);
132 self.names.insert(string, name);
136 // Get the symbol as a string. `Symbol::as_str()` should be used in
137 // preference to this function.
138 pub(super) fn get(&self, symbol: UniqueTypeId) -> &str {
139 self.strings[symbol.0 as usize]
143 use unique_type_id::*;
145 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
146 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
147 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
150 pub struct TypeMap<'ll, 'tcx> {
151 /// The `UniqueTypeId`s created so far.
152 unique_id_interner: TypeIdInterner,
153 /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
154 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
155 /// A map from types to debuginfo metadata. This is an N:1 mapping.
156 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
157 /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
158 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
161 impl<'ll, 'tcx> TypeMap<'ll, 'tcx> {
162 /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
163 /// the mapping already exists.
164 fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
165 if self.type_to_metadata.insert(type_, metadata).is_some() {
166 bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
170 /// Removes a `Ty`-to-metadata mapping.
171 /// This is useful when computing the metadata for a potentially
172 /// recursive type (e.g., a function pointer of the form:
174 /// fn foo() -> impl Copy { foo }
176 /// This kind of type cannot be properly represented
177 /// via LLVM debuginfo. As a workaround,
178 /// we register a temporary Ty to metadata mapping
179 /// for the function before we compute its actual metadata.
180 /// If the metadata computation ends up recursing back to the
181 /// original function, it will use the temporary mapping
182 /// for the inner self-reference, preventing us from
183 /// recursing forever.
185 /// This function is used to remove the temporary metadata
186 /// mapping after we've computed the actual metadata.
187 fn remove_type(&mut self, type_: Ty<'tcx>) {
188 if self.type_to_metadata.remove(type_).is_none() {
189 bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", type_);
193 /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
194 /// fail if the mapping already exists.
195 fn register_unique_id_with_metadata(
197 unique_type_id: UniqueTypeId,
198 metadata: &'ll DIType,
200 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
202 "type metadata for unique ID '{}' is already in the `TypeMap`!",
203 self.get_unique_type_id_as_string(unique_type_id)
208 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
209 self.type_to_metadata.get(&type_).cloned()
212 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
213 self.unique_id_to_metadata.get(&unique_type_id).cloned()
216 /// Gets the string representation of a `UniqueTypeId`. This method will fail if
217 /// the ID is unknown.
218 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
219 self.unique_id_interner.get(unique_type_id)
222 /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
223 /// type has been requested before, this is just a table lookup. Otherwise, an
224 /// ID will be generated and stored for later lookup.
225 fn get_unique_type_id_of_type<'a>(
227 cx: &CodegenCx<'a, 'tcx>,
230 // Let's see if we already have something in the cache.
231 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
232 return unique_type_id;
234 // If not, generate one.
236 // The hasher we are using to generate the UniqueTypeId. We want
237 // something that provides more than the 64 bits of the DefaultHasher.
238 let mut hasher = StableHasher::new();
239 let mut hcx = cx.tcx.create_stable_hashing_context();
240 let type_ = cx.tcx.erase_regions(type_);
241 hcx.while_hashing_spans(false, |hcx| {
242 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
243 type_.hash_stable(hcx, &mut hasher);
246 let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
248 let key = self.unique_id_interner.intern(&unique_type_id);
249 self.type_to_unique_id.insert(type_, key);
254 /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
255 /// types of their own, so they need special handling. We still need a
256 /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
257 fn get_unique_type_id_of_enum_variant<'a>(
259 cx: &CodegenCx<'a, 'tcx>,
263 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
264 let enum_variant_type_id =
265 format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
266 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
270 /// Gets the unique type ID string for an enum variant part.
271 /// Variant parts are not types and shouldn't really have their own ID,
272 /// but it makes `set_members_of_composite_type()` simpler.
273 fn get_unique_type_id_str_of_enum_variant_part(
275 enum_type_id: UniqueTypeId,
277 format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id))
281 /// A description of some recursive type. It can either be already finished (as
282 /// with `FinalMetadata`) or it is not yet finished, but contains all information
283 /// needed to generate the missing parts of the description. See the
284 /// documentation section on Recursive Types at the top of this file for more
286 enum RecursiveTypeDescription<'ll, 'tcx> {
288 unfinished_type: Ty<'tcx>,
289 unique_type_id: UniqueTypeId,
290 metadata_stub: &'ll DICompositeType,
291 member_holding_stub: &'ll DICompositeType,
292 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
294 FinalMetadata(&'ll DICompositeType),
297 fn create_and_register_recursive_type_forward_declaration<'ll, 'tcx>(
298 cx: &CodegenCx<'ll, 'tcx>,
299 unfinished_type: Ty<'tcx>,
300 unique_type_id: UniqueTypeId,
301 metadata_stub: &'ll DICompositeType,
302 member_holding_stub: &'ll DICompositeType,
303 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
304 ) -> RecursiveTypeDescription<'ll, 'tcx> {
305 // Insert the stub into the `TypeMap` in order to allow for recursive references.
306 let mut type_map = debug_context(cx).type_map.borrow_mut();
307 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
308 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
315 member_description_factory,
319 impl<'ll, 'tcx> RecursiveTypeDescription<'ll, 'tcx> {
320 /// Finishes up the description of the type in question (mostly by providing
321 /// descriptions of the fields of the given type) and returns the final type
323 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
325 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
331 ref member_description_factory,
333 // Make sure that we have a forward declaration of the type in
334 // the TypeMap so that recursive references are possible. This
335 // will always be the case if the RecursiveTypeDescription has
336 // been properly created through the
337 // `create_and_register_recursive_type_forward_declaration()`
340 let type_map = debug_context(cx).type_map.borrow();
341 if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
342 || type_map.find_metadata_for_type(unfinished_type).is_none()
345 "Forward declaration of potentially recursive type \
346 '{:?}' was not found in TypeMap!",
352 // ... then create the member descriptions ...
353 let member_descriptions = member_description_factory.create_member_descriptions(cx);
355 // ... and attach them to the stub to complete it.
356 set_members_of_composite_type(
363 MetadataCreationResult::new(metadata_stub, true)
369 /// Returns from the enclosing function if the type metadata with the given
370 /// unique ID can be found in the type map.
371 macro_rules! return_if_metadata_created_in_meantime {
372 ($cx: expr, $unique_type_id: expr) => {
373 if let Some(metadata) =
374 debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
376 return MetadataCreationResult::new(metadata, true);
381 /// Creates debuginfo for a fixed size array (e.g. `[u64; 123]`).
382 /// For slices (that is, "arrays" of unknown size) use [slice_type_metadata].
383 fn fixed_size_array_metadata<'ll, 'tcx>(
384 cx: &CodegenCx<'ll, 'tcx>,
385 unique_type_id: UniqueTypeId,
386 array_type: Ty<'tcx>,
387 ) -> MetadataCreationResult<'ll> {
388 let ty::Array(element_type, len) = array_type.kind() else {
389 bug!("fixed_size_array_metadata() called with non-ty::Array type `{:?}`", array_type)
392 let element_type_metadata = type_metadata(cx, element_type);
394 return_if_metadata_created_in_meantime!(cx, unique_type_id);
396 let (size, align) = cx.size_and_align_of(array_type);
398 let upper_bound = len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong;
401 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
403 let subscripts = create_DIArray(DIB(cx), &[subrange]);
404 let metadata = unsafe {
405 llvm::LLVMRustDIBuilderCreateArrayType(
409 element_type_metadata,
414 MetadataCreationResult::new(metadata, false)
417 /// Creates debuginfo for built-in pointer-like things:
421 /// - ty::Adt in the case it's Box
423 /// At some point we might want to remove the special handling of Box
424 /// and treat it the same as other smart pointers (like Rc, Arc, ...).
425 fn pointer_or_reference_metadata<'ll, 'tcx>(
426 cx: &CodegenCx<'ll, 'tcx>,
428 pointee_type: Ty<'tcx>,
429 unique_type_id: UniqueTypeId,
430 ) -> MetadataCreationResult<'ll> {
431 let pointee_type_metadata = type_metadata(cx, pointee_type);
433 return_if_metadata_created_in_meantime!(cx, unique_type_id);
435 let (thin_pointer_size, thin_pointer_align) =
436 cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.types.unit));
437 let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
439 let pointer_type_metadata = match fat_pointer_kind(cx, pointee_type) {
441 // This is a thin pointer. Create a regular pointer type and give it the correct name.
443 (thin_pointer_size, thin_pointer_align),
444 cx.size_and_align_of(ptr_type)
448 llvm::LLVMRustDIBuilderCreatePointerType(
450 pointee_type_metadata,
451 thin_pointer_size.bits(),
452 thin_pointer_align.bits() as u32,
453 0, // Ignore DWARF address space.
454 ptr_type_debuginfo_name.as_ptr().cast(),
455 ptr_type_debuginfo_name.len(),
459 Some(fat_pointer_kind) => {
460 let layout = cx.layout_of(ptr_type);
462 let addr_field = layout.field(cx, abi::FAT_PTR_ADDR);
463 let extra_field = layout.field(cx, abi::FAT_PTR_EXTRA);
465 let (addr_field_name, extra_field_name) = match fat_pointer_kind {
466 FatPtrKind::Dyn => ("pointer", "vtable"),
467 FatPtrKind::Slice => ("data_ptr", "length"),
470 debug_assert_eq!(abi::FAT_PTR_ADDR, 0);
471 debug_assert_eq!(abi::FAT_PTR_EXTRA, 1);
473 // The data pointer type is a regular, thin pointer, regardless of whether this is a slice
474 // or a trait object.
475 let data_ptr_type_metadata = unsafe {
476 llvm::LLVMRustDIBuilderCreatePointerType(
478 pointee_type_metadata,
479 addr_field.size.bits(),
480 addr_field.align.abi.bits() as u32,
481 0, // Ignore DWARF address space.
487 let member_descriptions = vec![
489 name: addr_field_name.into(),
490 type_metadata: data_ptr_type_metadata,
491 offset: layout.fields.offset(abi::FAT_PTR_ADDR),
492 size: addr_field.size,
493 align: addr_field.align.abi,
494 flags: DIFlags::FlagZero,
499 name: extra_field_name.into(),
500 type_metadata: type_metadata(cx, extra_field.ty),
501 offset: layout.fields.offset(abi::FAT_PTR_EXTRA),
502 size: extra_field.size,
503 align: extra_field.align.abi,
504 flags: DIFlags::FlagZero,
510 composite_type_metadata(
513 &ptr_type_debuginfo_name,
521 MetadataCreationResult { metadata: pointer_type_metadata, already_stored_in_typemap: false }
524 fn subroutine_type_metadata<'ll, 'tcx>(
525 cx: &CodegenCx<'ll, 'tcx>,
526 unique_type_id: UniqueTypeId,
527 signature: ty::PolyFnSig<'tcx>,
528 ) -> MetadataCreationResult<'ll> {
530 cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), signature);
532 let signature_metadata: Vec<_> = iter::once(
534 match signature.output().kind() {
535 ty::Tuple(tys) if tys.is_empty() => None,
536 _ => Some(type_metadata(cx, signature.output())),
541 signature.inputs().iter().map(|argument_type| Some(type_metadata(cx, argument_type))),
545 return_if_metadata_created_in_meantime!(cx, unique_type_id);
547 MetadataCreationResult::new(
549 llvm::LLVMRustDIBuilderCreateSubroutineType(
551 create_DIArray(DIB(cx), &signature_metadata[..]),
558 /// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
559 /// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
560 fn dyn_type_metadata<'ll, 'tcx>(
561 cx: &CodegenCx<'ll, 'tcx>,
563 unique_type_id: UniqueTypeId,
565 if let ty::Dynamic(..) = dyn_type.kind() {
566 let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
567 composite_type_metadata(cx, dyn_type, &type_name, unique_type_id, vec![], NO_SCOPE_METADATA)
569 bug!("Only ty::Dynamic is valid for dyn_type_metadata(). Found {:?} instead.", dyn_type)
573 /// Create debuginfo for `[T]` and `str`. These are unsized.
575 /// NOTE: We currently emit just emit the debuginfo for the element type here
576 /// (i.e. `T` for slices and `u8` for `str`), so that we end up with
577 /// `*const T` for the `data_ptr` field of the corresponding fat-pointer
578 /// debuginfo of `&[T]`.
580 /// It would be preferable and more accurate if we emitted a DIArray of T
581 /// without an upper bound instead. That is, LLVM already supports emitting
582 /// debuginfo of arrays of unknown size. But GDB currently seems to end up
583 /// in an infinite loop when confronted with such a type.
585 /// As a side effect of the current encoding every instance of a type like
586 /// `struct Foo { unsized_field: [u8] }` will look like
587 /// `struct Foo { unsized_field: u8 }` in debuginfo. If the length of the
588 /// slice is zero, then accessing `unsized_field` in the debugger would
589 /// result in an out-of-bounds access.
590 fn slice_type_metadata<'ll, 'tcx>(
591 cx: &CodegenCx<'ll, 'tcx>,
592 slice_type: Ty<'tcx>,
593 unique_type_id: UniqueTypeId,
594 ) -> MetadataCreationResult<'ll> {
595 let element_type = match slice_type.kind() {
596 ty::Slice(element_type) => element_type,
597 ty::Str => cx.tcx.types.u8,
600 "Only ty::Slice is valid for slice_type_metadata(). Found {:?} instead.",
606 let element_type_metadata = type_metadata(cx, element_type);
607 return_if_metadata_created_in_meantime!(cx, unique_type_id);
608 MetadataCreationResult { metadata: element_type_metadata, already_stored_in_typemap: false }
611 pub fn type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
612 // Get the unique type ID of this type.
613 let unique_type_id = {
614 let mut type_map = debug_context(cx).type_map.borrow_mut();
615 // First, try to find the type in `TypeMap`. If we have seen it before, we
616 // can exit early here.
617 match type_map.find_metadata_for_type(t) {
622 // The Ty is not in the `TypeMap` but maybe we have already seen
623 // an equivalent type (e.g., only differing in region arguments).
624 // In order to find out, generate the unique type ID and look
626 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
627 match type_map.find_metadata_for_unique_id(unique_type_id) {
629 // There is already an equivalent type in the TypeMap.
630 // Register this Ty as an alias in the cache and
631 // return the cached metadata.
632 type_map.register_type_with_metadata(t, metadata);
636 // There really is no type metadata for this type, so
637 // proceed by creating it.
645 debug!("type_metadata: {:?}", t);
647 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
648 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
649 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
651 ty::Tuple(elements) if elements.is_empty() => {
652 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
654 ty::Array(..) => fixed_size_array_metadata(cx, unique_type_id, t),
655 ty::Slice(_) | ty::Str => slice_type_metadata(cx, t, unique_type_id),
657 MetadataCreationResult::new(dyn_type_metadata(cx, t, unique_type_id), false)
660 MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
662 ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => {
663 pointer_or_reference_metadata(cx, t, pointee_type, unique_type_id)
665 ty::Adt(def, _) if def.is_box() => {
666 pointer_or_reference_metadata(cx, t, t.boxed_ty(), unique_type_id)
668 ty::FnDef(..) | ty::FnPtr(_) => {
669 if let Some(metadata) =
670 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
675 // It's possible to create a self-referential
676 // type in Rust by using 'impl trait':
678 // fn foo() -> impl Copy { foo }
680 // See `TypeMap::remove_type` for more detals
681 // about the workaround.
685 // The choice of type here is pretty arbitrary -
686 // anything reading the debuginfo for a recursive
687 // type is going to see *something* weird - the only
688 // question is what exactly it will see.
689 let name = "<recur_type>";
690 llvm::LLVMRustDIBuilderCreateBasicType(
692 name.as_ptr().cast(),
694 cx.size_of(t).bits(),
700 let type_map = &debug_context(cx).type_map;
701 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
704 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx)).metadata;
706 type_map.borrow_mut().remove_type(t);
708 // This is actually a function pointer, so wrap it in pointer DI.
709 let (pointer_size, pointer_align) =
710 cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.mk_unit()));
711 let name = compute_debuginfo_type_name(cx.tcx, t, false);
713 llvm::LLVMRustDIBuilderCreatePointerType(
717 pointer_align.bits() as u32,
718 0, // Ignore DWARF address space.
719 name.as_ptr().cast(),
724 MetadataCreationResult::new(md, false)
726 ty::Closure(def_id, substs) => {
727 let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
728 let containing_scope = get_namespace_for_item(cx, def_id);
729 prepare_tuple_metadata(cx, t, &upvar_tys, unique_type_id, Some(containing_scope))
732 ty::Generator(def_id, substs, _) => {
733 let upvar_tys: Vec<_> = substs
736 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
738 prepare_enum_metadata(cx, t, def_id, unique_type_id, upvar_tys).finalize(cx)
740 ty::Adt(def, ..) => match def.adt_kind() {
741 AdtKind::Struct => prepare_struct_metadata(cx, t, unique_type_id).finalize(cx),
742 AdtKind::Union => prepare_union_metadata(cx, t, unique_type_id).finalize(cx),
744 prepare_enum_metadata(cx, t, def.did, unique_type_id, vec![]).finalize(cx)
747 ty::Tuple(elements) => {
748 let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
749 prepare_tuple_metadata(cx, t, &tys, unique_type_id, NO_SCOPE_METADATA).finalize(cx)
751 // Type parameters from polymorphized functions.
752 ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
753 _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
757 let mut type_map = debug_context(cx).type_map.borrow_mut();
759 if already_stored_in_typemap {
760 // Also make sure that we already have a `TypeMap` entry for the unique type ID.
761 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
762 Some(metadata) => metadata,
765 "expected type metadata for unique \
766 type ID '{}' to already be in \
767 the `debuginfo::TypeMap` but it \
769 type_map.get_unique_type_id_as_string(unique_type_id),
775 match type_map.find_metadata_for_type(t) {
777 if metadata != metadata_for_uid {
779 "mismatch between `Ty` and \
780 `UniqueTypeId` maps in \
781 `debuginfo::TypeMap`. \
782 UniqueTypeId={}, Ty={}",
783 type_map.get_unique_type_id_as_string(unique_type_id),
789 type_map.register_type_with_metadata(t, metadata);
793 type_map.register_type_with_metadata(t, metadata);
794 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
801 fn hex_encode(data: &[u8]) -> String {
802 let mut hex_string = String::with_capacity(data.len() * 2);
803 for byte in data.iter() {
804 write!(&mut hex_string, "{:02x}", byte).unwrap();
809 pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
810 debug!("file_metadata: file_name: {:?}", source_file.name);
812 let hash = Some(&source_file.src_hash);
813 let file_name = Some(source_file.name.prefer_remapped().to_string());
814 let directory = if source_file.is_real_file() && !source_file.is_imported() {
819 .to_string_lossy(FileNameDisplayPreference::Remapped)
823 // If the path comes from an upstream crate we assume it has been made
824 // independent of the compiler's working directory one way or another.
827 file_metadata_raw(cx, file_name, directory, hash)
830 pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
831 file_metadata_raw(cx, None, None, None)
834 fn file_metadata_raw<'ll>(
835 cx: &CodegenCx<'ll, '_>,
836 file_name: Option<String>,
837 directory: Option<String>,
838 hash: Option<&SourceFileHash>,
840 let key = (file_name, directory);
842 match debug_context(cx).created_files.borrow_mut().entry(key) {
843 Entry::Occupied(o) => o.get(),
844 Entry::Vacant(v) => {
845 let (file_name, directory) = v.key();
846 debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
848 let file_name = file_name.as_deref().unwrap_or("<unknown>");
849 let directory = directory.as_deref().unwrap_or("");
851 let (hash_kind, hash_value) = match hash {
853 let kind = match hash.kind {
854 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
855 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
856 rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
858 (kind, hex_encode(hash.hash_bytes()))
860 None => (llvm::ChecksumKind::None, String::new()),
863 let file_metadata = unsafe {
864 llvm::LLVMRustDIBuilderCreateFile(
866 file_name.as_ptr().cast(),
868 directory.as_ptr().cast(),
871 hash_value.as_ptr().cast(),
876 v.insert(file_metadata);
882 trait MsvcBasicName {
883 fn msvc_basic_name(self) -> &'static str;
886 impl MsvcBasicName for ty::IntTy {
887 fn msvc_basic_name(self) -> &'static str {
889 ty::IntTy::Isize => "ptrdiff_t",
890 ty::IntTy::I8 => "__int8",
891 ty::IntTy::I16 => "__int16",
892 ty::IntTy::I32 => "__int32",
893 ty::IntTy::I64 => "__int64",
894 ty::IntTy::I128 => "__int128",
899 impl MsvcBasicName for ty::UintTy {
900 fn msvc_basic_name(self) -> &'static str {
902 ty::UintTy::Usize => "size_t",
903 ty::UintTy::U8 => "unsigned __int8",
904 ty::UintTy::U16 => "unsigned __int16",
905 ty::UintTy::U32 => "unsigned __int32",
906 ty::UintTy::U64 => "unsigned __int64",
907 ty::UintTy::U128 => "unsigned __int128",
912 impl MsvcBasicName for ty::FloatTy {
913 fn msvc_basic_name(self) -> &'static str {
915 ty::FloatTy::F32 => "float",
916 ty::FloatTy::F64 => "double",
921 fn basic_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
922 debug!("basic_type_metadata: {:?}", t);
924 // When targeting MSVC, emit MSVC style type names for compatibility with
925 // .natvis visualizers (and perhaps other existing native debuggers?)
926 let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
928 let (name, encoding) = match t.kind() {
929 ty::Never => ("!", DW_ATE_unsigned),
930 ty::Tuple(elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
931 ty::Bool => ("bool", DW_ATE_boolean),
932 ty::Char => ("char", DW_ATE_unsigned_char),
933 ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
934 ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
935 ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
936 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
937 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
938 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
939 _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
942 let ty_metadata = unsafe {
943 llvm::LLVMRustDIBuilderCreateBasicType(
945 name.as_ptr().cast(),
947 cx.size_of(t).bits(),
952 if !cpp_like_debuginfo {
956 let typedef_name = match t.kind() {
957 ty::Int(int_ty) => int_ty.name_str(),
958 ty::Uint(uint_ty) => uint_ty.name_str(),
959 ty::Float(float_ty) => float_ty.name_str(),
960 _ => return ty_metadata,
963 let typedef_metadata = unsafe {
964 llvm::LLVMRustDIBuilderCreateTypedef(
967 typedef_name.as_ptr().cast(),
969 unknown_file_metadata(cx),
978 fn foreign_type_metadata<'ll, 'tcx>(
979 cx: &CodegenCx<'ll, 'tcx>,
981 unique_type_id: UniqueTypeId,
983 debug!("foreign_type_metadata: {:?}", t);
985 let name = compute_debuginfo_type_name(cx.tcx, t, false);
986 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA, DIFlags::FlagZero)
989 fn param_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
990 debug!("param_type_metadata: {:?}", t);
991 let name = format!("{:?}", t);
993 llvm::LLVMRustDIBuilderCreateBasicType(
995 name.as_ptr().cast(),
1003 pub fn compile_unit_metadata<'ll, 'tcx>(
1005 codegen_unit_name: &str,
1006 debug_context: &CrateDebugContext<'ll, 'tcx>,
1007 ) -> &'ll DIDescriptor {
1008 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
1009 Some(ref path) => path.clone(),
1010 None => PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()),
1013 // To avoid breaking split DWARF, we need to ensure that each codegen unit
1014 // has a unique `DW_AT_name`. This is because there's a remote chance that
1015 // different codegen units for the same module will have entirely
1016 // identical DWARF entries for the purpose of the DWO ID, which would
1017 // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
1018 // specification. LLVM uses the algorithm specified in section 7.32 "Type
1019 // Signature Computation" to compute the DWO ID, which does not include
1020 // any fields that would distinguish compilation units. So we must embed
1021 // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
1023 // Additionally, the OSX linker has an idiosyncrasy where it will ignore
1024 // some debuginfo if multiple object files with the same `DW_AT_name` are
1027 // As a workaround for these two issues, we generate unique names for each
1028 // object file. Those do not correspond to an actual source file but that
1030 name_in_debuginfo.push("@");
1031 name_in_debuginfo.push(codegen_unit_name);
1033 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
1034 let rustc_producer =
1035 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
1036 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
1037 let producer = format!("clang LLVM ({})", rustc_producer);
1039 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1040 let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
1042 let output_filenames = tcx.output_filenames(());
1043 let split_name = if tcx.sess.target_can_use_split_dwarf() {
1046 tcx.sess.split_debuginfo(),
1047 tcx.sess.opts.debugging_opts.split_dwarf_kind,
1048 Some(codegen_unit_name),
1050 // We get a path relative to the working directory from split_dwarf_path
1051 .map(|f| tcx.sess.source_map().path_mapping().map_prefix(f).0)
1055 .unwrap_or_default();
1056 let split_name = split_name.to_str().unwrap();
1060 // This should actually be
1062 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1064 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
1065 // we are compiling with "limited" debuginfo. However, some of the
1066 // existing tools relied on slightly more debuginfo being generated than
1067 // would be the case with `LineTablesOnly`, and we did not want to break
1068 // these tools in a "drive-by fix", without a good idea or plan about
1069 // what limited debuginfo should exactly look like. So for now we keep
1070 // the emission kind as `FullDebug`.
1072 // See https://github.com/rust-lang/rust/issues/60020 for details.
1073 let kind = DebugEmissionKind::FullDebug;
1074 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1077 let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
1078 debug_context.builder,
1079 name_in_debuginfo.as_ptr().cast(),
1080 name_in_debuginfo.len(),
1081 work_dir.as_ptr().cast(),
1083 llvm::ChecksumKind::None,
1088 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1089 debug_context.builder,
1092 producer.as_ptr().cast(),
1094 tcx.sess.opts.optimize != config::OptLevel::No,
1095 flags.as_ptr().cast(),
1097 // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1098 // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1100 split_name.as_ptr().cast(),
1104 tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1107 if tcx.sess.opts.debugging_opts.profile {
1108 let cu_desc_metadata =
1109 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1110 let default_gcda_path = &output_filenames.with_extension("gcda");
1112 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1114 let gcov_cu_info = [
1115 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1116 path_to_mdstring(debug_context.llcontext, gcda_path),
1119 let gcov_metadata = llvm::LLVMMDNodeInContext(
1120 debug_context.llcontext,
1121 gcov_cu_info.as_ptr(),
1122 gcov_cu_info.len() as c_uint,
1125 let llvm_gcov_ident = cstr!("llvm.gcov");
1126 llvm::LLVMAddNamedMetadataOperand(
1127 debug_context.llmod,
1128 llvm_gcov_ident.as_ptr(),
1133 // Insert `llvm.ident` metadata on the wasm targets since that will
1134 // get hooked up to the "producer" sections `processed-by` information.
1135 if tcx.sess.target.is_like_wasm {
1136 let name_metadata = llvm::LLVMMDStringInContext(
1137 debug_context.llcontext,
1138 rustc_producer.as_ptr().cast(),
1139 rustc_producer.as_bytes().len() as c_uint,
1141 llvm::LLVMAddNamedMetadataOperand(
1142 debug_context.llmod,
1143 cstr!("llvm.ident").as_ptr(),
1144 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1148 return unit_metadata;
1151 fn path_to_mdstring<'ll>(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1152 let path_str = path_to_c_string(path);
1154 llvm::LLVMMDStringInContext(
1157 path_str.as_bytes().len() as c_uint,
1163 struct MetadataCreationResult<'ll> {
1164 metadata: &'ll DIType,
1165 already_stored_in_typemap: bool,
1168 impl<'ll> MetadataCreationResult<'ll> {
1169 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1170 MetadataCreationResult { metadata, already_stored_in_typemap }
1175 struct SourceInfo<'ll> {
1180 /// Description of a type member, which can either be a regular field (as in
1181 /// structs or tuples) or an enum variant.
1183 struct MemberDescription<'ll> {
1185 type_metadata: &'ll DIType,
1190 discriminant: Option<u64>,
1191 source_info: Option<SourceInfo<'ll>>,
1194 impl<'ll> MemberDescription<'ll> {
1197 cx: &CodegenCx<'ll, '_>,
1198 composite_type_metadata: &'ll DIScope,
1200 let (file, line) = self
1202 .map(|info| (info.file, info.line))
1203 .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1205 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1207 composite_type_metadata,
1208 self.name.as_ptr().cast(),
1213 self.align.bits() as u32,
1215 self.discriminant.map(|v| cx.const_u64(v)),
1223 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1224 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1225 /// creation of type member descriptions in order to break cycles arising from
1226 /// recursive type definitions.
1227 enum MemberDescriptionFactory<'ll, 'tcx> {
1228 StructMDF(StructMemberDescriptionFactory<'tcx>),
1229 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1230 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1231 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1232 VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1235 impl<'ll, 'tcx> MemberDescriptionFactory<'ll, 'tcx> {
1236 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1238 StructMDF(ref this) => this.create_member_descriptions(cx),
1239 TupleMDF(ref this) => this.create_member_descriptions(cx),
1240 EnumMDF(ref this) => this.create_member_descriptions(cx),
1241 UnionMDF(ref this) => this.create_member_descriptions(cx),
1242 VariantMDF(ref this) => this.create_member_descriptions(cx),
1247 //=-----------------------------------------------------------------------------
1249 //=-----------------------------------------------------------------------------
1251 /// Creates `MemberDescription`s for the fields of a struct.
1252 struct StructMemberDescriptionFactory<'tcx> {
1254 variant: &'tcx ty::VariantDef,
1257 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1258 fn create_member_descriptions<'ll>(
1260 cx: &CodegenCx<'ll, 'tcx>,
1261 ) -> Vec<MemberDescription<'ll>> {
1262 let layout = cx.layout_of(self.ty);
1268 let name = if self.variant.ctor_kind == CtorKind::Fn {
1273 let field = layout.field(cx, i);
1276 type_metadata: type_metadata(cx, field.ty),
1277 offset: layout.fields.offset(i),
1279 align: field.align.abi,
1280 flags: DIFlags::FlagZero,
1289 fn prepare_struct_metadata<'ll, 'tcx>(
1290 cx: &CodegenCx<'ll, 'tcx>,
1291 struct_type: Ty<'tcx>,
1292 unique_type_id: UniqueTypeId,
1293 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1294 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1296 let (struct_def_id, variant) = match struct_type.kind() {
1297 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1298 _ => bug!("prepare_struct_metadata on a non-ADT"),
1301 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1303 let struct_metadata_stub = create_struct_stub(
1308 Some(containing_scope),
1312 create_and_register_recursive_type_forward_declaration(
1316 struct_metadata_stub,
1317 struct_metadata_stub,
1318 StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant }),
1322 //=-----------------------------------------------------------------------------
1324 //=-----------------------------------------------------------------------------
1326 /// Returns names of captured upvars for closures and generators.
1328 /// Here are some examples:
1329 /// - `name__field1__field2` when the upvar is captured by value.
1330 /// - `_ref__name__field` when the upvar is captured by reference.
1331 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<String> {
1332 let body = tcx.optimized_mir(def_id);
1337 let is_ref = match var.value {
1338 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1339 // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1340 // implies whether the variable is captured by value or by reference.
1341 matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1345 let prefix = if is_ref { "_ref__" } else { "" };
1346 Some(prefix.to_owned() + var.name.as_str())
1348 .collect::<Vec<_>>()
1351 /// Creates `MemberDescription`s for the fields of a tuple.
1352 struct TupleMemberDescriptionFactory<'tcx> {
1354 component_types: Vec<Ty<'tcx>>,
1357 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1358 fn create_member_descriptions<'ll>(
1360 cx: &CodegenCx<'ll, 'tcx>,
1361 ) -> Vec<MemberDescription<'ll>> {
1362 let mut capture_names = match *self.ty.kind() {
1363 ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1364 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1368 let layout = cx.layout_of(self.ty);
1369 self.component_types
1372 .map(|(i, &component_type)| {
1373 let (size, align) = cx.size_and_align_of(component_type);
1374 let name = if let Some(names) = capture_names.as_mut() {
1375 names.next().unwrap()
1381 type_metadata: type_metadata(cx, component_type),
1382 offset: layout.fields.offset(i),
1385 flags: DIFlags::FlagZero,
1394 fn prepare_tuple_metadata<'ll, 'tcx>(
1395 cx: &CodegenCx<'ll, 'tcx>,
1396 tuple_type: Ty<'tcx>,
1397 component_types: &[Ty<'tcx>],
1398 unique_type_id: UniqueTypeId,
1399 containing_scope: Option<&'ll DIScope>,
1400 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1401 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1403 let struct_stub = create_struct_stub(
1412 create_and_register_recursive_type_forward_declaration(
1418 TupleMDF(TupleMemberDescriptionFactory {
1420 component_types: component_types.to_vec(),
1425 //=-----------------------------------------------------------------------------
1427 //=-----------------------------------------------------------------------------
1429 struct UnionMemberDescriptionFactory<'tcx> {
1430 layout: TyAndLayout<'tcx>,
1431 variant: &'tcx ty::VariantDef,
1434 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1435 fn create_member_descriptions<'ll>(
1437 cx: &CodegenCx<'ll, 'tcx>,
1438 ) -> Vec<MemberDescription<'ll>> {
1444 let field = self.layout.field(cx, i);
1446 name: f.name.to_string(),
1447 type_metadata: type_metadata(cx, field.ty),
1450 align: field.align.abi,
1451 flags: DIFlags::FlagZero,
1460 fn prepare_union_metadata<'ll, 'tcx>(
1461 cx: &CodegenCx<'ll, 'tcx>,
1462 union_type: Ty<'tcx>,
1463 unique_type_id: UniqueTypeId,
1464 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1465 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1467 let (union_def_id, variant) = match union_type.kind() {
1468 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1469 _ => bug!("prepare_union_metadata on a non-ADT"),
1472 let containing_scope = get_namespace_for_item(cx, union_def_id);
1474 let union_metadata_stub =
1475 create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1477 create_and_register_recursive_type_forward_declaration(
1481 union_metadata_stub,
1482 union_metadata_stub,
1483 UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant }),
1487 //=-----------------------------------------------------------------------------
1489 //=-----------------------------------------------------------------------------
1491 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1492 // per generator monomorphization, but it doesn't depend on substs.
1493 fn generator_layout_and_saved_local_names<'tcx>(
1496 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1497 let body = tcx.optimized_mir(def_id);
1498 let generator_layout = body.generator_layout().unwrap();
1499 let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1501 let state_arg = mir::Local::new(1);
1502 for var in &body.var_debug_info {
1503 let mir::VarDebugInfoContents::Place(place) = &var.value else { continue };
1504 if place.local != state_arg {
1507 match place.projection[..] {
1509 // Deref of the `Pin<&mut Self>` state argument.
1510 mir::ProjectionElem::Field(..),
1511 mir::ProjectionElem::Deref,
1512 // Field of a variant of the state.
1513 mir::ProjectionElem::Downcast(_, variant),
1514 mir::ProjectionElem::Field(field, _),
1516 let name = &mut generator_saved_local_names
1517 [generator_layout.variant_fields[variant][field]];
1519 name.replace(var.name);
1525 (generator_layout, generator_saved_local_names)
1528 /// Describes the members of an enum value; an enum is described as a union of
1529 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1530 /// the members of this union; so for every variant of the given enum, this
1531 /// factory will produce one `MemberDescription` (all with no name and a fixed
1532 /// offset of zero bytes).
1533 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1534 enum_type: Ty<'tcx>,
1535 layout: TyAndLayout<'tcx>,
1536 tag_type_metadata: Option<&'ll DIType>,
1537 common_members: Vec<Option<&'ll DIType>>,
1540 impl<'ll, 'tcx> EnumMemberDescriptionFactory<'ll, 'tcx> {
1541 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1542 let generator_variant_info_data = match *self.enum_type.kind() {
1543 ty::Generator(def_id, ..) => {
1544 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1549 let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1550 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1551 ty::Generator(def_id, _, _) => {
1552 let (generator_layout, generator_saved_local_names) =
1553 generator_variant_info_data.as_ref().unwrap();
1554 VariantInfo::Generator {
1556 generator_layout: *generator_layout,
1557 generator_saved_local_names,
1558 variant_index: index,
1564 // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
1565 // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
1566 // msvc, then we need to use a different, fallback encoding of the debuginfo.
1567 let fallback = cpp_like_debuginfo(cx.tcx);
1568 // This will always find the metadata in the type map.
1569 let self_metadata = type_metadata(cx, self.enum_type);
1571 match self.layout.variants {
1572 Variants::Single { index } => {
1573 if let ty::Adt(adt, _) = self.enum_type.kind() {
1574 if adt.variants.is_empty() {
1579 let variant_info = variant_info_for(index);
1580 let (variant_type_metadata, member_description_factory) =
1581 describe_enum_variant(cx, self.layout, variant_info, self_metadata);
1583 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1585 set_members_of_composite_type(
1588 variant_type_metadata,
1589 member_descriptions,
1590 Some(&self.common_members),
1592 vec![MemberDescription {
1593 name: variant_info.variant_name(),
1594 type_metadata: variant_type_metadata,
1596 size: self.layout.size,
1597 align: self.layout.align.abi,
1598 flags: DIFlags::FlagZero,
1600 source_info: variant_info.source_info(cx),
1603 Variants::Multiple {
1604 tag_encoding: TagEncoding::Direct,
1609 let fallback_discr_variant = if fallback {
1610 // For MSVC, we generate a union of structs for each variant and an
1611 // explicit discriminant field roughly equivalent to the following C:
1613 // union enum$<{name}> {
1614 // struct {variant 0 name} {
1615 // <variant 0 fields>
1617 // <other variant structs>
1618 // {name} discriminant;
1621 // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1622 // determine which variant is active and then displays it.
1623 let enum_layout = self.layout;
1624 let offset = enum_layout.fields.offset(tag_field);
1625 let discr_ty = enum_layout.field(cx, tag_field).ty;
1626 let (size, align) = cx.size_and_align_of(discr_ty);
1627 Some(MemberDescription {
1628 name: "discriminant".into(),
1629 type_metadata: self.tag_type_metadata.unwrap(),
1633 flags: DIFlags::FlagZero,
1644 let variant = self.layout.for_variant(cx, i);
1645 let variant_info = variant_info_for(i);
1646 let (variant_type_metadata, member_desc_factory) =
1647 describe_enum_variant(cx, variant, variant_info, self_metadata);
1649 let member_descriptions =
1650 member_desc_factory.create_member_descriptions(cx);
1652 set_members_of_composite_type(
1655 variant_type_metadata,
1656 member_descriptions,
1657 Some(&self.common_members),
1662 format!("variant{}", i.as_u32())
1664 variant_info.variant_name()
1666 type_metadata: variant_type_metadata,
1668 size: self.layout.size,
1669 align: self.layout.align.abi,
1670 flags: DIFlags::FlagZero,
1672 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1675 source_info: variant_info.source_info(cx),
1678 .chain(fallback_discr_variant.into_iter())
1681 Variants::Multiple {
1683 TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1688 let calculate_niche_value = |i: VariantIdx| {
1689 if i == dataful_variant {
1692 let value = (i.as_u32() as u128)
1693 .wrapping_sub(niche_variants.start().as_u32() as u128)
1694 .wrapping_add(niche_start);
1695 let value = tag.value.size(cx).truncate(value);
1696 // NOTE(eddyb) do *NOT* remove this assert, until
1697 // we pass the full 128-bit value to LLVM, otherwise
1698 // truncation will be silent and remain undetected.
1699 assert_eq!(value as u64 as u128, value);
1704 // For MSVC, we will generate a union of two fields, one for the dataful variant
1705 // and one that just points to the discriminant. We also create an enum that
1706 // contains tag values for the non-dataful variants and make the discriminant field
1707 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1708 // This will generate debuginfo roughly equivalent to the following C:
1710 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1711 // struct <dataful variant name> {
1712 // <fields in dataful variant>
1713 // } dataful_variant;
1714 // enum Discriminant$ {
1715 // <non-dataful variants>
1719 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1720 // and evaluates `this.discriminant`. If the value is between the min niche and max
1721 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1722 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1723 // case, we just need to render the name of the `this.discriminant` enum.
1725 let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1727 let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1728 // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1729 // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1730 // to just be `usize`.
1731 if let ty::RawPtr(_) = discr_enum_ty.kind() {
1732 discr_enum_ty = cx.tcx.types.usize;
1735 let tags: Vec<_> = variants
1737 .filter_map(|(variant_idx, _)| {
1738 calculate_niche_value(variant_idx).map(|tag| {
1739 let variant = variant_info_for(variant_idx);
1740 let name = variant.variant_name();
1743 llvm::LLVMRustDIBuilderCreateEnumerator(
1745 name.as_ptr().cast(),
1748 !discr_enum_ty.is_signed(),
1755 let discr_enum = unsafe {
1756 llvm::LLVMRustDIBuilderCreateEnumerationType(
1759 "Discriminant$".as_ptr().cast(),
1760 "Discriminant$".len(),
1761 unknown_file_metadata(cx),
1762 UNKNOWN_LINE_NUMBER,
1763 tag.value.size(cx).bits(),
1764 tag.value.align(cx).abi.bits() as u32,
1765 create_DIArray(DIB(cx), &tags),
1766 type_metadata(cx, discr_enum_ty),
1771 let variant_info = variant_info_for(dataful_variant);
1772 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1774 dataful_variant_layout,
1779 let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1781 set_members_of_composite_type(
1784 variant_type_metadata,
1785 member_descriptions,
1786 Some(&self.common_members),
1790 cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1794 // Name the dataful variant so that we can identify it for natvis
1795 name: "dataful_variant".to_string(),
1796 type_metadata: variant_type_metadata,
1798 size: self.layout.size,
1799 align: self.layout.align.abi,
1800 flags: DIFlags::FlagZero,
1802 source_info: variant_info.source_info(cx),
1805 name: "discriminant".into(),
1806 type_metadata: discr_enum,
1807 offset: dataful_variant_layout.fields.offset(tag_field),
1810 flags: DIFlags::FlagZero,
1819 let variant = self.layout.for_variant(cx, i);
1820 let variant_info = variant_info_for(i);
1821 let (variant_type_metadata, member_desc_factory) =
1822 describe_enum_variant(cx, variant, variant_info, self_metadata);
1824 let member_descriptions =
1825 member_desc_factory.create_member_descriptions(cx);
1827 set_members_of_composite_type(
1830 variant_type_metadata,
1831 member_descriptions,
1832 Some(&self.common_members),
1835 let niche_value = calculate_niche_value(i);
1838 name: variant_info.variant_name(),
1839 type_metadata: variant_type_metadata,
1841 size: self.layout.size,
1842 align: self.layout.align.abi,
1843 flags: DIFlags::FlagZero,
1844 discriminant: niche_value,
1845 source_info: variant_info.source_info(cx),
1855 // Creates `MemberDescription`s for the fields of a single enum variant.
1856 struct VariantMemberDescriptionFactory<'tcx> {
1857 /// Cloned from the `layout::Struct` describing the variant.
1859 args: Vec<(String, Ty<'tcx>)>,
1862 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1863 fn create_member_descriptions<'ll>(
1865 cx: &CodegenCx<'ll, 'tcx>,
1866 ) -> Vec<MemberDescription<'ll>> {
1870 .map(|(i, &(ref name, ty))| {
1871 let (size, align) = cx.size_and_align_of(ty);
1873 name: name.to_string(),
1874 type_metadata: type_metadata(cx, ty),
1875 offset: self.offsets[i],
1878 flags: DIFlags::FlagZero,
1887 #[derive(Copy, Clone)]
1888 enum VariantInfo<'a, 'tcx> {
1889 Adt(&'tcx ty::VariantDef),
1892 generator_layout: &'tcx GeneratorLayout<'tcx>,
1893 generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1894 variant_index: VariantIdx,
1898 impl<'tcx> VariantInfo<'_, 'tcx> {
1899 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1901 VariantInfo::Adt(variant) => f(variant.name.as_str()),
1902 VariantInfo::Generator { variant_index, .. } => {
1903 f(&GeneratorSubsts::variant_name(*variant_index))
1908 fn variant_name(&self) -> String {
1910 VariantInfo::Adt(variant) => variant.name.to_string(),
1911 VariantInfo::Generator { variant_index, .. } => {
1912 // Since GDB currently prints out the raw discriminant along
1913 // with every variant, make each variant name be just the value
1914 // of the discriminant. The struct name for the variant includes
1915 // the actual variant description.
1916 format!("{}", variant_index.as_usize())
1921 fn field_name(&self, i: usize) -> String {
1922 let field_name = match *self {
1923 VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1924 Some(variant.fields[i].name)
1926 VariantInfo::Generator {
1928 generator_saved_local_names,
1932 generator_saved_local_names
1933 [generator_layout.variant_fields[variant_index][i.into()]]
1937 field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1940 fn source_info<'ll>(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1941 if let VariantInfo::Generator { def_id, variant_index, .. } = self {
1943 cx.tcx.generator_layout(*def_id).unwrap().variant_source_info[*variant_index].span;
1944 if !span.is_dummy() {
1945 let loc = cx.lookup_debug_loc(span.lo());
1946 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
1953 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1954 /// `MemberDescriptionFactory` for producing the descriptions of the
1955 /// fields of the variant. This is a rudimentary version of a full
1956 /// `RecursiveTypeDescription`.
1957 fn describe_enum_variant<'ll, 'tcx>(
1958 cx: &CodegenCx<'ll, 'tcx>,
1959 layout: layout::TyAndLayout<'tcx>,
1960 variant: VariantInfo<'_, 'tcx>,
1961 containing_scope: &'ll DIScope,
1962 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1963 let metadata_stub = variant.map_struct_name(|variant_name| {
1964 let unique_type_id = debug_context(cx)
1967 .get_unique_type_id_of_enum_variant(cx, layout.ty, variant_name);
1973 Some(containing_scope),
1978 let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
1979 let args = (0..layout.fields.count())
1980 .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
1983 let member_description_factory = VariantMDF(VariantMemberDescriptionFactory { offsets, args });
1985 (metadata_stub, member_description_factory)
1988 fn prepare_enum_metadata<'ll, 'tcx>(
1989 cx: &CodegenCx<'ll, 'tcx>,
1990 enum_type: Ty<'tcx>,
1992 unique_type_id: UniqueTypeId,
1993 outer_field_tys: Vec<Ty<'tcx>>,
1994 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1996 let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
1998 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1999 // FIXME: This should emit actual file metadata for the enum, but we
2000 // currently can't get the necessary information when it comes to types
2001 // imported from other crates. Formerly we violated the ODR when performing
2002 // LTO because we emitted debuginfo for the same type with varying file
2003 // metadata, so as a workaround we pretend that the type comes from
2005 let file_metadata = unknown_file_metadata(cx);
2007 let discriminant_type_metadata = |discr: Primitive| {
2008 let enumerators_metadata: Vec<_> = match enum_type.kind() {
2009 ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
2010 .map(|((_, discr), v)| {
2011 let name = v.name.as_str();
2012 let is_unsigned = match discr.ty.kind() {
2013 ty::Int(_) => false,
2014 ty::Uint(_) => true,
2015 _ => bug!("non integer discriminant"),
2018 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2020 name.as_ptr().cast(),
2022 // FIXME: what if enumeration has i128 discriminant?
2029 ty::Generator(_, substs, _) => substs
2031 .variant_range(enum_def_id, tcx)
2032 .map(|variant_index| {
2033 debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
2034 let name = GeneratorSubsts::variant_name(variant_index);
2036 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2038 name.as_ptr().cast(),
2040 // Generators use u32 as discriminant type, verified above.
2041 variant_index.as_u32().into(),
2050 let disr_type_key = (enum_def_id, discr);
2051 let cached_discriminant_type_metadata =
2052 debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2053 match cached_discriminant_type_metadata {
2054 Some(discriminant_type_metadata) => discriminant_type_metadata,
2056 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2057 let discriminant_base_type_metadata = type_metadata(cx, discr.to_ty(tcx));
2060 let discriminant_name = match enum_type.kind() {
2062 item_name = tcx.item_name(enum_def_id);
2065 ty::Generator(..) => enum_name.as_str(),
2069 let discriminant_type_metadata = unsafe {
2070 llvm::LLVMRustDIBuilderCreateEnumerationType(
2073 discriminant_name.as_ptr().cast(),
2074 discriminant_name.len(),
2076 UNKNOWN_LINE_NUMBER,
2077 discriminant_size.bits(),
2078 discriminant_align.abi.bits() as u32,
2079 create_DIArray(DIB(cx), &enumerators_metadata),
2080 discriminant_base_type_metadata,
2086 .created_enum_disr_types
2088 .insert(disr_type_key, discriminant_type_metadata);
2090 discriminant_type_metadata
2095 let layout = cx.layout_of(enum_type);
2097 if let (Abi::Scalar(_), Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. }) =
2098 (layout.abi, &layout.variants)
2100 return FinalMetadata(discriminant_type_metadata(tag.value));
2103 // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
2104 // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
2105 // msvc, then we need to use a different encoding of the debuginfo.
2106 if cpp_like_debuginfo(tcx) {
2107 let discriminant_type_metadata = match layout.variants {
2108 Variants::Single { .. } => None,
2109 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, .. }
2110 | Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. } => {
2111 Some(discriminant_type_metadata(tag.value))
2115 let enum_metadata = {
2116 let type_map = debug_context(cx).type_map.borrow();
2117 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2120 llvm::LLVMRustDIBuilderCreateUnionType(
2123 enum_name.as_ptr().cast(),
2126 UNKNOWN_LINE_NUMBER,
2128 layout.align.abi.bits() as u32,
2132 unique_type_id_str.as_ptr().cast(),
2133 unique_type_id_str.len(),
2138 return create_and_register_recursive_type_forward_declaration(
2144 EnumMDF(EnumMemberDescriptionFactory {
2147 tag_type_metadata: discriminant_type_metadata,
2148 common_members: vec![],
2153 let discriminator_name = match enum_type.kind() {
2154 ty::Generator(..) => "__state",
2157 let discriminator_metadata = match layout.variants {
2158 // A single-variant enum has no discriminant.
2159 Variants::Single { .. } => None,
2161 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, tag_field, .. } => {
2162 // Find the integer type of the correct size.
2163 let size = tag.value.size(cx);
2164 let align = tag.value.align(cx);
2166 let tag_type = match tag.value {
2168 F32 => Integer::I32,
2169 F64 => Integer::I64,
2170 Pointer => cx.data_layout().ptr_sized_integer(),
2172 .to_ty(cx.tcx, false);
2174 let tag_metadata = basic_type_metadata(cx, tag_type);
2176 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2179 discriminator_name.as_ptr().cast(),
2180 discriminator_name.len(),
2182 UNKNOWN_LINE_NUMBER,
2184 align.abi.bits() as u32,
2185 layout.fields.offset(tag_field).bits(),
2186 DIFlags::FlagArtificial,
2192 Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, tag_field, .. } => {
2193 let discr_type = tag.value.to_ty(cx.tcx);
2194 let (size, align) = cx.size_and_align_of(discr_type);
2196 let discr_metadata = basic_type_metadata(cx, discr_type);
2198 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2201 discriminator_name.as_ptr().cast(),
2202 discriminator_name.len(),
2204 UNKNOWN_LINE_NUMBER,
2206 align.bits() as u32,
2207 layout.fields.offset(tag_field).bits(),
2208 DIFlags::FlagArtificial,
2215 let outer_fields = match layout.variants {
2216 Variants::Single { .. } => vec![],
2217 Variants::Multiple { .. } => {
2219 TupleMemberDescriptionFactory { ty: enum_type, component_types: outer_field_tys };
2221 .create_member_descriptions(cx)
2223 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2228 let variant_part_unique_type_id_str = debug_context(cx)
2231 .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2232 let empty_array = create_DIArray(DIB(cx), &[]);
2234 let variant_part = unsafe {
2235 llvm::LLVMRustDIBuilderCreateVariantPart(
2238 name.as_ptr().cast(),
2241 UNKNOWN_LINE_NUMBER,
2243 layout.align.abi.bits() as u32,
2245 discriminator_metadata,
2247 variant_part_unique_type_id_str.as_ptr().cast(),
2248 variant_part_unique_type_id_str.len(),
2252 let struct_wrapper = {
2253 // The variant part must be wrapped in a struct according to DWARF.
2254 // All fields except the discriminant (including `outer_fields`)
2255 // should be put into structures inside the variant part, which gives
2256 // an equivalent layout but offers us much better integration with
2258 let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2260 let type_map = debug_context(cx).type_map.borrow();
2261 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2264 llvm::LLVMRustDIBuilderCreateStructType(
2266 Some(containing_scope),
2267 enum_name.as_ptr().cast(),
2270 UNKNOWN_LINE_NUMBER,
2272 layout.align.abi.bits() as u32,
2278 unique_type_id_str.as_ptr().cast(),
2279 unique_type_id_str.len(),
2284 create_and_register_recursive_type_forward_declaration(
2290 EnumMDF(EnumMemberDescriptionFactory {
2293 tag_type_metadata: None,
2294 common_members: outer_fields,
2299 /// Creates debug information for a composite type, that is, anything that
2300 /// results in a LLVM struct.
2302 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2303 fn composite_type_metadata<'ll, 'tcx>(
2304 cx: &CodegenCx<'ll, 'tcx>,
2305 composite_type: Ty<'tcx>,
2306 composite_type_name: &str,
2307 composite_type_unique_id: UniqueTypeId,
2308 member_descriptions: Vec<MemberDescription<'ll>>,
2309 containing_scope: Option<&'ll DIScope>,
2310 ) -> &'ll DICompositeType {
2311 // Create the (empty) struct metadata node ...
2312 let composite_type_metadata = create_struct_stub(
2315 composite_type_name,
2316 composite_type_unique_id,
2320 // ... and immediately create and add the member descriptions.
2321 set_members_of_composite_type(
2324 composite_type_metadata,
2325 member_descriptions,
2329 composite_type_metadata
2332 fn set_members_of_composite_type<'ll, 'tcx>(
2333 cx: &CodegenCx<'ll, 'tcx>,
2334 composite_type: Ty<'tcx>,
2335 composite_type_metadata: &'ll DICompositeType,
2336 member_descriptions: Vec<MemberDescription<'ll>>,
2337 common_members: Option<&Vec<Option<&'ll DIType>>>,
2339 // In some rare cases LLVM metadata uniquing would lead to an existing type
2340 // description being used instead of a new one created in
2341 // create_struct_stub. This would cause a hard to trace assertion in
2342 // DICompositeType::SetTypeArray(). The following check makes sure that we
2343 // get a better error message if this should happen again due to some
2346 let mut composite_types_completed =
2347 debug_context(cx).composite_types_completed.borrow_mut();
2348 if !composite_types_completed.insert(composite_type_metadata) {
2350 "debuginfo::set_members_of_composite_type() - \
2351 Already completed forward declaration re-encountered."
2356 let mut member_metadata: Vec<_> = member_descriptions
2358 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2360 if let Some(other_members) = common_members {
2361 member_metadata.extend(other_members.iter());
2364 let type_params = compute_type_parameters(cx, composite_type);
2366 let type_array = create_DIArray(DIB(cx), &member_metadata);
2367 llvm::LLVMRustDICompositeTypeReplaceArrays(
2369 composite_type_metadata,
2376 /// Computes the type parameters for a type, if any, for the given metadata.
2377 fn compute_type_parameters<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2378 if let ty::Adt(def, substs) = *ty.kind() {
2379 if substs.types().next().is_some() {
2380 let generics = cx.tcx.generics_of(def.did);
2381 let names = get_parameter_names(cx, generics);
2382 let template_params: Vec<_> = iter::zip(substs, names)
2383 .filter_map(|(kind, name)| {
2384 if let GenericArgKind::Type(ty) = kind.unpack() {
2386 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2387 let actual_type_metadata = type_metadata(cx, actual_type);
2388 let name = name.as_str();
2390 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2393 name.as_ptr().cast(),
2395 actual_type_metadata,
2404 return create_DIArray(DIB(cx), &template_params);
2407 return create_DIArray(DIB(cx), &[]);
2409 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2410 let mut names = generics
2412 .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2413 names.extend(generics.params.iter().map(|param| param.name));
2418 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2419 /// any caching, does not add any fields to the struct. This can be done later
2420 /// with `set_members_of_composite_type()`.
2421 fn create_struct_stub<'ll, 'tcx>(
2422 cx: &CodegenCx<'ll, 'tcx>,
2423 struct_type: Ty<'tcx>,
2424 struct_type_name: &str,
2425 unique_type_id: UniqueTypeId,
2426 containing_scope: Option<&'ll DIScope>,
2428 ) -> &'ll DICompositeType {
2429 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2431 let type_map = debug_context(cx).type_map.borrow();
2432 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2434 let metadata_stub = unsafe {
2435 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2436 // pointer will lead to hard to trace and debug LLVM assertions
2437 // later on in `llvm/lib/IR/Value.cpp`.
2438 let empty_array = create_DIArray(DIB(cx), &[]);
2440 llvm::LLVMRustDIBuilderCreateStructType(
2443 struct_type_name.as_ptr().cast(),
2444 struct_type_name.len(),
2445 unknown_file_metadata(cx),
2446 UNKNOWN_LINE_NUMBER,
2448 struct_align.bits() as u32,
2454 unique_type_id.as_ptr().cast(),
2455 unique_type_id.len(),
2462 fn create_union_stub<'ll, 'tcx>(
2463 cx: &CodegenCx<'ll, 'tcx>,
2464 union_type: Ty<'tcx>,
2465 union_type_name: &str,
2466 unique_type_id: UniqueTypeId,
2467 containing_scope: &'ll DIScope,
2468 ) -> &'ll DICompositeType {
2469 let (union_size, union_align) = cx.size_and_align_of(union_type);
2471 let type_map = debug_context(cx).type_map.borrow();
2472 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2474 let metadata_stub = unsafe {
2475 // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2476 // pointer will lead to hard to trace and debug LLVM assertions
2477 // later on in `llvm/lib/IR/Value.cpp`.
2478 let empty_array = create_DIArray(DIB(cx), &[]);
2480 llvm::LLVMRustDIBuilderCreateUnionType(
2482 Some(containing_scope),
2483 union_type_name.as_ptr().cast(),
2484 union_type_name.len(),
2485 unknown_file_metadata(cx),
2486 UNKNOWN_LINE_NUMBER,
2488 union_align.bits() as u32,
2492 unique_type_id.as_ptr().cast(),
2493 unique_type_id.len(),
2500 /// Creates debug information for the given global variable.
2502 /// Adds the created metadata nodes directly to the crate's IR.
2503 pub fn create_global_var_metadata<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2504 if cx.dbg_cx.is_none() {
2508 // Only create type information if full debuginfo is enabled
2509 if cx.sess().opts.debuginfo != DebugInfo::Full {
2515 // We may want to remove the namespace scope if we're in an extern block (see
2516 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2517 let var_scope = get_namespace_for_item(cx, def_id);
2518 let span = tcx.def_span(def_id);
2520 let (file_metadata, line_number) = if !span.is_dummy() {
2521 let loc = cx.lookup_debug_loc(span.lo());
2522 (file_metadata(cx, &loc.file), loc.line)
2524 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2527 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2528 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2529 let type_metadata = type_metadata(cx, variable_type);
2530 let var_name = tcx.item_name(def_id);
2531 let var_name = var_name.as_str();
2532 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2533 // When empty, linkage_name field is omitted,
2534 // which is what we want for no_mangle statics
2535 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2537 let global_align = cx.align_of(variable_type);
2540 llvm::LLVMRustDIBuilderCreateStaticVariable(
2543 var_name.as_ptr().cast(),
2545 linkage_name.as_ptr().cast(),
2553 global_align.bytes() as u32,
2558 /// Generates LLVM debuginfo for a vtable.
2559 fn vtable_type_metadata<'ll, 'tcx>(
2560 cx: &CodegenCx<'ll, 'tcx>,
2562 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2566 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
2567 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
2568 let trait_ref = tcx.erase_regions(trait_ref);
2570 tcx.vtable_entries(trait_ref)
2572 COMMON_VTABLE_ENTRIES
2575 // FIXME: We describe the vtable as an array of *const () pointers. The length of the array is
2576 // correct - but we could create a more accurate description, e.g. by describing it
2577 // as a struct where each field has a name that corresponds to the name of the method
2579 // However, this is not entirely straightforward because there might be multiple
2580 // methods with the same name if the vtable is for multiple traits. So for now we keep
2581 // things simple instead of adding some ad-hoc disambiguation scheme.
2582 let vtable_type = tcx.mk_array(tcx.mk_imm_ptr(tcx.types.unit), vtable_entries.len() as u64);
2584 type_metadata(cx, vtable_type)
2587 /// Creates debug information for the given vtable, which is for the
2590 /// Adds the created metadata nodes directly to the crate's IR.
2591 pub fn create_vtable_metadata<'ll, 'tcx>(
2592 cx: &CodegenCx<'ll, 'tcx>,
2594 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2597 if cx.dbg_cx.is_none() {
2601 // Only create type information if full debuginfo is enabled
2602 if cx.sess().opts.debuginfo != DebugInfo::Full {
2606 let vtable_name = compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref);
2607 let vtable_type = vtable_type_metadata(cx, ty, poly_trait_ref);
2610 let linkage_name = "";
2611 llvm::LLVMRustDIBuilderCreateStaticVariable(
2614 vtable_name.as_ptr().cast(),
2616 linkage_name.as_ptr().cast(),
2618 unknown_file_metadata(cx),
2619 UNKNOWN_LINE_NUMBER,
2629 /// Creates an "extension" of an existing `DIScope` into another file.
2630 pub fn extend_scope_to_file<'ll>(
2631 cx: &CodegenCx<'ll, '_>,
2632 scope_metadata: &'ll DIScope,
2634 ) -> &'ll DILexicalBlock {
2635 let file_metadata = file_metadata(cx, file);
2636 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }