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;
14 use crate::llvm::debuginfo::{
15 DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
18 use crate::value::Value;
21 use rustc_codegen_ssa::traits::*;
22 use rustc_data_structures::fingerprint::Fingerprint;
23 use rustc_data_structures::fx::FxHashMap;
24 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
25 use rustc_fs_util::path_to_c_string;
26 use rustc_hir::def::CtorKind;
27 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_middle::mir::{self, GeneratorLayout};
30 use rustc_middle::ty::layout::{self, IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout};
31 use rustc_middle::ty::subst::GenericArgKind;
32 use rustc_middle::ty::{
33 self, AdtKind, GeneratorSubsts, Instance, ParamEnv, Ty, TyCtxt, COMMON_VTABLE_ENTRIES,
35 use rustc_middle::{bug, span_bug};
36 use rustc_query_system::ich::NodeIdHashingMode;
37 use rustc_session::config::{self, DebugInfo};
38 use rustc_span::symbol::Symbol;
39 use rustc_span::FileNameDisplayPreference;
40 use rustc_span::{self, SourceFile, SourceFileHash, Span};
41 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, TagEncoding};
42 use rustc_target::abi::{Int, Pointer, F32, F64};
43 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
46 use libc::{c_longlong, c_uint};
47 use std::collections::hash_map::Entry;
48 use std::fmt::{self, Write};
49 use std::hash::{Hash, Hasher};
51 use std::path::{Path, PathBuf};
54 impl PartialEq for llvm::Metadata {
55 fn eq(&self, other: &Self) -> bool {
60 impl Eq for llvm::Metadata {}
62 impl Hash for llvm::Metadata {
63 fn hash<H: Hasher>(&self, hasher: &mut H) {
64 (self as *const Self).hash(hasher);
68 impl fmt::Debug for llvm::Metadata {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 (self as *const Self).fmt(f)
75 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
76 const DW_LANG_RUST: c_uint = 0x1c;
77 #[allow(non_upper_case_globals)]
78 const DW_ATE_boolean: c_uint = 0x02;
79 #[allow(non_upper_case_globals)]
80 const DW_ATE_float: c_uint = 0x04;
81 #[allow(non_upper_case_globals)]
82 const DW_ATE_signed: c_uint = 0x05;
83 #[allow(non_upper_case_globals)]
84 const DW_ATE_unsigned: c_uint = 0x07;
85 #[allow(non_upper_case_globals)]
86 const DW_ATE_unsigned_char: c_uint = 0x08;
88 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
89 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
91 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
95 use rustc_arena::DroplessArena;
97 #[derive(Copy, Hash, Eq, PartialEq, Clone)]
98 pub(super) struct UniqueTypeId(u32);
100 // The `&'static str`s in this type actually point into the arena.
102 // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
103 // found that to regress performance up to 2% in some cases. This might be
104 // revisited after further improvements to `indexmap`.
106 pub(super) struct TypeIdInterner {
107 arena: DroplessArena,
108 names: FxHashMap<&'static str, UniqueTypeId>,
109 strings: Vec<&'static str>,
112 impl TypeIdInterner {
114 pub(super) fn intern(&mut self, string: &str) -> UniqueTypeId {
115 if let Some(&name) = self.names.get(string) {
119 let name = UniqueTypeId(self.strings.len() as u32);
121 // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
124 unsafe { std::str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
125 // It is safe to extend the arena allocation to `'static` because we only access
126 // these while the arena is still alive.
127 let string: &'static str = unsafe { &*(string as *const str) };
128 self.strings.push(string);
129 self.names.insert(string, name);
133 // Get the symbol as a string. `Symbol::as_str()` should be used in
134 // preference to this function.
135 pub(super) fn get(&self, symbol: UniqueTypeId) -> &str {
136 self.strings[symbol.0 as usize]
140 use unique_type_id::*;
142 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
143 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
144 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
147 pub struct TypeMap<'ll, 'tcx> {
148 /// The `UniqueTypeId`s created so far.
149 unique_id_interner: TypeIdInterner,
150 /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
151 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
152 /// A map from types to debuginfo metadata. This is an N:1 mapping.
153 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
154 /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
155 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
158 impl<'ll, 'tcx> TypeMap<'ll, 'tcx> {
159 /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
160 /// the mapping already exists.
161 fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
162 if self.type_to_metadata.insert(type_, metadata).is_some() {
163 bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
167 /// Removes a `Ty`-to-metadata mapping.
168 /// This is useful when computing the metadata for a potentially
169 /// recursive type (e.g., a function pointer of the form:
171 /// fn foo() -> impl Copy { foo }
173 /// This kind of type cannot be properly represented
174 /// via LLVM debuginfo. As a workaround,
175 /// we register a temporary Ty to metadata mapping
176 /// for the function before we compute its actual metadata.
177 /// If the metadata computation ends up recursing back to the
178 /// original function, it will use the temporary mapping
179 /// for the inner self-reference, preventing us from
180 /// recursing forever.
182 /// This function is used to remove the temporary metadata
183 /// mapping after we've computed the actual metadata.
184 fn remove_type(&mut self, type_: Ty<'tcx>) {
185 if self.type_to_metadata.remove(type_).is_none() {
186 bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", type_);
190 /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
191 /// fail if the mapping already exists.
192 fn register_unique_id_with_metadata(
194 unique_type_id: UniqueTypeId,
195 metadata: &'ll DIType,
197 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
199 "type metadata for unique ID '{}' is already in the `TypeMap`!",
200 self.get_unique_type_id_as_string(unique_type_id)
205 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
206 self.type_to_metadata.get(&type_).cloned()
209 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
210 self.unique_id_to_metadata.get(&unique_type_id).cloned()
213 /// Gets the string representation of a `UniqueTypeId`. This method will fail if
214 /// the ID is unknown.
215 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
216 self.unique_id_interner.get(unique_type_id)
219 /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
220 /// type has been requested before, this is just a table lookup. Otherwise, an
221 /// ID will be generated and stored for later lookup.
222 fn get_unique_type_id_of_type<'a>(
224 cx: &CodegenCx<'a, 'tcx>,
227 // Let's see if we already have something in the cache.
228 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
229 return unique_type_id;
231 // If not, generate one.
233 // The hasher we are using to generate the UniqueTypeId. We want
234 // something that provides more than the 64 bits of the DefaultHasher.
235 let mut hasher = StableHasher::new();
236 let mut hcx = cx.tcx.create_stable_hashing_context();
237 let type_ = cx.tcx.erase_regions(type_);
238 hcx.while_hashing_spans(false, |hcx| {
239 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
240 type_.hash_stable(hcx, &mut hasher);
243 let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
245 let key = self.unique_id_interner.intern(&unique_type_id);
246 self.type_to_unique_id.insert(type_, key);
251 /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
252 /// types of their own, so they need special handling. We still need a
253 /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
254 fn get_unique_type_id_of_enum_variant<'a>(
256 cx: &CodegenCx<'a, 'tcx>,
260 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
261 let enum_variant_type_id =
262 format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
263 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
267 /// Gets the unique type ID string for an enum variant part.
268 /// Variant parts are not types and shouldn't really have their own ID,
269 /// but it makes `set_members_of_composite_type()` simpler.
270 fn get_unique_type_id_str_of_enum_variant_part(
272 enum_type_id: UniqueTypeId,
274 format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id))
278 /// A description of some recursive type. It can either be already finished (as
279 /// with `FinalMetadata`) or it is not yet finished, but contains all information
280 /// needed to generate the missing parts of the description. See the
281 /// documentation section on Recursive Types at the top of this file for more
283 enum RecursiveTypeDescription<'ll, 'tcx> {
285 unfinished_type: Ty<'tcx>,
286 unique_type_id: UniqueTypeId,
287 metadata_stub: &'ll DICompositeType,
288 member_holding_stub: &'ll DICompositeType,
289 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
291 FinalMetadata(&'ll DICompositeType),
294 fn create_and_register_recursive_type_forward_declaration<'ll, 'tcx>(
295 cx: &CodegenCx<'ll, 'tcx>,
296 unfinished_type: Ty<'tcx>,
297 unique_type_id: UniqueTypeId,
298 metadata_stub: &'ll DICompositeType,
299 member_holding_stub: &'ll DICompositeType,
300 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
301 ) -> RecursiveTypeDescription<'ll, 'tcx> {
302 // Insert the stub into the `TypeMap` in order to allow for recursive references.
303 let mut type_map = debug_context(cx).type_map.borrow_mut();
304 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
305 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
312 member_description_factory,
316 impl<'ll, 'tcx> RecursiveTypeDescription<'ll, 'tcx> {
317 /// Finishes up the description of the type in question (mostly by providing
318 /// descriptions of the fields of the given type) and returns the final type
320 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
322 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
328 ref member_description_factory,
330 // Make sure that we have a forward declaration of the type in
331 // the TypeMap so that recursive references are possible. This
332 // will always be the case if the RecursiveTypeDescription has
333 // been properly created through the
334 // `create_and_register_recursive_type_forward_declaration()`
337 let type_map = debug_context(cx).type_map.borrow();
338 if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
339 || type_map.find_metadata_for_type(unfinished_type).is_none()
342 "Forward declaration of potentially recursive type \
343 '{:?}' was not found in TypeMap!",
349 // ... then create the member descriptions ...
350 let member_descriptions = member_description_factory.create_member_descriptions(cx);
352 // ... and attach them to the stub to complete it.
353 set_members_of_composite_type(
360 MetadataCreationResult::new(metadata_stub, true)
366 /// Returns from the enclosing function if the type metadata with the given
367 /// unique ID can be found in the type map.
368 macro_rules! return_if_metadata_created_in_meantime {
369 ($cx: expr, $unique_type_id: expr) => {
370 if let Some(metadata) =
371 debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
373 return MetadataCreationResult::new(metadata, true);
378 fn fixed_vec_metadata<'ll, 'tcx>(
379 cx: &CodegenCx<'ll, 'tcx>,
380 unique_type_id: UniqueTypeId,
381 array_or_slice_type: Ty<'tcx>,
382 element_type: Ty<'tcx>,
384 ) -> MetadataCreationResult<'ll> {
385 let element_type_metadata = type_metadata(cx, element_type, span);
387 return_if_metadata_created_in_meantime!(cx, unique_type_id);
389 let (size, align) = cx.size_and_align_of(array_or_slice_type);
391 let upper_bound = match array_or_slice_type.kind() {
392 ty::Array(_, len) => len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong,
397 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
399 let subscripts = create_DIArray(DIB(cx), &[subrange]);
400 let metadata = unsafe {
401 llvm::LLVMRustDIBuilderCreateArrayType(
405 element_type_metadata,
410 MetadataCreationResult::new(metadata, false)
413 fn vec_slice_metadata<'ll, 'tcx>(
414 cx: &CodegenCx<'ll, 'tcx>,
415 slice_ptr_type: Ty<'tcx>,
416 element_type: Ty<'tcx>,
417 unique_type_id: UniqueTypeId,
419 ) -> MetadataCreationResult<'ll> {
420 let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
422 let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
424 return_if_metadata_created_in_meantime!(cx, unique_type_id);
426 let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
428 let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
429 let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
431 let member_descriptions = vec![
433 name: "data_ptr".to_owned(),
434 type_metadata: data_ptr_metadata,
437 align: pointer_align,
438 flags: DIFlags::FlagZero,
443 name: "length".to_owned(),
444 type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
445 offset: pointer_size,
448 flags: DIFlags::FlagZero,
454 let file_metadata = unknown_file_metadata(cx);
456 let metadata = composite_type_metadata(
466 MetadataCreationResult::new(metadata, false)
469 fn subroutine_type_metadata<'ll, 'tcx>(
470 cx: &CodegenCx<'ll, 'tcx>,
471 unique_type_id: UniqueTypeId,
472 signature: ty::PolyFnSig<'tcx>,
474 ) -> MetadataCreationResult<'ll> {
476 cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), signature);
478 let signature_metadata: Vec<_> = iter::once(
480 match signature.output().kind() {
481 ty::Tuple(tys) if tys.is_empty() => None,
482 _ => Some(type_metadata(cx, signature.output(), span)),
487 signature.inputs().iter().map(|argument_type| Some(type_metadata(cx, argument_type, span))),
491 return_if_metadata_created_in_meantime!(cx, unique_type_id);
493 MetadataCreationResult::new(
495 llvm::LLVMRustDIBuilderCreateSubroutineType(
497 create_DIArray(DIB(cx), &signature_metadata[..]),
504 // FIXME(1563): This is all a bit of a hack because 'trait pointer' is an ill-
505 // defined concept. For the case of an actual trait pointer (i.e., `Box<Trait>`,
506 // `&Trait`), `trait_object_type` should be the whole thing (e.g, `Box<Trait>`) and
507 // `trait_type` should be the actual trait (e.g., `Trait`). Where the trait is part
508 // of a DST struct, there is no `trait_object_type` and the results of this
509 // function will be a little bit weird.
510 fn trait_pointer_metadata<'ll, 'tcx>(
511 cx: &CodegenCx<'ll, 'tcx>,
512 trait_type: Ty<'tcx>,
513 trait_object_type: Option<Ty<'tcx>>,
514 unique_type_id: UniqueTypeId,
516 // The implementation provided here is a stub. It makes sure that the trait
517 // type is assigned the correct name, size, namespace, and source location.
518 // However, it does not describe the trait's methods.
520 let (containing_scope, trait_type_name) = match trait_object_type {
521 Some(trait_object_type) => match trait_object_type.kind() {
523 Some(get_namespace_for_item(cx, def.did)),
524 compute_debuginfo_type_name(cx.tcx, trait_object_type, false),
526 ty::RawPtr(_) | ty::Ref(..) => {
527 (NO_SCOPE_METADATA, compute_debuginfo_type_name(cx.tcx, trait_object_type, true))
531 "debuginfo: unexpected trait-object type in \
532 trait_pointer_metadata(): {:?}",
538 // No object type, use the trait type directly (no scope here since the type
539 // will be wrapped in the dyn$ synthetic type).
540 None => (NO_SCOPE_METADATA, compute_debuginfo_type_name(cx.tcx, trait_type, true)),
543 let file_metadata = unknown_file_metadata(cx);
545 let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
547 assert_eq!(abi::FAT_PTR_ADDR, 0);
548 assert_eq!(abi::FAT_PTR_EXTRA, 1);
550 let data_ptr_field = layout.field(cx, 0);
551 let vtable_field = layout.field(cx, 1);
552 let member_descriptions = vec![
554 name: "pointer".to_owned(),
555 type_metadata: type_metadata(
557 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
558 rustc_span::DUMMY_SP,
560 offset: layout.fields.offset(0),
561 size: data_ptr_field.size,
562 align: data_ptr_field.align.abi,
563 flags: DIFlags::FlagArtificial,
568 name: "vtable".to_owned(),
569 type_metadata: type_metadata(cx, vtable_field.ty, rustc_span::DUMMY_SP),
570 offset: layout.fields.offset(1),
571 size: vtable_field.size,
572 align: vtable_field.align.abi,
573 flags: DIFlags::FlagArtificial,
579 composite_type_metadata(
581 trait_object_type.unwrap_or(trait_type),
587 rustc_span::DUMMY_SP,
591 pub fn type_metadata<'ll, 'tcx>(
592 cx: &CodegenCx<'ll, 'tcx>,
594 usage_site_span: Span,
596 // Get the unique type ID of this type.
597 let unique_type_id = {
598 let mut type_map = debug_context(cx).type_map.borrow_mut();
599 // First, try to find the type in `TypeMap`. If we have seen it before, we
600 // can exit early here.
601 match type_map.find_metadata_for_type(t) {
606 // The Ty is not in the `TypeMap` but maybe we have already seen
607 // an equivalent type (e.g., only differing in region arguments).
608 // In order to find out, generate the unique type ID and look
610 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
611 match type_map.find_metadata_for_unique_id(unique_type_id) {
613 // There is already an equivalent type in the TypeMap.
614 // Register this Ty as an alias in the cache and
615 // return the cached metadata.
616 type_map.register_type_with_metadata(t, metadata);
620 // There really is no type metadata for this type, so
621 // proceed by creating it.
629 debug!("type_metadata: {:?}", t);
631 let ptr_metadata = |ty: Ty<'tcx>| match *ty.kind() {
632 ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)),
633 ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)),
634 ty::Dynamic(..) => Ok(MetadataCreationResult::new(
635 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
639 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
641 if let Some(metadata) =
642 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
644 return Err(metadata);
647 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), false))
651 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
652 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
653 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
655 ty::Tuple(elements) if elements.is_empty() => {
656 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
658 ty::Array(typ, _) | ty::Slice(typ) => {
659 fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
661 ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span),
663 MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false)
666 MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
668 ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => match ptr_metadata(ty) {
670 Err(metadata) => return metadata,
672 ty::Adt(def, _) if def.is_box() => match ptr_metadata(t.boxed_ty()) {
674 Err(metadata) => return metadata,
676 ty::FnDef(..) | ty::FnPtr(_) => {
677 if let Some(metadata) =
678 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
683 // It's possible to create a self-referential
684 // type in Rust by using 'impl trait':
686 // fn foo() -> impl Copy { foo }
688 // See `TypeMap::remove_type` for more detals
689 // about the workaround.
693 // The choice of type here is pretty arbitrary -
694 // anything reading the debuginfo for a recursive
695 // type is going to see *something* weird - the only
696 // question is what exactly it will see.
697 let name = "<recur_type>";
698 llvm::LLVMRustDIBuilderCreateBasicType(
700 name.as_ptr().cast(),
702 cx.size_of(t).bits(),
708 let type_map = &debug_context(cx).type_map;
709 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
712 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx), usage_site_span)
715 type_map.borrow_mut().remove_type(t);
717 // This is actually a function pointer, so wrap it in pointer DI.
718 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
720 ty::Closure(def_id, substs) => {
721 let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
722 let containing_scope = get_namespace_for_item(cx, def_id);
723 prepare_tuple_metadata(
729 Some(containing_scope),
733 ty::Generator(def_id, substs, _) => {
734 let upvar_tys: Vec<_> = substs
737 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
739 prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span, upvar_tys)
742 ty::Adt(def, ..) => match def.adt_kind() {
744 prepare_struct_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
747 prepare_union_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
750 prepare_enum_metadata(cx, t, def.did, unique_type_id, usage_site_span, vec![])
754 ty::Tuple(elements) => {
755 let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
756 prepare_tuple_metadata(cx, t, &tys, unique_type_id, usage_site_span, NO_SCOPE_METADATA)
759 // Type parameters from polymorphized functions.
760 ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
761 _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
765 let mut type_map = debug_context(cx).type_map.borrow_mut();
767 if already_stored_in_typemap {
768 // Also make sure that we already have a `TypeMap` entry for the unique type ID.
769 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
770 Some(metadata) => metadata,
774 "expected type metadata for unique \
775 type ID '{}' to already be in \
776 the `debuginfo::TypeMap` but it \
778 type_map.get_unique_type_id_as_string(unique_type_id),
784 match type_map.find_metadata_for_type(t) {
786 if metadata != metadata_for_uid {
789 "mismatch between `Ty` and \
790 `UniqueTypeId` maps in \
791 `debuginfo::TypeMap`. \
792 UniqueTypeId={}, Ty={}",
793 type_map.get_unique_type_id_as_string(unique_type_id),
799 type_map.register_type_with_metadata(t, metadata);
803 type_map.register_type_with_metadata(t, metadata);
804 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
811 fn hex_encode(data: &[u8]) -> String {
812 let mut hex_string = String::with_capacity(data.len() * 2);
813 for byte in data.iter() {
814 write!(&mut hex_string, "{:02x}", byte).unwrap();
819 pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
820 debug!("file_metadata: file_name: {:?}", source_file.name);
822 let hash = Some(&source_file.src_hash);
823 let file_name = Some(source_file.name.prefer_remapped().to_string());
824 let directory = if source_file.is_real_file() && !source_file.is_imported() {
829 .to_string_lossy(FileNameDisplayPreference::Remapped)
833 // If the path comes from an upstream crate we assume it has been made
834 // independent of the compiler's working directory one way or another.
837 file_metadata_raw(cx, file_name, directory, hash)
840 pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
841 file_metadata_raw(cx, None, None, None)
844 fn file_metadata_raw<'ll>(
845 cx: &CodegenCx<'ll, '_>,
846 file_name: Option<String>,
847 directory: Option<String>,
848 hash: Option<&SourceFileHash>,
850 let key = (file_name, directory);
852 match debug_context(cx).created_files.borrow_mut().entry(key) {
853 Entry::Occupied(o) => o.get(),
854 Entry::Vacant(v) => {
855 let (file_name, directory) = v.key();
856 debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
858 let file_name = file_name.as_deref().unwrap_or("<unknown>");
859 let directory = directory.as_deref().unwrap_or("");
861 let (hash_kind, hash_value) = match hash {
863 let kind = match hash.kind {
864 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
865 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
866 rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
868 (kind, hex_encode(hash.hash_bytes()))
870 None => (llvm::ChecksumKind::None, String::new()),
873 let file_metadata = unsafe {
874 llvm::LLVMRustDIBuilderCreateFile(
876 file_name.as_ptr().cast(),
878 directory.as_ptr().cast(),
881 hash_value.as_ptr().cast(),
886 v.insert(file_metadata);
892 trait MsvcBasicName {
893 fn msvc_basic_name(self) -> &'static str;
896 impl MsvcBasicName for ty::IntTy {
897 fn msvc_basic_name(self) -> &'static str {
899 ty::IntTy::Isize => "ptrdiff_t",
900 ty::IntTy::I8 => "__int8",
901 ty::IntTy::I16 => "__int16",
902 ty::IntTy::I32 => "__int32",
903 ty::IntTy::I64 => "__int64",
904 ty::IntTy::I128 => "__int128",
909 impl MsvcBasicName for ty::UintTy {
910 fn msvc_basic_name(self) -> &'static str {
912 ty::UintTy::Usize => "size_t",
913 ty::UintTy::U8 => "unsigned __int8",
914 ty::UintTy::U16 => "unsigned __int16",
915 ty::UintTy::U32 => "unsigned __int32",
916 ty::UintTy::U64 => "unsigned __int64",
917 ty::UintTy::U128 => "unsigned __int128",
922 impl MsvcBasicName for ty::FloatTy {
923 fn msvc_basic_name(self) -> &'static str {
925 ty::FloatTy::F32 => "float",
926 ty::FloatTy::F64 => "double",
931 fn basic_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
932 debug!("basic_type_metadata: {:?}", t);
934 // When targeting MSVC, emit MSVC style type names for compatibility with
935 // .natvis visualizers (and perhaps other existing native debuggers?)
936 let msvc_like_names = cx.tcx.sess.target.is_like_msvc;
938 let (name, encoding) = match t.kind() {
939 ty::Never => ("!", DW_ATE_unsigned),
940 ty::Tuple(elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
941 ty::Bool => ("bool", DW_ATE_boolean),
942 ty::Char => ("char", DW_ATE_unsigned_char),
943 ty::Int(int_ty) if msvc_like_names => (int_ty.msvc_basic_name(), DW_ATE_signed),
944 ty::Uint(uint_ty) if msvc_like_names => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
945 ty::Float(float_ty) if msvc_like_names => (float_ty.msvc_basic_name(), DW_ATE_float),
946 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
947 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
948 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
949 _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
952 let ty_metadata = unsafe {
953 llvm::LLVMRustDIBuilderCreateBasicType(
955 name.as_ptr().cast(),
957 cx.size_of(t).bits(),
962 if !msvc_like_names {
966 let typedef_name = match t.kind() {
967 ty::Int(int_ty) => int_ty.name_str(),
968 ty::Uint(uint_ty) => uint_ty.name_str(),
969 ty::Float(float_ty) => float_ty.name_str(),
970 _ => return ty_metadata,
973 let typedef_metadata = unsafe {
974 llvm::LLVMRustDIBuilderCreateTypedef(
977 typedef_name.as_ptr().cast(),
979 unknown_file_metadata(cx),
988 fn foreign_type_metadata<'ll, 'tcx>(
989 cx: &CodegenCx<'ll, 'tcx>,
991 unique_type_id: UniqueTypeId,
993 debug!("foreign_type_metadata: {:?}", t);
995 let name = compute_debuginfo_type_name(cx.tcx, t, false);
996 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA, DIFlags::FlagZero)
999 fn pointer_type_metadata<'ll, 'tcx>(
1000 cx: &CodegenCx<'ll, 'tcx>,
1001 pointer_type: Ty<'tcx>,
1002 pointee_type_metadata: &'ll DIType,
1004 let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
1005 let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
1007 llvm::LLVMRustDIBuilderCreatePointerType(
1009 pointee_type_metadata,
1010 pointer_size.bits(),
1011 pointer_align.bits() as u32,
1012 0, // Ignore DWARF address space.
1013 name.as_ptr().cast(),
1019 fn param_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
1020 debug!("param_type_metadata: {:?}", t);
1021 let name = format!("{:?}", t);
1023 llvm::LLVMRustDIBuilderCreateBasicType(
1025 name.as_ptr().cast(),
1033 pub fn compile_unit_metadata<'ll, 'tcx>(
1035 codegen_unit_name: &str,
1036 debug_context: &CrateDebugContext<'ll, 'tcx>,
1037 ) -> &'ll DIDescriptor {
1038 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
1039 Some(ref path) => path.clone(),
1040 None => PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()),
1043 // To avoid breaking split DWARF, we need to ensure that each codegen unit
1044 // has a unique `DW_AT_name`. This is because there's a remote chance that
1045 // different codegen units for the same module will have entirely
1046 // identical DWARF entries for the purpose of the DWO ID, which would
1047 // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
1048 // specification. LLVM uses the algorithm specified in section 7.32 "Type
1049 // Signature Computation" to compute the DWO ID, which does not include
1050 // any fields that would distinguish compilation units. So we must embed
1051 // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
1053 // Additionally, the OSX linker has an idiosyncrasy where it will ignore
1054 // some debuginfo if multiple object files with the same `DW_AT_name` are
1057 // As a workaround for these two issues, we generate unique names for each
1058 // object file. Those do not correspond to an actual source file but that
1060 name_in_debuginfo.push("@");
1061 name_in_debuginfo.push(codegen_unit_name);
1063 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
1064 let rustc_producer =
1065 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
1066 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
1067 let producer = format!("clang LLVM ({})", rustc_producer);
1069 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1070 let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
1072 let output_filenames = tcx.output_filenames(());
1073 let split_name = if tcx.sess.target_can_use_split_dwarf() {
1075 .split_dwarf_path(tcx.sess.split_debuginfo(), Some(codegen_unit_name))
1076 // We get a path relative to the working directory from split_dwarf_path
1077 .map(|f| tcx.sess.source_map().path_mapping().map_prefix(f).0)
1081 .unwrap_or_default();
1082 let split_name = split_name.to_str().unwrap();
1086 // This should actually be
1088 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1090 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
1091 // we are compiling with "limited" debuginfo. However, some of the
1092 // existing tools relied on slightly more debuginfo being generated than
1093 // would be the case with `LineTablesOnly`, and we did not want to break
1094 // these tools in a "drive-by fix", without a good idea or plan about
1095 // what limited debuginfo should exactly look like. So for now we keep
1096 // the emission kind as `FullDebug`.
1098 // See https://github.com/rust-lang/rust/issues/60020 for details.
1099 let kind = DebugEmissionKind::FullDebug;
1100 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1103 let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
1104 debug_context.builder,
1105 name_in_debuginfo.as_ptr().cast(),
1106 name_in_debuginfo.len(),
1107 work_dir.as_ptr().cast(),
1109 llvm::ChecksumKind::None,
1114 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1115 debug_context.builder,
1118 producer.as_ptr().cast(),
1120 tcx.sess.opts.optimize != config::OptLevel::No,
1121 flags.as_ptr().cast(),
1123 // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1124 // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1126 split_name.as_ptr().cast(),
1130 tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1133 if tcx.sess.opts.debugging_opts.profile {
1134 let cu_desc_metadata =
1135 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1136 let default_gcda_path = &output_filenames.with_extension("gcda");
1138 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1140 let gcov_cu_info = [
1141 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1142 path_to_mdstring(debug_context.llcontext, gcda_path),
1145 let gcov_metadata = llvm::LLVMMDNodeInContext(
1146 debug_context.llcontext,
1147 gcov_cu_info.as_ptr(),
1148 gcov_cu_info.len() as c_uint,
1151 let llvm_gcov_ident = cstr!("llvm.gcov");
1152 llvm::LLVMAddNamedMetadataOperand(
1153 debug_context.llmod,
1154 llvm_gcov_ident.as_ptr(),
1159 // Insert `llvm.ident` metadata on the wasm targets since that will
1160 // get hooked up to the "producer" sections `processed-by` information.
1161 if tcx.sess.target.is_like_wasm {
1162 let name_metadata = llvm::LLVMMDStringInContext(
1163 debug_context.llcontext,
1164 rustc_producer.as_ptr().cast(),
1165 rustc_producer.as_bytes().len() as c_uint,
1167 llvm::LLVMAddNamedMetadataOperand(
1168 debug_context.llmod,
1169 cstr!("llvm.ident").as_ptr(),
1170 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1174 return unit_metadata;
1177 fn path_to_mdstring<'ll>(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1178 let path_str = path_to_c_string(path);
1180 llvm::LLVMMDStringInContext(
1183 path_str.as_bytes().len() as c_uint,
1189 struct MetadataCreationResult<'ll> {
1190 metadata: &'ll DIType,
1191 already_stored_in_typemap: bool,
1194 impl<'ll> MetadataCreationResult<'ll> {
1195 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1196 MetadataCreationResult { metadata, already_stored_in_typemap }
1201 struct SourceInfo<'ll> {
1206 /// Description of a type member, which can either be a regular field (as in
1207 /// structs or tuples) or an enum variant.
1209 struct MemberDescription<'ll> {
1211 type_metadata: &'ll DIType,
1216 discriminant: Option<u64>,
1217 source_info: Option<SourceInfo<'ll>>,
1220 impl<'ll> MemberDescription<'ll> {
1223 cx: &CodegenCx<'ll, '_>,
1224 composite_type_metadata: &'ll DIScope,
1226 let (file, line) = self
1228 .map(|info| (info.file, info.line))
1229 .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1231 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1233 composite_type_metadata,
1234 self.name.as_ptr().cast(),
1239 self.align.bits() as u32,
1241 self.discriminant.map(|v| cx.const_u64(v)),
1249 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1250 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1251 /// creation of type member descriptions in order to break cycles arising from
1252 /// recursive type definitions.
1253 enum MemberDescriptionFactory<'ll, 'tcx> {
1254 StructMDF(StructMemberDescriptionFactory<'tcx>),
1255 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1256 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1257 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1258 VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1261 impl<'ll, 'tcx> MemberDescriptionFactory<'ll, 'tcx> {
1262 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1264 StructMDF(ref this) => this.create_member_descriptions(cx),
1265 TupleMDF(ref this) => this.create_member_descriptions(cx),
1266 EnumMDF(ref this) => this.create_member_descriptions(cx),
1267 UnionMDF(ref this) => this.create_member_descriptions(cx),
1268 VariantMDF(ref this) => this.create_member_descriptions(cx),
1273 //=-----------------------------------------------------------------------------
1275 //=-----------------------------------------------------------------------------
1277 /// Creates `MemberDescription`s for the fields of a struct.
1278 struct StructMemberDescriptionFactory<'tcx> {
1280 variant: &'tcx ty::VariantDef,
1284 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1285 fn create_member_descriptions<'ll>(
1287 cx: &CodegenCx<'ll, 'tcx>,
1288 ) -> Vec<MemberDescription<'ll>> {
1289 let layout = cx.layout_of(self.ty);
1295 let name = if self.variant.ctor_kind == CtorKind::Fn {
1300 let field = layout.field(cx, i);
1303 type_metadata: type_metadata(cx, field.ty, self.span),
1304 offset: layout.fields.offset(i),
1306 align: field.align.abi,
1307 flags: DIFlags::FlagZero,
1316 fn prepare_struct_metadata<'ll, 'tcx>(
1317 cx: &CodegenCx<'ll, 'tcx>,
1318 struct_type: Ty<'tcx>,
1319 unique_type_id: UniqueTypeId,
1321 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1322 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1324 let (struct_def_id, variant) = match struct_type.kind() {
1325 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1326 _ => bug!("prepare_struct_metadata on a non-ADT"),
1329 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1331 let struct_metadata_stub = create_struct_stub(
1336 Some(containing_scope),
1340 create_and_register_recursive_type_forward_declaration(
1344 struct_metadata_stub,
1345 struct_metadata_stub,
1346 StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant, span }),
1350 //=-----------------------------------------------------------------------------
1352 //=-----------------------------------------------------------------------------
1354 /// Returns names of captured upvars for closures and generators.
1356 /// Here are some examples:
1357 /// - `name__field1__field2` when the upvar is captured by value.
1358 /// - `_ref__name__field` when the upvar is captured by reference.
1359 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<String> {
1360 let body = tcx.optimized_mir(def_id);
1365 let is_ref = match var.value {
1366 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1367 // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1368 // implies whether the variable is captured by value or by reference.
1369 matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1373 let prefix = if is_ref { "_ref__" } else { "" };
1374 Some(prefix.to_owned() + var.name.as_str())
1376 .collect::<Vec<_>>()
1379 /// Creates `MemberDescription`s for the fields of a tuple.
1380 struct TupleMemberDescriptionFactory<'tcx> {
1382 component_types: Vec<Ty<'tcx>>,
1386 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1387 fn create_member_descriptions<'ll>(
1389 cx: &CodegenCx<'ll, 'tcx>,
1390 ) -> Vec<MemberDescription<'ll>> {
1391 let mut capture_names = match *self.ty.kind() {
1392 ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1393 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1397 let layout = cx.layout_of(self.ty);
1398 self.component_types
1401 .map(|(i, &component_type)| {
1402 let (size, align) = cx.size_and_align_of(component_type);
1403 let name = if let Some(names) = capture_names.as_mut() {
1404 names.next().unwrap()
1410 type_metadata: type_metadata(cx, component_type, self.span),
1411 offset: layout.fields.offset(i),
1414 flags: DIFlags::FlagZero,
1423 fn prepare_tuple_metadata<'ll, 'tcx>(
1424 cx: &CodegenCx<'ll, 'tcx>,
1425 tuple_type: Ty<'tcx>,
1426 component_types: &[Ty<'tcx>],
1427 unique_type_id: UniqueTypeId,
1429 containing_scope: Option<&'ll DIScope>,
1430 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1431 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1433 let struct_stub = create_struct_stub(
1442 create_and_register_recursive_type_forward_declaration(
1448 TupleMDF(TupleMemberDescriptionFactory {
1450 component_types: component_types.to_vec(),
1456 //=-----------------------------------------------------------------------------
1458 //=-----------------------------------------------------------------------------
1460 struct UnionMemberDescriptionFactory<'tcx> {
1461 layout: TyAndLayout<'tcx>,
1462 variant: &'tcx ty::VariantDef,
1466 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1467 fn create_member_descriptions<'ll>(
1469 cx: &CodegenCx<'ll, 'tcx>,
1470 ) -> Vec<MemberDescription<'ll>> {
1476 let field = self.layout.field(cx, i);
1478 name: f.ident.to_string(),
1479 type_metadata: type_metadata(cx, field.ty, self.span),
1482 align: field.align.abi,
1483 flags: DIFlags::FlagZero,
1492 fn prepare_union_metadata<'ll, 'tcx>(
1493 cx: &CodegenCx<'ll, 'tcx>,
1494 union_type: Ty<'tcx>,
1495 unique_type_id: UniqueTypeId,
1497 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1498 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1500 let (union_def_id, variant) = match union_type.kind() {
1501 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1502 _ => bug!("prepare_union_metadata on a non-ADT"),
1505 let containing_scope = get_namespace_for_item(cx, union_def_id);
1507 let union_metadata_stub =
1508 create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1510 create_and_register_recursive_type_forward_declaration(
1514 union_metadata_stub,
1515 union_metadata_stub,
1516 UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant, span }),
1520 //=-----------------------------------------------------------------------------
1522 //=-----------------------------------------------------------------------------
1524 /// DWARF variant support is only available starting in LLVM 8, but
1525 /// on MSVC we have to use the fallback mode, because LLVM doesn't
1526 /// lower variant parts to PDB.
1527 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1528 cx.sess().target.is_like_msvc
1531 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1532 // per generator monomorphization, but it doesn't depend on substs.
1533 fn generator_layout_and_saved_local_names<'tcx>(
1536 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1537 let body = tcx.optimized_mir(def_id);
1538 let generator_layout = body.generator_layout().unwrap();
1539 let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1541 let state_arg = mir::Local::new(1);
1542 for var in &body.var_debug_info {
1543 let place = if let mir::VarDebugInfoContents::Place(p) = var.value { p } else { continue };
1544 if place.local != state_arg {
1547 match place.projection[..] {
1549 // Deref of the `Pin<&mut Self>` state argument.
1550 mir::ProjectionElem::Field(..),
1551 mir::ProjectionElem::Deref,
1552 // Field of a variant of the state.
1553 mir::ProjectionElem::Downcast(_, variant),
1554 mir::ProjectionElem::Field(field, _),
1556 let name = &mut generator_saved_local_names
1557 [generator_layout.variant_fields[variant][field]];
1559 name.replace(var.name);
1565 (generator_layout, generator_saved_local_names)
1568 /// Describes the members of an enum value; an enum is described as a union of
1569 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1570 /// the members of this union; so for every variant of the given enum, this
1571 /// factory will produce one `MemberDescription` (all with no name and a fixed
1572 /// offset of zero bytes).
1573 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1574 enum_type: Ty<'tcx>,
1575 layout: TyAndLayout<'tcx>,
1576 tag_type_metadata: Option<&'ll DIType>,
1577 common_members: Vec<Option<&'ll DIType>>,
1581 impl<'ll, 'tcx> EnumMemberDescriptionFactory<'ll, 'tcx> {
1582 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1583 let generator_variant_info_data = match *self.enum_type.kind() {
1584 ty::Generator(def_id, ..) => {
1585 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1590 let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1591 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1592 ty::Generator(def_id, _, _) => {
1593 let (generator_layout, generator_saved_local_names) =
1594 generator_variant_info_data.as_ref().unwrap();
1595 VariantInfo::Generator {
1597 generator_layout: *generator_layout,
1598 generator_saved_local_names,
1599 variant_index: index,
1605 let fallback = use_enum_fallback(cx);
1606 // This will always find the metadata in the type map.
1607 let self_metadata = type_metadata(cx, self.enum_type, self.span);
1609 match self.layout.variants {
1610 Variants::Single { index } => {
1611 if let ty::Adt(adt, _) = self.enum_type.kind() {
1612 if adt.variants.is_empty() {
1617 let variant_info = variant_info_for(index);
1618 let (variant_type_metadata, member_description_factory) =
1619 describe_enum_variant(cx, self.layout, variant_info, self_metadata, self.span);
1621 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1623 set_members_of_composite_type(
1626 variant_type_metadata,
1627 member_descriptions,
1628 Some(&self.common_members),
1630 vec![MemberDescription {
1631 name: variant_info.variant_name(),
1632 type_metadata: variant_type_metadata,
1634 size: self.layout.size,
1635 align: self.layout.align.abi,
1636 flags: DIFlags::FlagZero,
1638 source_info: variant_info.source_info(cx),
1641 Variants::Multiple {
1642 tag_encoding: TagEncoding::Direct,
1647 let fallback_discr_variant = if fallback {
1648 // For MSVC, we generate a union of structs for each variant and an
1649 // explicit discriminant field roughly equivalent to the following C:
1651 // union enum$<{name}> {
1652 // struct {variant 0 name} {
1653 // <variant 0 fields>
1655 // <other variant structs>
1656 // {name} discriminant;
1659 // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1660 // determine which variant is active and then displays it.
1661 let enum_layout = self.layout;
1662 let offset = enum_layout.fields.offset(tag_field);
1663 let discr_ty = enum_layout.field(cx, tag_field).ty;
1664 let (size, align) = cx.size_and_align_of(discr_ty);
1665 Some(MemberDescription {
1666 name: "discriminant".into(),
1667 type_metadata: self.tag_type_metadata.unwrap(),
1671 flags: DIFlags::FlagZero,
1682 let variant = self.layout.for_variant(cx, i);
1683 let variant_info = variant_info_for(i);
1684 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1692 let member_descriptions =
1693 member_desc_factory.create_member_descriptions(cx);
1695 set_members_of_composite_type(
1698 variant_type_metadata,
1699 member_descriptions,
1700 Some(&self.common_members),
1705 format!("variant{}", i.as_u32())
1707 variant_info.variant_name()
1709 type_metadata: variant_type_metadata,
1711 size: self.layout.size,
1712 align: self.layout.align.abi,
1713 flags: DIFlags::FlagZero,
1715 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1718 source_info: variant_info.source_info(cx),
1721 .chain(fallback_discr_variant.into_iter())
1724 Variants::Multiple {
1726 TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1731 let calculate_niche_value = |i: VariantIdx| {
1732 if i == dataful_variant {
1735 let value = (i.as_u32() as u128)
1736 .wrapping_sub(niche_variants.start().as_u32() as u128)
1737 .wrapping_add(niche_start);
1738 let value = tag.value.size(cx).truncate(value);
1739 // NOTE(eddyb) do *NOT* remove this assert, until
1740 // we pass the full 128-bit value to LLVM, otherwise
1741 // truncation will be silent and remain undetected.
1742 assert_eq!(value as u64 as u128, value);
1747 // For MSVC, we will generate a union of two fields, one for the dataful variant
1748 // and one that just points to the discriminant. We also create an enum that
1749 // contains tag values for the non-dataful variants and make the discriminant field
1750 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1751 // This will generate debuginfo roughly equivalent to the following C:
1753 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1754 // struct <dataful variant name> {
1755 // <fields in dataful variant>
1756 // } dataful_variant;
1757 // enum Discriminant$ {
1758 // <non-dataful variants>
1762 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1763 // and evaluates `this.discriminant`. If the value is between the min niche and max
1764 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1765 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1766 // case, we just need to render the name of the `this.discriminant` enum.
1768 let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1770 let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1771 // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1772 // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1773 // to just be `usize`.
1774 if let ty::RawPtr(_) = discr_enum_ty.kind() {
1775 discr_enum_ty = cx.tcx.types.usize;
1778 let tags: Vec<_> = variants
1780 .filter_map(|(variant_idx, _)| {
1781 calculate_niche_value(variant_idx).map(|tag| {
1782 let variant = variant_info_for(variant_idx);
1783 let name = variant.variant_name();
1786 llvm::LLVMRustDIBuilderCreateEnumerator(
1788 name.as_ptr().cast(),
1791 !discr_enum_ty.is_signed(),
1798 let discr_enum = unsafe {
1799 llvm::LLVMRustDIBuilderCreateEnumerationType(
1802 "Discriminant$".as_ptr().cast(),
1803 "Discriminant$".len(),
1804 unknown_file_metadata(cx),
1805 UNKNOWN_LINE_NUMBER,
1806 tag.value.size(cx).bits(),
1807 tag.value.align(cx).abi.bits() as u32,
1808 create_DIArray(DIB(cx), &tags),
1809 type_metadata(cx, discr_enum_ty, self.span),
1814 let variant_info = variant_info_for(dataful_variant);
1815 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1817 dataful_variant_layout,
1823 let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1825 set_members_of_composite_type(
1828 variant_type_metadata,
1829 member_descriptions,
1830 Some(&self.common_members),
1834 cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1838 // Name the dataful variant so that we can identify it for natvis
1839 name: "dataful_variant".to_string(),
1840 type_metadata: variant_type_metadata,
1842 size: self.layout.size,
1843 align: self.layout.align.abi,
1844 flags: DIFlags::FlagZero,
1846 source_info: variant_info.source_info(cx),
1849 name: "discriminant".into(),
1850 type_metadata: discr_enum,
1851 offset: dataful_variant_layout.fields.offset(tag_field),
1854 flags: DIFlags::FlagZero,
1863 let variant = self.layout.for_variant(cx, i);
1864 let variant_info = variant_info_for(i);
1865 let (variant_type_metadata, member_desc_factory) =
1866 describe_enum_variant(
1874 let member_descriptions =
1875 member_desc_factory.create_member_descriptions(cx);
1877 set_members_of_composite_type(
1880 variant_type_metadata,
1881 member_descriptions,
1882 Some(&self.common_members),
1885 let niche_value = calculate_niche_value(i);
1888 name: variant_info.variant_name(),
1889 type_metadata: variant_type_metadata,
1891 size: self.layout.size,
1892 align: self.layout.align.abi,
1893 flags: DIFlags::FlagZero,
1894 discriminant: niche_value,
1895 source_info: variant_info.source_info(cx),
1905 // Creates `MemberDescription`s for the fields of a single enum variant.
1906 struct VariantMemberDescriptionFactory<'tcx> {
1907 /// Cloned from the `layout::Struct` describing the variant.
1909 args: Vec<(String, Ty<'tcx>)>,
1913 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1914 fn create_member_descriptions<'ll>(
1916 cx: &CodegenCx<'ll, 'tcx>,
1917 ) -> Vec<MemberDescription<'ll>> {
1921 .map(|(i, &(ref name, ty))| {
1922 let (size, align) = cx.size_and_align_of(ty);
1924 name: name.to_string(),
1925 type_metadata: type_metadata(cx, ty, self.span),
1926 offset: self.offsets[i],
1929 flags: DIFlags::FlagZero,
1938 #[derive(Copy, Clone)]
1939 enum VariantInfo<'a, 'tcx> {
1940 Adt(&'tcx ty::VariantDef),
1943 generator_layout: &'tcx GeneratorLayout<'tcx>,
1944 generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1945 variant_index: VariantIdx,
1949 impl<'tcx> VariantInfo<'_, 'tcx> {
1950 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1952 VariantInfo::Adt(variant) => f(variant.ident.as_str()),
1953 VariantInfo::Generator { variant_index, .. } => {
1954 f(&GeneratorSubsts::variant_name(*variant_index))
1959 fn variant_name(&self) -> String {
1961 VariantInfo::Adt(variant) => variant.ident.to_string(),
1962 VariantInfo::Generator { variant_index, .. } => {
1963 // Since GDB currently prints out the raw discriminant along
1964 // with every variant, make each variant name be just the value
1965 // of the discriminant. The struct name for the variant includes
1966 // the actual variant description.
1967 format!("{}", variant_index.as_usize())
1972 fn field_name(&self, i: usize) -> String {
1973 let field_name = match *self {
1974 VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1975 Some(variant.fields[i].ident.name)
1977 VariantInfo::Generator {
1979 generator_saved_local_names,
1983 generator_saved_local_names
1984 [generator_layout.variant_fields[variant_index][i.into()]]
1988 field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1991 fn source_info<'ll>(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1992 if let VariantInfo::Generator { def_id, variant_index, .. } = self {
1994 cx.tcx.generator_layout(*def_id).unwrap().variant_source_info[*variant_index].span;
1995 if !span.is_dummy() {
1996 let loc = cx.lookup_debug_loc(span.lo());
1997 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
2004 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
2005 /// `MemberDescriptionFactory` for producing the descriptions of the
2006 /// fields of the variant. This is a rudimentary version of a full
2007 /// `RecursiveTypeDescription`.
2008 fn describe_enum_variant<'ll, 'tcx>(
2009 cx: &CodegenCx<'ll, 'tcx>,
2010 layout: layout::TyAndLayout<'tcx>,
2011 variant: VariantInfo<'_, 'tcx>,
2012 containing_scope: &'ll DIScope,
2014 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
2015 let metadata_stub = variant.map_struct_name(|variant_name| {
2016 let unique_type_id = debug_context(cx)
2019 .get_unique_type_id_of_enum_variant(cx, layout.ty, variant_name);
2025 Some(containing_scope),
2030 let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
2031 let args = (0..layout.fields.count())
2032 .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
2035 let member_description_factory =
2036 VariantMDF(VariantMemberDescriptionFactory { offsets, args, span });
2038 (metadata_stub, member_description_factory)
2041 fn prepare_enum_metadata<'ll, 'tcx>(
2042 cx: &CodegenCx<'ll, 'tcx>,
2043 enum_type: Ty<'tcx>,
2045 unique_type_id: UniqueTypeId,
2047 outer_field_tys: Vec<Ty<'tcx>>,
2048 ) -> RecursiveTypeDescription<'ll, 'tcx> {
2050 let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
2052 let containing_scope = get_namespace_for_item(cx, enum_def_id);
2053 // FIXME: This should emit actual file metadata for the enum, but we
2054 // currently can't get the necessary information when it comes to types
2055 // imported from other crates. Formerly we violated the ODR when performing
2056 // LTO because we emitted debuginfo for the same type with varying file
2057 // metadata, so as a workaround we pretend that the type comes from
2059 let file_metadata = unknown_file_metadata(cx);
2061 let discriminant_type_metadata = |discr: Primitive| {
2062 let enumerators_metadata: Vec<_> = match enum_type.kind() {
2063 ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
2064 .map(|((_, discr), v)| {
2065 let name = v.ident.as_str();
2066 let is_unsigned = match discr.ty.kind() {
2067 ty::Int(_) => false,
2068 ty::Uint(_) => true,
2069 _ => bug!("non integer discriminant"),
2072 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2074 name.as_ptr().cast(),
2076 // FIXME: what if enumeration has i128 discriminant?
2083 ty::Generator(_, substs, _) => substs
2085 .variant_range(enum_def_id, tcx)
2086 .map(|variant_index| {
2087 debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
2088 let name = GeneratorSubsts::variant_name(variant_index);
2090 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2092 name.as_ptr().cast(),
2094 // Generators use u32 as discriminant type, verified above.
2095 variant_index.as_u32().into(),
2104 let disr_type_key = (enum_def_id, discr);
2105 let cached_discriminant_type_metadata =
2106 debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2107 match cached_discriminant_type_metadata {
2108 Some(discriminant_type_metadata) => discriminant_type_metadata,
2110 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2111 let discriminant_base_type_metadata =
2112 type_metadata(cx, discr.to_ty(tcx), rustc_span::DUMMY_SP);
2115 let discriminant_name = match enum_type.kind() {
2117 item_name = tcx.item_name(enum_def_id);
2120 ty::Generator(..) => enum_name.as_str(),
2124 let discriminant_type_metadata = unsafe {
2125 llvm::LLVMRustDIBuilderCreateEnumerationType(
2128 discriminant_name.as_ptr().cast(),
2129 discriminant_name.len(),
2131 UNKNOWN_LINE_NUMBER,
2132 discriminant_size.bits(),
2133 discriminant_align.abi.bits() as u32,
2134 create_DIArray(DIB(cx), &enumerators_metadata),
2135 discriminant_base_type_metadata,
2141 .created_enum_disr_types
2143 .insert(disr_type_key, discriminant_type_metadata);
2145 discriminant_type_metadata
2150 let layout = cx.layout_of(enum_type);
2152 if let (Abi::Scalar(_), Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. }) =
2153 (layout.abi, &layout.variants)
2155 return FinalMetadata(discriminant_type_metadata(tag.value));
2158 if use_enum_fallback(cx) {
2159 let discriminant_type_metadata = match layout.variants {
2160 Variants::Single { .. } => None,
2161 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, .. }
2162 | Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. } => {
2163 Some(discriminant_type_metadata(tag.value))
2167 let enum_metadata = {
2168 let type_map = debug_context(cx).type_map.borrow();
2169 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2172 llvm::LLVMRustDIBuilderCreateUnionType(
2175 enum_name.as_ptr().cast(),
2178 UNKNOWN_LINE_NUMBER,
2180 layout.align.abi.bits() as u32,
2184 unique_type_id_str.as_ptr().cast(),
2185 unique_type_id_str.len(),
2190 return create_and_register_recursive_type_forward_declaration(
2196 EnumMDF(EnumMemberDescriptionFactory {
2199 tag_type_metadata: discriminant_type_metadata,
2200 common_members: vec![],
2206 let discriminator_name = match enum_type.kind() {
2207 ty::Generator(..) => "__state",
2210 let discriminator_metadata = match layout.variants {
2211 // A single-variant enum has no discriminant.
2212 Variants::Single { .. } => None,
2214 Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, tag_field, .. } => {
2215 // Find the integer type of the correct size.
2216 let size = tag.value.size(cx);
2217 let align = tag.value.align(cx);
2219 let tag_type = match tag.value {
2221 F32 => Integer::I32,
2222 F64 => Integer::I64,
2223 Pointer => cx.data_layout().ptr_sized_integer(),
2225 .to_ty(cx.tcx, false);
2227 let tag_metadata = basic_type_metadata(cx, tag_type);
2229 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2232 discriminator_name.as_ptr().cast(),
2233 discriminator_name.len(),
2235 UNKNOWN_LINE_NUMBER,
2237 align.abi.bits() as u32,
2238 layout.fields.offset(tag_field).bits(),
2239 DIFlags::FlagArtificial,
2245 Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, tag_field, .. } => {
2246 let discr_type = tag.value.to_ty(cx.tcx);
2247 let (size, align) = cx.size_and_align_of(discr_type);
2249 let discr_metadata = basic_type_metadata(cx, discr_type);
2251 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2254 discriminator_name.as_ptr().cast(),
2255 discriminator_name.len(),
2257 UNKNOWN_LINE_NUMBER,
2259 align.bits() as u32,
2260 layout.fields.offset(tag_field).bits(),
2261 DIFlags::FlagArtificial,
2268 let outer_fields = match layout.variants {
2269 Variants::Single { .. } => vec![],
2270 Variants::Multiple { .. } => {
2271 let tuple_mdf = TupleMemberDescriptionFactory {
2273 component_types: outer_field_tys,
2277 .create_member_descriptions(cx)
2279 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2284 let variant_part_unique_type_id_str = debug_context(cx)
2287 .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2288 let empty_array = create_DIArray(DIB(cx), &[]);
2290 let variant_part = unsafe {
2291 llvm::LLVMRustDIBuilderCreateVariantPart(
2294 name.as_ptr().cast(),
2297 UNKNOWN_LINE_NUMBER,
2299 layout.align.abi.bits() as u32,
2301 discriminator_metadata,
2303 variant_part_unique_type_id_str.as_ptr().cast(),
2304 variant_part_unique_type_id_str.len(),
2308 let struct_wrapper = {
2309 // The variant part must be wrapped in a struct according to DWARF.
2310 // All fields except the discriminant (including `outer_fields`)
2311 // should be put into structures inside the variant part, which gives
2312 // an equivalent layout but offers us much better integration with
2314 let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2316 let type_map = debug_context(cx).type_map.borrow();
2317 let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2320 llvm::LLVMRustDIBuilderCreateStructType(
2322 Some(containing_scope),
2323 enum_name.as_ptr().cast(),
2326 UNKNOWN_LINE_NUMBER,
2328 layout.align.abi.bits() as u32,
2334 unique_type_id_str.as_ptr().cast(),
2335 unique_type_id_str.len(),
2340 create_and_register_recursive_type_forward_declaration(
2346 EnumMDF(EnumMemberDescriptionFactory {
2349 tag_type_metadata: None,
2350 common_members: outer_fields,
2356 /// Creates debug information for a composite type, that is, anything that
2357 /// results in a LLVM struct.
2359 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2360 fn composite_type_metadata<'ll, 'tcx>(
2361 cx: &CodegenCx<'ll, 'tcx>,
2362 composite_type: Ty<'tcx>,
2363 composite_type_name: &str,
2364 composite_type_unique_id: UniqueTypeId,
2365 member_descriptions: Vec<MemberDescription<'ll>>,
2366 containing_scope: Option<&'ll DIScope>,
2368 // Ignore source location information as long as it
2369 // can't be reconstructed for non-local crates.
2370 _file_metadata: &'ll DIFile,
2371 _definition_span: Span,
2372 ) -> &'ll DICompositeType {
2373 // Create the (empty) struct metadata node ...
2374 let composite_type_metadata = create_struct_stub(
2377 composite_type_name,
2378 composite_type_unique_id,
2382 // ... and immediately create and add the member descriptions.
2383 set_members_of_composite_type(
2386 composite_type_metadata,
2387 member_descriptions,
2391 composite_type_metadata
2394 fn set_members_of_composite_type<'ll, 'tcx>(
2395 cx: &CodegenCx<'ll, 'tcx>,
2396 composite_type: Ty<'tcx>,
2397 composite_type_metadata: &'ll DICompositeType,
2398 member_descriptions: Vec<MemberDescription<'ll>>,
2399 common_members: Option<&Vec<Option<&'ll DIType>>>,
2401 // In some rare cases LLVM metadata uniquing would lead to an existing type
2402 // description being used instead of a new one created in
2403 // create_struct_stub. This would cause a hard to trace assertion in
2404 // DICompositeType::SetTypeArray(). The following check makes sure that we
2405 // get a better error message if this should happen again due to some
2408 let mut composite_types_completed =
2409 debug_context(cx).composite_types_completed.borrow_mut();
2410 if !composite_types_completed.insert(composite_type_metadata) {
2412 "debuginfo::set_members_of_composite_type() - \
2413 Already completed forward declaration re-encountered."
2418 let mut member_metadata: Vec<_> = member_descriptions
2420 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2422 if let Some(other_members) = common_members {
2423 member_metadata.extend(other_members.iter());
2426 let type_params = compute_type_parameters(cx, composite_type);
2428 let type_array = create_DIArray(DIB(cx), &member_metadata);
2429 llvm::LLVMRustDICompositeTypeReplaceArrays(
2431 composite_type_metadata,
2438 /// Computes the type parameters for a type, if any, for the given metadata.
2439 fn compute_type_parameters<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2440 if let ty::Adt(def, substs) = *ty.kind() {
2441 if substs.types().next().is_some() {
2442 let generics = cx.tcx.generics_of(def.did);
2443 let names = get_parameter_names(cx, generics);
2444 let template_params: Vec<_> = iter::zip(substs, names)
2445 .filter_map(|(kind, name)| {
2446 if let GenericArgKind::Type(ty) = kind.unpack() {
2448 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2449 let actual_type_metadata =
2450 type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
2451 let name = name.as_str();
2453 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2456 name.as_ptr().cast(),
2458 actual_type_metadata,
2467 return create_DIArray(DIB(cx), &template_params);
2470 return create_DIArray(DIB(cx), &[]);
2472 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2473 let mut names = generics
2475 .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2476 names.extend(generics.params.iter().map(|param| param.name));
2481 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2482 /// any caching, does not add any fields to the struct. This can be done later
2483 /// with `set_members_of_composite_type()`.
2484 fn create_struct_stub<'ll, 'tcx>(
2485 cx: &CodegenCx<'ll, 'tcx>,
2486 struct_type: Ty<'tcx>,
2487 struct_type_name: &str,
2488 unique_type_id: UniqueTypeId,
2489 containing_scope: Option<&'ll DIScope>,
2491 ) -> &'ll DICompositeType {
2492 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2494 let type_map = debug_context(cx).type_map.borrow();
2495 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2497 let metadata_stub = unsafe {
2498 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2499 // pointer will lead to hard to trace and debug LLVM assertions
2500 // later on in `llvm/lib/IR/Value.cpp`.
2501 let empty_array = create_DIArray(DIB(cx), &[]);
2503 llvm::LLVMRustDIBuilderCreateStructType(
2506 struct_type_name.as_ptr().cast(),
2507 struct_type_name.len(),
2508 unknown_file_metadata(cx),
2509 UNKNOWN_LINE_NUMBER,
2511 struct_align.bits() as u32,
2517 unique_type_id.as_ptr().cast(),
2518 unique_type_id.len(),
2525 fn create_union_stub<'ll, 'tcx>(
2526 cx: &CodegenCx<'ll, 'tcx>,
2527 union_type: Ty<'tcx>,
2528 union_type_name: &str,
2529 unique_type_id: UniqueTypeId,
2530 containing_scope: &'ll DIScope,
2531 ) -> &'ll DICompositeType {
2532 let (union_size, union_align) = cx.size_and_align_of(union_type);
2534 let type_map = debug_context(cx).type_map.borrow();
2535 let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2537 let metadata_stub = unsafe {
2538 // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2539 // pointer will lead to hard to trace and debug LLVM assertions
2540 // later on in `llvm/lib/IR/Value.cpp`.
2541 let empty_array = create_DIArray(DIB(cx), &[]);
2543 llvm::LLVMRustDIBuilderCreateUnionType(
2545 Some(containing_scope),
2546 union_type_name.as_ptr().cast(),
2547 union_type_name.len(),
2548 unknown_file_metadata(cx),
2549 UNKNOWN_LINE_NUMBER,
2551 union_align.bits() as u32,
2555 unique_type_id.as_ptr().cast(),
2556 unique_type_id.len(),
2563 /// Creates debug information for the given global variable.
2565 /// Adds the created metadata nodes directly to the crate's IR.
2566 pub fn create_global_var_metadata<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2567 if cx.dbg_cx.is_none() {
2571 // Only create type information if full debuginfo is enabled
2572 if cx.sess().opts.debuginfo != DebugInfo::Full {
2578 // We may want to remove the namespace scope if we're in an extern block (see
2579 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2580 let var_scope = get_namespace_for_item(cx, def_id);
2581 let span = tcx.def_span(def_id);
2583 let (file_metadata, line_number) = if !span.is_dummy() {
2584 let loc = cx.lookup_debug_loc(span.lo());
2585 (file_metadata(cx, &loc.file), loc.line)
2587 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2590 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2591 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2592 let type_metadata = type_metadata(cx, variable_type, span);
2593 let var_name = tcx.item_name(def_id);
2594 let var_name = var_name.as_str();
2595 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2596 // When empty, linkage_name field is omitted,
2597 // which is what we want for no_mangle statics
2598 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2600 let global_align = cx.align_of(variable_type);
2603 llvm::LLVMRustDIBuilderCreateStaticVariable(
2606 var_name.as_ptr().cast(),
2608 linkage_name.as_ptr().cast(),
2616 global_align.bytes() as u32,
2621 /// Generates LLVM debuginfo for a vtable.
2622 fn vtable_type_metadata<'ll, 'tcx>(
2623 cx: &CodegenCx<'ll, 'tcx>,
2625 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2629 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
2630 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
2631 let trait_ref = tcx.erase_regions(trait_ref);
2633 tcx.vtable_entries(trait_ref)
2635 COMMON_VTABLE_ENTRIES
2638 // FIXME: We describe the vtable as an array of *const () pointers. The length of the array is
2639 // correct - but we could create a more accurate description, e.g. by describing it
2640 // as a struct where each field has a name that corresponds to the name of the method
2642 // However, this is not entirely straightforward because there might be multiple
2643 // methods with the same name if the vtable is for multiple traits. So for now we keep
2644 // things simple instead of adding some ad-hoc disambiguation scheme.
2645 let vtable_type = tcx.mk_array(tcx.mk_imm_ptr(tcx.types.unit), vtable_entries.len() as u64);
2647 type_metadata(cx, vtable_type, rustc_span::DUMMY_SP)
2650 /// Creates debug information for the given vtable, which is for the
2653 /// Adds the created metadata nodes directly to the crate's IR.
2654 pub fn create_vtable_metadata<'ll, 'tcx>(
2655 cx: &CodegenCx<'ll, 'tcx>,
2657 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2660 if cx.dbg_cx.is_none() {
2664 // Only create type information if full debuginfo is enabled
2665 if cx.sess().opts.debuginfo != DebugInfo::Full {
2669 let vtable_name = compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref);
2670 let vtable_type = vtable_type_metadata(cx, ty, poly_trait_ref);
2673 let linkage_name = "";
2674 llvm::LLVMRustDIBuilderCreateStaticVariable(
2677 vtable_name.as_ptr().cast(),
2679 linkage_name.as_ptr().cast(),
2681 unknown_file_metadata(cx),
2682 UNKNOWN_LINE_NUMBER,
2692 /// Creates an "extension" of an existing `DIScope` into another file.
2693 pub fn extend_scope_to_file<'ll>(
2694 cx: &CodegenCx<'ll, '_>,
2695 scope_metadata: &'ll DIScope,
2697 ) -> &'ll DILexicalBlock {
2698 let file_metadata = file_metadata(cx, file);
2699 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }