]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Do not suggest using a const parameter when there are bounds on an unused type parameter
[rust.git] / compiler / rustc_codegen_llvm / src / debuginfo / metadata.rs
1 use self::MemberDescriptionFactory::*;
2 use self::RecursiveTypeDescription::*;
3
4 use super::namespace::mangled_name_of_instance;
5 use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
6 use super::utils::{
7     create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB,
8 };
9 use super::CrateDebugContext;
10
11 use crate::abi;
12 use crate::common::CodegenCx;
13 use crate::debuginfo::utils::fat_pointer_kind;
14 use crate::debuginfo::utils::FatPtrKind;
15 use crate::llvm;
16 use crate::llvm::debuginfo::{
17     DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
18     DebugEmissionKind,
19 };
20 use crate::value::Value;
21
22 use cstr::cstr;
23 use rustc_codegen_ssa::debuginfo::type_names::cpp_like_debuginfo;
24 use rustc_codegen_ssa::debuginfo::type_names::VTableNameKind;
25 use rustc_codegen_ssa::traits::*;
26 use rustc_data_structures::fingerprint::Fingerprint;
27 use rustc_data_structures::fx::FxHashMap;
28 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
29 use rustc_fs_util::path_to_c_string;
30 use rustc_hir::def::CtorKind;
31 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
32 use rustc_index::vec::{Idx, IndexVec};
33 use rustc_middle::bug;
34 use rustc_middle::mir::{self, GeneratorLayout};
35 use rustc_middle::ty::layout::{self, IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout};
36 use rustc_middle::ty::subst::GenericArgKind;
37 use rustc_middle::ty::{
38     self, AdtKind, GeneratorSubsts, Instance, ParamEnv, Ty, TyCtxt, COMMON_VTABLE_ENTRIES,
39 };
40 use rustc_query_system::ich::NodeIdHashingMode;
41 use rustc_session::config::{self, DebugInfo};
42 use rustc_span::symbol::Symbol;
43 use rustc_span::FileNameDisplayPreference;
44 use rustc_span::{self, SourceFile, SourceFileHash};
45 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, TagEncoding};
46 use rustc_target::abi::{Int, Pointer, F32, F64};
47 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
48 use tracing::debug;
49
50 use libc::{c_longlong, c_uint};
51 use std::collections::hash_map::Entry;
52 use std::fmt::{self, Write};
53 use std::hash::{Hash, Hasher};
54 use std::iter;
55 use std::path::{Path, PathBuf};
56 use std::ptr;
57
58 impl PartialEq for llvm::Metadata {
59     fn eq(&self, other: &Self) -> bool {
60         ptr::eq(self, other)
61     }
62 }
63
64 impl Eq for llvm::Metadata {}
65
66 impl Hash for llvm::Metadata {
67     fn hash<H: Hasher>(&self, hasher: &mut H) {
68         (self as *const Self).hash(hasher);
69     }
70 }
71
72 impl fmt::Debug for llvm::Metadata {
73     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74         (self as *const Self).fmt(f)
75     }
76 }
77
78 // From DWARF 5.
79 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
80 const DW_LANG_RUST: c_uint = 0x1c;
81 #[allow(non_upper_case_globals)]
82 const DW_ATE_boolean: c_uint = 0x02;
83 #[allow(non_upper_case_globals)]
84 const DW_ATE_float: c_uint = 0x04;
85 #[allow(non_upper_case_globals)]
86 const DW_ATE_signed: c_uint = 0x05;
87 #[allow(non_upper_case_globals)]
88 const DW_ATE_unsigned: c_uint = 0x07;
89 #[allow(non_upper_case_globals)]
90 const DW_ATE_UTF: c_uint = 0x10;
91
92 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
93 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
94
95 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
96
97 mod unique_type_id {
98     use super::*;
99     use rustc_arena::DroplessArena;
100
101     #[derive(Copy, Hash, Eq, PartialEq, Clone)]
102     pub(super) struct UniqueTypeId(u32);
103
104     // The `&'static str`s in this type actually point into the arena.
105     //
106     // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
107     // found that to regress performance up to 2% in some cases. This might be
108     // revisited after further improvements to `indexmap`.
109     #[derive(Default)]
110     pub(super) struct TypeIdInterner {
111         arena: DroplessArena,
112         names: FxHashMap<&'static str, UniqueTypeId>,
113         strings: Vec<&'static str>,
114     }
115
116     impl TypeIdInterner {
117         #[inline]
118         pub(super) fn intern(&mut self, string: &str) -> UniqueTypeId {
119             if let Some(&name) = self.names.get(string) {
120                 return name;
121             }
122
123             let name = UniqueTypeId(self.strings.len() as u32);
124
125             // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
126             // UTF-8.
127             let string: &str =
128                 unsafe { std::str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
129             // It is safe to extend the arena allocation to `'static` because we only access
130             // these while the arena is still alive.
131             let string: &'static str = unsafe { &*(string as *const str) };
132             self.strings.push(string);
133             self.names.insert(string, name);
134             name
135         }
136
137         // Get the symbol as a string. `Symbol::as_str()` should be used in
138         // preference to this function.
139         pub(super) fn get(&self, symbol: UniqueTypeId) -> &str {
140             self.strings[symbol.0 as usize]
141         }
142     }
143 }
144 use unique_type_id::*;
145
146 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
147 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
148 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
149 /// `UniqueTypeId`s.
150 #[derive(Default)]
151 pub struct TypeMap<'ll, 'tcx> {
152     /// The `UniqueTypeId`s created so far.
153     unique_id_interner: TypeIdInterner,
154     /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
155     unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
156     /// A map from types to debuginfo metadata. This is an N:1 mapping.
157     type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
158     /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
159     type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
160 }
161
162 impl<'ll, 'tcx> TypeMap<'ll, 'tcx> {
163     /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
164     /// the mapping already exists.
165     fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
166         if self.type_to_metadata.insert(type_, metadata).is_some() {
167             bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
168         }
169     }
170
171     /// Removes a `Ty`-to-metadata mapping.
172     /// This is useful when computing the metadata for a potentially
173     /// recursive type (e.g., a function pointer of the form:
174     ///
175     ///     fn foo() -> impl Copy { foo }
176     ///
177     /// This kind of type cannot be properly represented
178     /// via LLVM debuginfo. As a workaround,
179     /// we register a temporary Ty to metadata mapping
180     /// for the function before we compute its actual metadata.
181     /// If the metadata computation ends up recursing back to the
182     /// original function, it will use the temporary mapping
183     /// for the inner self-reference, preventing us from
184     /// recursing forever.
185     ///
186     /// This function is used to remove the temporary metadata
187     /// mapping after we've computed the actual metadata.
188     fn remove_type(&mut self, ty: Ty<'tcx>) {
189         if self.type_to_metadata.remove(&ty).is_none() {
190             bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", ty);
191         }
192     }
193
194     /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
195     /// fail if the mapping already exists.
196     fn register_unique_id_with_metadata(
197         &mut self,
198         unique_type_id: UniqueTypeId,
199         metadata: &'ll DIType,
200     ) {
201         if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
202             bug!(
203                 "type metadata for unique ID '{}' is already in the `TypeMap`!",
204                 self.get_unique_type_id_as_string(unique_type_id)
205             );
206         }
207     }
208
209     fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
210         self.type_to_metadata.get(&type_).cloned()
211     }
212
213     fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
214         self.unique_id_to_metadata.get(&unique_type_id).cloned()
215     }
216
217     /// Gets the string representation of a `UniqueTypeId`. This method will fail if
218     /// the ID is unknown.
219     fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
220         self.unique_id_interner.get(unique_type_id)
221     }
222
223     /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
224     /// type has been requested before, this is just a table lookup. Otherwise, an
225     /// ID will be generated and stored for later lookup.
226     fn get_unique_type_id_of_type<'a>(
227         &mut self,
228         cx: &CodegenCx<'a, 'tcx>,
229         type_: Ty<'tcx>,
230     ) -> UniqueTypeId {
231         // Let's see if we already have something in the cache.
232         if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
233             return unique_type_id;
234         }
235         // If not, generate one.
236
237         // The hasher we are using to generate the UniqueTypeId. We want
238         // something that provides more than the 64 bits of the DefaultHasher.
239         let mut hasher = StableHasher::new();
240         let mut hcx = cx.tcx.create_stable_hashing_context();
241         let type_ = cx.tcx.erase_regions(type_);
242         hcx.while_hashing_spans(false, |hcx| {
243             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
244                 type_.hash_stable(hcx, &mut hasher);
245             });
246         });
247         let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
248
249         let key = self.unique_id_interner.intern(&unique_type_id);
250         self.type_to_unique_id.insert(type_, key);
251
252         key
253     }
254
255     /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
256     /// types of their own, so they need special handling. We still need a
257     /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
258     fn get_unique_type_id_of_enum_variant<'a>(
259         &mut self,
260         cx: &CodegenCx<'a, 'tcx>,
261         enum_type: Ty<'tcx>,
262         variant_name: &str,
263     ) -> UniqueTypeId {
264         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
265         let enum_variant_type_id =
266             format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
267         let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
268         interner_key
269     }
270
271     /// Gets the unique type ID string for an enum variant part.
272     /// Variant parts are not types and shouldn't really have their own ID,
273     /// but it makes `set_members_of_composite_type()` simpler.
274     fn get_unique_type_id_str_of_enum_variant_part(
275         &mut self,
276         enum_type_id: UniqueTypeId,
277     ) -> String {
278         format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id))
279     }
280
281     /// Gets the `UniqueTypeId` for the type of a vtable.
282     fn get_unique_type_id_of_vtable_type(&mut self, vtable_type_name: &str) -> UniqueTypeId {
283         let interner_key = self.unique_id_interner.intern(vtable_type_name);
284         interner_key
285     }
286 }
287
288 /// A description of some recursive type. It can either be already finished (as
289 /// with `FinalMetadata`) or it is not yet finished, but contains all information
290 /// needed to generate the missing parts of the description. See the
291 /// documentation section on Recursive Types at the top of this file for more
292 /// information.
293 enum RecursiveTypeDescription<'ll, 'tcx> {
294     UnfinishedMetadata {
295         unfinished_type: Ty<'tcx>,
296         unique_type_id: UniqueTypeId,
297         metadata_stub: &'ll DICompositeType,
298         member_holding_stub: &'ll DICompositeType,
299         member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
300     },
301     FinalMetadata(&'ll DICompositeType),
302 }
303
304 fn create_and_register_recursive_type_forward_declaration<'ll, 'tcx>(
305     cx: &CodegenCx<'ll, 'tcx>,
306     unfinished_type: Ty<'tcx>,
307     unique_type_id: UniqueTypeId,
308     metadata_stub: &'ll DICompositeType,
309     member_holding_stub: &'ll DICompositeType,
310     member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
311 ) -> RecursiveTypeDescription<'ll, 'tcx> {
312     // Insert the stub into the `TypeMap` in order to allow for recursive references.
313     let mut type_map = debug_context(cx).type_map.borrow_mut();
314     type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
315     type_map.register_type_with_metadata(unfinished_type, metadata_stub);
316
317     UnfinishedMetadata {
318         unfinished_type,
319         unique_type_id,
320         metadata_stub,
321         member_holding_stub,
322         member_description_factory,
323     }
324 }
325
326 impl<'ll, 'tcx> RecursiveTypeDescription<'ll, 'tcx> {
327     /// Finishes up the description of the type in question (mostly by providing
328     /// descriptions of the fields of the given type) and returns the final type
329     /// metadata.
330     fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
331         match *self {
332             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
333             UnfinishedMetadata {
334                 unfinished_type,
335                 unique_type_id,
336                 metadata_stub,
337                 member_holding_stub,
338                 ref member_description_factory,
339             } => {
340                 // Make sure that we have a forward declaration of the type in
341                 // the TypeMap so that recursive references are possible. This
342                 // will always be the case if the RecursiveTypeDescription has
343                 // been properly created through the
344                 // `create_and_register_recursive_type_forward_declaration()`
345                 // function.
346                 {
347                     let type_map = debug_context(cx).type_map.borrow();
348                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
349                         || type_map.find_metadata_for_type(unfinished_type).is_none()
350                     {
351                         bug!(
352                             "Forward declaration of potentially recursive type \
353                               '{:?}' was not found in TypeMap!",
354                             unfinished_type
355                         );
356                     }
357                 }
358
359                 // ... then create the member descriptions ...
360                 let member_descriptions = member_description_factory.create_member_descriptions(cx);
361                 let type_params = compute_type_parameters(cx, unfinished_type);
362
363                 // ... and attach them to the stub to complete it.
364                 set_members_of_composite_type(
365                     cx,
366                     member_holding_stub,
367                     member_descriptions,
368                     None,
369                     type_params,
370                 );
371                 MetadataCreationResult::new(metadata_stub, true)
372             }
373         }
374     }
375 }
376
377 /// Returns from the enclosing function if the type metadata with the given
378 /// unique ID can be found in the type map.
379 macro_rules! return_if_metadata_created_in_meantime {
380     ($cx: expr, $unique_type_id: expr) => {
381         if let Some(metadata) =
382             debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
383         {
384             return MetadataCreationResult::new(metadata, true);
385         }
386     };
387 }
388
389 /// Creates debuginfo for a fixed size array (e.g. `[u64; 123]`).
390 /// For slices (that is, "arrays" of unknown size) use [slice_type_metadata].
391 fn fixed_size_array_metadata<'ll, 'tcx>(
392     cx: &CodegenCx<'ll, 'tcx>,
393     unique_type_id: UniqueTypeId,
394     array_type: Ty<'tcx>,
395 ) -> MetadataCreationResult<'ll> {
396     let ty::Array(element_type, len) = array_type.kind() else {
397         bug!("fixed_size_array_metadata() called with non-ty::Array type `{:?}`", array_type)
398     };
399
400     let element_type_metadata = type_metadata(cx, *element_type);
401
402     return_if_metadata_created_in_meantime!(cx, unique_type_id);
403
404     let (size, align) = cx.size_and_align_of(array_type);
405
406     let upper_bound = len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong;
407
408     let subrange =
409         unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
410
411     let subscripts = create_DIArray(DIB(cx), &[subrange]);
412     let metadata = unsafe {
413         llvm::LLVMRustDIBuilderCreateArrayType(
414             DIB(cx),
415             size.bits(),
416             align.bits() as u32,
417             element_type_metadata,
418             subscripts,
419         )
420     };
421
422     MetadataCreationResult::new(metadata, false)
423 }
424
425 /// Creates debuginfo for built-in pointer-like things:
426 ///
427 ///  - ty::Ref
428 ///  - ty::RawPtr
429 ///  - ty::Adt in the case it's Box
430 ///
431 /// At some point we might want to remove the special handling of Box
432 /// and treat it the same as other smart pointers (like Rc, Arc, ...).
433 fn pointer_or_reference_metadata<'ll, 'tcx>(
434     cx: &CodegenCx<'ll, 'tcx>,
435     ptr_type: Ty<'tcx>,
436     pointee_type: Ty<'tcx>,
437     unique_type_id: UniqueTypeId,
438 ) -> MetadataCreationResult<'ll> {
439     let pointee_type_metadata = type_metadata(cx, pointee_type);
440
441     return_if_metadata_created_in_meantime!(cx, unique_type_id);
442
443     let (thin_pointer_size, thin_pointer_align) =
444         cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.types.unit));
445     let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
446
447     let pointer_type_metadata = match fat_pointer_kind(cx, pointee_type) {
448         None => {
449             // This is a thin pointer. Create a regular pointer type and give it the correct name.
450             debug_assert_eq!(
451                 (thin_pointer_size, thin_pointer_align),
452                 cx.size_and_align_of(ptr_type),
453                 "ptr_type={}, pointee_type={}",
454                 ptr_type,
455                 pointee_type,
456             );
457
458             unsafe {
459                 llvm::LLVMRustDIBuilderCreatePointerType(
460                     DIB(cx),
461                     pointee_type_metadata,
462                     thin_pointer_size.bits(),
463                     thin_pointer_align.bits() as u32,
464                     0, // Ignore DWARF address space.
465                     ptr_type_debuginfo_name.as_ptr().cast(),
466                     ptr_type_debuginfo_name.len(),
467                 )
468             }
469         }
470         Some(fat_pointer_kind) => {
471             let layout = cx.layout_of(ptr_type);
472
473             let addr_field = layout.field(cx, abi::FAT_PTR_ADDR);
474             let extra_field = layout.field(cx, abi::FAT_PTR_EXTRA);
475
476             let (addr_field_name, extra_field_name) = match fat_pointer_kind {
477                 FatPtrKind::Dyn => ("pointer", "vtable"),
478                 FatPtrKind::Slice => ("data_ptr", "length"),
479             };
480
481             debug_assert_eq!(abi::FAT_PTR_ADDR, 0);
482             debug_assert_eq!(abi::FAT_PTR_EXTRA, 1);
483
484             // The data pointer type is a regular, thin pointer, regardless of whether this is a slice
485             // or a trait object.
486             let data_ptr_type_metadata = unsafe {
487                 llvm::LLVMRustDIBuilderCreatePointerType(
488                     DIB(cx),
489                     pointee_type_metadata,
490                     addr_field.size.bits(),
491                     addr_field.align.abi.bits() as u32,
492                     0, // Ignore DWARF address space.
493                     std::ptr::null(),
494                     0,
495                 )
496             };
497
498             let member_descriptions = vec![
499                 MemberDescription {
500                     name: addr_field_name.into(),
501                     type_metadata: data_ptr_type_metadata,
502                     offset: layout.fields.offset(abi::FAT_PTR_ADDR),
503                     size: addr_field.size,
504                     align: addr_field.align.abi,
505                     flags: DIFlags::FlagZero,
506                     discriminant: None,
507                     source_info: None,
508                 },
509                 MemberDescription {
510                     name: extra_field_name.into(),
511                     type_metadata: type_metadata(cx, extra_field.ty),
512                     offset: layout.fields.offset(abi::FAT_PTR_EXTRA),
513                     size: extra_field.size,
514                     align: extra_field.align.abi,
515                     flags: DIFlags::FlagZero,
516                     discriminant: None,
517                     source_info: None,
518                 },
519             ];
520
521             composite_type_metadata(
522                 cx,
523                 ptr_type,
524                 &ptr_type_debuginfo_name,
525                 unique_type_id,
526                 member_descriptions,
527                 NO_SCOPE_METADATA,
528             )
529         }
530     };
531
532     MetadataCreationResult { metadata: pointer_type_metadata, already_stored_in_typemap: false }
533 }
534
535 fn subroutine_type_metadata<'ll, 'tcx>(
536     cx: &CodegenCx<'ll, 'tcx>,
537     unique_type_id: UniqueTypeId,
538     signature: ty::PolyFnSig<'tcx>,
539 ) -> MetadataCreationResult<'ll> {
540     let signature =
541         cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), signature);
542
543     let signature_metadata: Vec<_> = iter::once(
544         // return type
545         match signature.output().kind() {
546             ty::Tuple(tys) if tys.is_empty() => None,
547             _ => Some(type_metadata(cx, signature.output())),
548         },
549     )
550     .chain(
551         // regular arguments
552         signature.inputs().iter().map(|&argument_type| Some(type_metadata(cx, argument_type))),
553     )
554     .collect();
555
556     return_if_metadata_created_in_meantime!(cx, unique_type_id);
557
558     MetadataCreationResult::new(
559         unsafe {
560             llvm::LLVMRustDIBuilderCreateSubroutineType(
561                 DIB(cx),
562                 create_DIArray(DIB(cx), &signature_metadata[..]),
563             )
564         },
565         false,
566     )
567 }
568
569 /// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
570 /// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
571 fn dyn_type_metadata<'ll, 'tcx>(
572     cx: &CodegenCx<'ll, 'tcx>,
573     dyn_type: Ty<'tcx>,
574     unique_type_id: UniqueTypeId,
575 ) -> &'ll DIType {
576     if let ty::Dynamic(..) = dyn_type.kind() {
577         let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
578         composite_type_metadata(cx, dyn_type, &type_name, unique_type_id, vec![], NO_SCOPE_METADATA)
579     } else {
580         bug!("Only ty::Dynamic is valid for dyn_type_metadata(). Found {:?} instead.", dyn_type)
581     }
582 }
583
584 /// Create debuginfo for `[T]` and `str`. These are unsized.
585 ///
586 /// NOTE: We currently emit just emit the debuginfo for the element type here
587 /// (i.e. `T` for slices and `u8` for `str`), so that we end up with
588 /// `*const T` for the `data_ptr` field of the corresponding fat-pointer
589 /// debuginfo of `&[T]`.
590 ///
591 /// It would be preferable and more accurate if we emitted a DIArray of T
592 /// without an upper bound instead. That is, LLVM already supports emitting
593 /// debuginfo of arrays of unknown size. But GDB currently seems to end up
594 /// in an infinite loop when confronted with such a type.
595 ///
596 /// As a side effect of the current encoding every instance of a type like
597 /// `struct Foo { unsized_field: [u8] }` will look like
598 /// `struct Foo { unsized_field: u8 }` in debuginfo. If the length of the
599 /// slice is zero, then accessing `unsized_field` in the debugger would
600 /// result in an out-of-bounds access.
601 fn slice_type_metadata<'ll, 'tcx>(
602     cx: &CodegenCx<'ll, 'tcx>,
603     slice_type: Ty<'tcx>,
604     unique_type_id: UniqueTypeId,
605 ) -> MetadataCreationResult<'ll> {
606     let element_type = match slice_type.kind() {
607         ty::Slice(element_type) => *element_type,
608         ty::Str => cx.tcx.types.u8,
609         _ => {
610             bug!(
611                 "Only ty::Slice is valid for slice_type_metadata(). Found {:?} instead.",
612                 slice_type
613             )
614         }
615     };
616
617     let element_type_metadata = type_metadata(cx, element_type);
618     return_if_metadata_created_in_meantime!(cx, unique_type_id);
619     MetadataCreationResult { metadata: element_type_metadata, already_stored_in_typemap: false }
620 }
621
622 pub fn type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
623     // Get the unique type ID of this type.
624     let unique_type_id = {
625         let mut type_map = debug_context(cx).type_map.borrow_mut();
626         // First, try to find the type in `TypeMap`. If we have seen it before, we
627         // can exit early here.
628         match type_map.find_metadata_for_type(t) {
629             Some(metadata) => {
630                 return metadata;
631             }
632             None => {
633                 // The Ty is not in the `TypeMap` but maybe we have already seen
634                 // an equivalent type (e.g., only differing in region arguments).
635                 // In order to find out, generate the unique type ID and look
636                 // that up.
637                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
638                 match type_map.find_metadata_for_unique_id(unique_type_id) {
639                     Some(metadata) => {
640                         // There is already an equivalent type in the TypeMap.
641                         // Register this Ty as an alias in the cache and
642                         // return the cached metadata.
643                         type_map.register_type_with_metadata(t, metadata);
644                         return metadata;
645                     }
646                     None => {
647                         // There really is no type metadata for this type, so
648                         // proceed by creating it.
649                         unique_type_id
650                     }
651                 }
652             }
653         }
654     };
655
656     debug!("type_metadata: {:?}", t);
657
658     let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
659         ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
660             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
661         }
662         ty::Tuple(elements) if elements.is_empty() => {
663             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
664         }
665         ty::Array(..) => fixed_size_array_metadata(cx, unique_type_id, t),
666         ty::Slice(_) | ty::Str => slice_type_metadata(cx, t, unique_type_id),
667         ty::Dynamic(..) => {
668             MetadataCreationResult::new(dyn_type_metadata(cx, t, unique_type_id), false)
669         }
670         ty::Foreign(..) => {
671             MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
672         }
673         ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => {
674             pointer_or_reference_metadata(cx, t, pointee_type, unique_type_id)
675         }
676         ty::Adt(def, _) if def.is_box() => {
677             pointer_or_reference_metadata(cx, t, t.boxed_ty(), unique_type_id)
678         }
679         ty::FnDef(..) | ty::FnPtr(_) => {
680             if let Some(metadata) =
681                 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
682             {
683                 return metadata;
684             }
685
686             // It's possible to create a self-referential
687             // type in Rust by using 'impl trait':
688             //
689             // fn foo() -> impl Copy { foo }
690             //
691             // See `TypeMap::remove_type` for more detals
692             // about the workaround.
693
694             let temp_type = {
695                 unsafe {
696                     // The choice of type here is pretty arbitrary -
697                     // anything reading the debuginfo for a recursive
698                     // type is going to see *something* weird - the only
699                     // question is what exactly it will see.
700                     let name = "<recur_type>";
701                     llvm::LLVMRustDIBuilderCreateBasicType(
702                         DIB(cx),
703                         name.as_ptr().cast(),
704                         name.len(),
705                         cx.size_of(t).bits(),
706                         DW_ATE_unsigned,
707                     )
708                 }
709             };
710
711             let type_map = &debug_context(cx).type_map;
712             type_map.borrow_mut().register_type_with_metadata(t, temp_type);
713
714             let fn_metadata =
715                 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx)).metadata;
716
717             type_map.borrow_mut().remove_type(t);
718
719             // This is actually a function pointer, so wrap it in pointer DI.
720             let (pointer_size, pointer_align) =
721                 cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.mk_unit()));
722             let name = compute_debuginfo_type_name(cx.tcx, t, false);
723             let md = unsafe {
724                 llvm::LLVMRustDIBuilderCreatePointerType(
725                     DIB(cx),
726                     fn_metadata,
727                     pointer_size.bits(),
728                     pointer_align.bits() as u32,
729                     0, // Ignore DWARF address space.
730                     name.as_ptr().cast(),
731                     name.len(),
732                 )
733             };
734
735             MetadataCreationResult::new(md, false)
736         }
737         ty::Closure(def_id, substs) => {
738             let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
739             let containing_scope = get_namespace_for_item(cx, def_id);
740             prepare_tuple_metadata(cx, t, &upvar_tys, unique_type_id, Some(containing_scope))
741                 .finalize(cx)
742         }
743         ty::Generator(def_id, substs, _) => {
744             let upvar_tys: Vec<_> = substs
745                 .as_generator()
746                 .prefix_tys()
747                 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
748                 .collect();
749             prepare_enum_metadata(cx, t, def_id, unique_type_id, upvar_tys).finalize(cx)
750         }
751         ty::Adt(def, ..) => match def.adt_kind() {
752             AdtKind::Struct => prepare_struct_metadata(cx, t, unique_type_id).finalize(cx),
753             AdtKind::Union => prepare_union_metadata(cx, t, unique_type_id).finalize(cx),
754             AdtKind::Enum => {
755                 prepare_enum_metadata(cx, t, def.did, unique_type_id, vec![]).finalize(cx)
756             }
757         },
758         ty::Tuple(tys) => {
759             prepare_tuple_metadata(cx, t, tys, unique_type_id, NO_SCOPE_METADATA).finalize(cx)
760         }
761         // Type parameters from polymorphized functions.
762         ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
763         _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
764     };
765
766     {
767         let mut type_map = debug_context(cx).type_map.borrow_mut();
768
769         if already_stored_in_typemap {
770             // Also make sure that we already have a `TypeMap` entry for the unique type ID.
771             let Some(metadata_for_uid) = type_map.find_metadata_for_unique_id(unique_type_id) else {
772                 bug!(
773                     "expected type metadata for unique \
774                             type ID '{}' to already be in \
775                             the `debuginfo::TypeMap` but it \
776                             was not. (Ty = {})",
777                     type_map.get_unique_type_id_as_string(unique_type_id),
778                     t
779                 );
780             };
781
782             match type_map.find_metadata_for_type(t) {
783                 Some(metadata) => {
784                     if metadata != metadata_for_uid {
785                         bug!(
786                             "mismatch between `Ty` and \
787                                    `UniqueTypeId` maps in \
788                                    `debuginfo::TypeMap`. \
789                                    UniqueTypeId={}, Ty={}",
790                             type_map.get_unique_type_id_as_string(unique_type_id),
791                             t
792                         );
793                     }
794                 }
795                 None => {
796                     type_map.register_type_with_metadata(t, metadata);
797                 }
798             }
799         } else {
800             type_map.register_type_with_metadata(t, metadata);
801             type_map.register_unique_id_with_metadata(unique_type_id, metadata);
802         }
803     }
804
805     metadata
806 }
807
808 fn hex_encode(data: &[u8]) -> String {
809     let mut hex_string = String::with_capacity(data.len() * 2);
810     for byte in data.iter() {
811         write!(&mut hex_string, "{:02x}", byte).unwrap();
812     }
813     hex_string
814 }
815
816 pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
817     debug!("file_metadata: file_name: {:?}", source_file.name);
818
819     let hash = Some(&source_file.src_hash);
820     let file_name = Some(source_file.name.prefer_remapped().to_string());
821     let directory = if source_file.is_real_file() && !source_file.is_imported() {
822         Some(
823             cx.sess()
824                 .opts
825                 .working_dir
826                 .to_string_lossy(FileNameDisplayPreference::Remapped)
827                 .to_string(),
828         )
829     } else {
830         // If the path comes from an upstream crate we assume it has been made
831         // independent of the compiler's working directory one way or another.
832         None
833     };
834     file_metadata_raw(cx, file_name, directory, hash)
835 }
836
837 pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
838     file_metadata_raw(cx, None, None, None)
839 }
840
841 fn file_metadata_raw<'ll>(
842     cx: &CodegenCx<'ll, '_>,
843     file_name: Option<String>,
844     directory: Option<String>,
845     hash: Option<&SourceFileHash>,
846 ) -> &'ll DIFile {
847     let key = (file_name, directory);
848
849     match debug_context(cx).created_files.borrow_mut().entry(key) {
850         Entry::Occupied(o) => o.get(),
851         Entry::Vacant(v) => {
852             let (file_name, directory) = v.key();
853             debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
854
855             let file_name = file_name.as_deref().unwrap_or("<unknown>");
856             let directory = directory.as_deref().unwrap_or("");
857
858             let (hash_kind, hash_value) = match hash {
859                 Some(hash) => {
860                     let kind = match hash.kind {
861                         rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
862                         rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
863                         rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
864                     };
865                     (kind, hex_encode(hash.hash_bytes()))
866                 }
867                 None => (llvm::ChecksumKind::None, String::new()),
868             };
869
870             let file_metadata = unsafe {
871                 llvm::LLVMRustDIBuilderCreateFile(
872                     DIB(cx),
873                     file_name.as_ptr().cast(),
874                     file_name.len(),
875                     directory.as_ptr().cast(),
876                     directory.len(),
877                     hash_kind,
878                     hash_value.as_ptr().cast(),
879                     hash_value.len(),
880                 )
881             };
882
883             v.insert(file_metadata);
884             file_metadata
885         }
886     }
887 }
888
889 trait MsvcBasicName {
890     fn msvc_basic_name(self) -> &'static str;
891 }
892
893 impl MsvcBasicName for ty::IntTy {
894     fn msvc_basic_name(self) -> &'static str {
895         match self {
896             ty::IntTy::Isize => "ptrdiff_t",
897             ty::IntTy::I8 => "__int8",
898             ty::IntTy::I16 => "__int16",
899             ty::IntTy::I32 => "__int32",
900             ty::IntTy::I64 => "__int64",
901             ty::IntTy::I128 => "__int128",
902         }
903     }
904 }
905
906 impl MsvcBasicName for ty::UintTy {
907     fn msvc_basic_name(self) -> &'static str {
908         match self {
909             ty::UintTy::Usize => "size_t",
910             ty::UintTy::U8 => "unsigned __int8",
911             ty::UintTy::U16 => "unsigned __int16",
912             ty::UintTy::U32 => "unsigned __int32",
913             ty::UintTy::U64 => "unsigned __int64",
914             ty::UintTy::U128 => "unsigned __int128",
915         }
916     }
917 }
918
919 impl MsvcBasicName for ty::FloatTy {
920     fn msvc_basic_name(self) -> &'static str {
921         match self {
922             ty::FloatTy::F32 => "float",
923             ty::FloatTy::F64 => "double",
924         }
925     }
926 }
927
928 fn basic_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
929     debug!("basic_type_metadata: {:?}", t);
930
931     // When targeting MSVC, emit MSVC style type names for compatibility with
932     // .natvis visualizers (and perhaps other existing native debuggers?)
933     let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
934
935     let (name, encoding) = match t.kind() {
936         ty::Never => ("!", DW_ATE_unsigned),
937         ty::Tuple(elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
938         ty::Bool => ("bool", DW_ATE_boolean),
939         ty::Char => ("char", DW_ATE_UTF),
940         ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
941         ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
942         ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
943         ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
944         ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
945         ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
946         _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
947     };
948
949     let ty_metadata = unsafe {
950         llvm::LLVMRustDIBuilderCreateBasicType(
951             DIB(cx),
952             name.as_ptr().cast(),
953             name.len(),
954             cx.size_of(t).bits(),
955             encoding,
956         )
957     };
958
959     if !cpp_like_debuginfo {
960         return ty_metadata;
961     }
962
963     let typedef_name = match t.kind() {
964         ty::Int(int_ty) => int_ty.name_str(),
965         ty::Uint(uint_ty) => uint_ty.name_str(),
966         ty::Float(float_ty) => float_ty.name_str(),
967         _ => return ty_metadata,
968     };
969
970     let typedef_metadata = unsafe {
971         llvm::LLVMRustDIBuilderCreateTypedef(
972             DIB(cx),
973             ty_metadata,
974             typedef_name.as_ptr().cast(),
975             typedef_name.len(),
976             unknown_file_metadata(cx),
977             0,
978             None,
979         )
980     };
981
982     typedef_metadata
983 }
984
985 fn foreign_type_metadata<'ll, 'tcx>(
986     cx: &CodegenCx<'ll, 'tcx>,
987     t: Ty<'tcx>,
988     unique_type_id: UniqueTypeId,
989 ) -> &'ll DIType {
990     debug!("foreign_type_metadata: {:?}", t);
991
992     let name = compute_debuginfo_type_name(cx.tcx, t, false);
993     let (size, align) = cx.size_and_align_of(t);
994     create_struct_stub(
995         cx,
996         size,
997         align,
998         &name,
999         unique_type_id,
1000         NO_SCOPE_METADATA,
1001         DIFlags::FlagZero,
1002         None,
1003     )
1004 }
1005
1006 fn param_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
1007     debug!("param_type_metadata: {:?}", t);
1008     let name = format!("{:?}", t);
1009     unsafe {
1010         llvm::LLVMRustDIBuilderCreateBasicType(
1011             DIB(cx),
1012             name.as_ptr().cast(),
1013             name.len(),
1014             Size::ZERO.bits(),
1015             DW_ATE_unsigned,
1016         )
1017     }
1018 }
1019
1020 pub fn compile_unit_metadata<'ll, 'tcx>(
1021     tcx: TyCtxt<'tcx>,
1022     codegen_unit_name: &str,
1023     debug_context: &CrateDebugContext<'ll, 'tcx>,
1024 ) -> &'ll DIDescriptor {
1025     let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
1026         Some(ref path) => path.clone(),
1027         None => PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()),
1028     };
1029
1030     // To avoid breaking split DWARF, we need to ensure that each codegen unit
1031     // has a unique `DW_AT_name`. This is because there's a remote chance that
1032     // different codegen units for the same module will have entirely
1033     // identical DWARF entries for the purpose of the DWO ID, which would
1034     // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
1035     // specification. LLVM uses the algorithm specified in section 7.32 "Type
1036     // Signature Computation" to compute the DWO ID, which does not include
1037     // any fields that would distinguish compilation units. So we must embed
1038     // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
1039     //
1040     // Additionally, the OSX linker has an idiosyncrasy where it will ignore
1041     // some debuginfo if multiple object files with the same `DW_AT_name` are
1042     // linked together.
1043     //
1044     // As a workaround for these two issues, we generate unique names for each
1045     // object file. Those do not correspond to an actual source file but that
1046     // is harmless.
1047     name_in_debuginfo.push("@");
1048     name_in_debuginfo.push(codegen_unit_name);
1049
1050     debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
1051     let rustc_producer =
1052         format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
1053     // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
1054     let producer = format!("clang LLVM ({})", rustc_producer);
1055
1056     let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1057     let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
1058     let flags = "\0";
1059     let output_filenames = tcx.output_filenames(());
1060     let split_name = if tcx.sess.target_can_use_split_dwarf() {
1061         output_filenames
1062             .split_dwarf_path(
1063                 tcx.sess.split_debuginfo(),
1064                 tcx.sess.opts.debugging_opts.split_dwarf_kind,
1065                 Some(codegen_unit_name),
1066             )
1067             // We get a path relative to the working directory from split_dwarf_path
1068             .map(|f| tcx.sess.source_map().path_mapping().map_prefix(f).0)
1069     } else {
1070         None
1071     }
1072     .unwrap_or_default();
1073     let split_name = split_name.to_str().unwrap();
1074
1075     // FIXME(#60020):
1076     //
1077     //    This should actually be
1078     //
1079     //        let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1080     //
1081     //    That is, we should set LLVM's emission kind to `LineTablesOnly` if
1082     //    we are compiling with "limited" debuginfo. However, some of the
1083     //    existing tools relied on slightly more debuginfo being generated than
1084     //    would be the case with `LineTablesOnly`, and we did not want to break
1085     //    these tools in a "drive-by fix", without a good idea or plan about
1086     //    what limited debuginfo should exactly look like. So for now we keep
1087     //    the emission kind as `FullDebug`.
1088     //
1089     //    See https://github.com/rust-lang/rust/issues/60020 for details.
1090     let kind = DebugEmissionKind::FullDebug;
1091     assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1092
1093     unsafe {
1094         let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
1095             debug_context.builder,
1096             name_in_debuginfo.as_ptr().cast(),
1097             name_in_debuginfo.len(),
1098             work_dir.as_ptr().cast(),
1099             work_dir.len(),
1100             llvm::ChecksumKind::None,
1101             ptr::null(),
1102             0,
1103         );
1104
1105         let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1106             debug_context.builder,
1107             DW_LANG_RUST,
1108             compile_unit_file,
1109             producer.as_ptr().cast(),
1110             producer.len(),
1111             tcx.sess.opts.optimize != config::OptLevel::No,
1112             flags.as_ptr().cast(),
1113             0,
1114             // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1115             // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1116             // output(s).
1117             split_name.as_ptr().cast(),
1118             split_name.len(),
1119             kind,
1120             0,
1121             tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1122         );
1123
1124         if tcx.sess.opts.debugging_opts.profile {
1125             let cu_desc_metadata =
1126                 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1127             let default_gcda_path = &output_filenames.with_extension("gcda");
1128             let gcda_path =
1129                 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1130
1131             let gcov_cu_info = [
1132                 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1133                 path_to_mdstring(debug_context.llcontext, gcda_path),
1134                 cu_desc_metadata,
1135             ];
1136             let gcov_metadata = llvm::LLVMMDNodeInContext(
1137                 debug_context.llcontext,
1138                 gcov_cu_info.as_ptr(),
1139                 gcov_cu_info.len() as c_uint,
1140             );
1141
1142             let llvm_gcov_ident = cstr!("llvm.gcov");
1143             llvm::LLVMAddNamedMetadataOperand(
1144                 debug_context.llmod,
1145                 llvm_gcov_ident.as_ptr(),
1146                 gcov_metadata,
1147             );
1148         }
1149
1150         // Insert `llvm.ident` metadata on the wasm targets since that will
1151         // get hooked up to the "producer" sections `processed-by` information.
1152         if tcx.sess.target.is_like_wasm {
1153             let name_metadata = llvm::LLVMMDStringInContext(
1154                 debug_context.llcontext,
1155                 rustc_producer.as_ptr().cast(),
1156                 rustc_producer.as_bytes().len() as c_uint,
1157             );
1158             llvm::LLVMAddNamedMetadataOperand(
1159                 debug_context.llmod,
1160                 cstr!("llvm.ident").as_ptr(),
1161                 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1162             );
1163         }
1164
1165         return unit_metadata;
1166     };
1167
1168     fn path_to_mdstring<'ll>(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1169         let path_str = path_to_c_string(path);
1170         unsafe {
1171             llvm::LLVMMDStringInContext(
1172                 llcx,
1173                 path_str.as_ptr(),
1174                 path_str.as_bytes().len() as c_uint,
1175             )
1176         }
1177     }
1178 }
1179
1180 struct MetadataCreationResult<'ll> {
1181     metadata: &'ll DIType,
1182     already_stored_in_typemap: bool,
1183 }
1184
1185 impl<'ll> MetadataCreationResult<'ll> {
1186     fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1187         MetadataCreationResult { metadata, already_stored_in_typemap }
1188     }
1189 }
1190
1191 #[derive(Debug)]
1192 struct SourceInfo<'ll> {
1193     file: &'ll DIFile,
1194     line: u32,
1195 }
1196
1197 /// Description of a type member, which can either be a regular field (as in
1198 /// structs or tuples) or an enum variant.
1199 #[derive(Debug)]
1200 struct MemberDescription<'ll> {
1201     name: String,
1202     type_metadata: &'ll DIType,
1203     offset: Size,
1204     size: Size,
1205     align: Align,
1206     flags: DIFlags,
1207     discriminant: Option<u64>,
1208     source_info: Option<SourceInfo<'ll>>,
1209 }
1210
1211 impl<'ll> MemberDescription<'ll> {
1212     fn into_metadata(
1213         self,
1214         cx: &CodegenCx<'ll, '_>,
1215         composite_type_metadata: &'ll DIScope,
1216     ) -> &'ll DIType {
1217         let (file, line) = self
1218             .source_info
1219             .map(|info| (info.file, info.line))
1220             .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1221         unsafe {
1222             llvm::LLVMRustDIBuilderCreateVariantMemberType(
1223                 DIB(cx),
1224                 composite_type_metadata,
1225                 self.name.as_ptr().cast(),
1226                 self.name.len(),
1227                 file,
1228                 line,
1229                 self.size.bits(),
1230                 self.align.bits() as u32,
1231                 self.offset.bits(),
1232                 self.discriminant.map(|v| cx.const_u64(v)),
1233                 self.flags,
1234                 self.type_metadata,
1235             )
1236         }
1237     }
1238 }
1239
1240 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1241 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1242 /// creation of type member descriptions in order to break cycles arising from
1243 /// recursive type definitions.
1244 enum MemberDescriptionFactory<'ll, 'tcx> {
1245     StructMDF(StructMemberDescriptionFactory<'tcx>),
1246     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1247     EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1248     UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1249     VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1250 }
1251
1252 impl<'ll, 'tcx> MemberDescriptionFactory<'ll, 'tcx> {
1253     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1254         match *self {
1255             StructMDF(ref this) => this.create_member_descriptions(cx),
1256             TupleMDF(ref this) => this.create_member_descriptions(cx),
1257             EnumMDF(ref this) => this.create_member_descriptions(cx),
1258             UnionMDF(ref this) => this.create_member_descriptions(cx),
1259             VariantMDF(ref this) => this.create_member_descriptions(cx),
1260         }
1261     }
1262 }
1263
1264 //=-----------------------------------------------------------------------------
1265 // Structs
1266 //=-----------------------------------------------------------------------------
1267
1268 /// Creates `MemberDescription`s for the fields of a struct.
1269 struct StructMemberDescriptionFactory<'tcx> {
1270     ty: Ty<'tcx>,
1271     variant: &'tcx ty::VariantDef,
1272 }
1273
1274 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1275     fn create_member_descriptions<'ll>(
1276         &self,
1277         cx: &CodegenCx<'ll, 'tcx>,
1278     ) -> Vec<MemberDescription<'ll>> {
1279         let layout = cx.layout_of(self.ty);
1280         self.variant
1281             .fields
1282             .iter()
1283             .enumerate()
1284             .map(|(i, f)| {
1285                 let name = if self.variant.ctor_kind == CtorKind::Fn {
1286                     format!("__{}", i)
1287                 } else {
1288                     f.name.to_string()
1289                 };
1290                 let field = layout.field(cx, i);
1291                 MemberDescription {
1292                     name,
1293                     type_metadata: type_metadata(cx, field.ty),
1294                     offset: layout.fields.offset(i),
1295                     size: field.size,
1296                     align: field.align.abi,
1297                     flags: DIFlags::FlagZero,
1298                     discriminant: None,
1299                     source_info: None,
1300                 }
1301             })
1302             .collect()
1303     }
1304 }
1305
1306 fn prepare_struct_metadata<'ll, 'tcx>(
1307     cx: &CodegenCx<'ll, 'tcx>,
1308     struct_type: Ty<'tcx>,
1309     unique_type_id: UniqueTypeId,
1310 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1311     let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1312
1313     let (struct_def_id, variant) = match struct_type.kind() {
1314         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1315         _ => bug!("prepare_struct_metadata on a non-ADT"),
1316     };
1317
1318     let containing_scope = get_namespace_for_item(cx, struct_def_id);
1319     let (size, align) = cx.size_and_align_of(struct_type);
1320
1321     let struct_metadata_stub = create_struct_stub(
1322         cx,
1323         size,
1324         align,
1325         &struct_name,
1326         unique_type_id,
1327         Some(containing_scope),
1328         DIFlags::FlagZero,
1329         None,
1330     );
1331
1332     create_and_register_recursive_type_forward_declaration(
1333         cx,
1334         struct_type,
1335         unique_type_id,
1336         struct_metadata_stub,
1337         struct_metadata_stub,
1338         StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant }),
1339     )
1340 }
1341
1342 //=-----------------------------------------------------------------------------
1343 // Tuples
1344 //=-----------------------------------------------------------------------------
1345
1346 /// Returns names of captured upvars for closures and generators.
1347 ///
1348 /// Here are some examples:
1349 ///  - `name__field1__field2` when the upvar is captured by value.
1350 ///  - `_ref__name__field` when the upvar is captured by reference.
1351 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<String> {
1352     let body = tcx.optimized_mir(def_id);
1353
1354     body.var_debug_info
1355         .iter()
1356         .filter_map(|var| {
1357             let is_ref = match var.value {
1358                 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1359                     // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1360                     // implies whether the variable is captured by value or by reference.
1361                     matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1362                 }
1363                 _ => return None,
1364             };
1365             let prefix = if is_ref { "_ref__" } else { "" };
1366             Some(prefix.to_owned() + var.name.as_str())
1367         })
1368         .collect::<Vec<_>>()
1369 }
1370
1371 /// Creates `MemberDescription`s for the fields of a tuple.
1372 struct TupleMemberDescriptionFactory<'tcx> {
1373     ty: Ty<'tcx>,
1374     component_types: Vec<Ty<'tcx>>,
1375 }
1376
1377 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1378     fn create_member_descriptions<'ll>(
1379         &self,
1380         cx: &CodegenCx<'ll, 'tcx>,
1381     ) -> Vec<MemberDescription<'ll>> {
1382         let mut capture_names = match *self.ty.kind() {
1383             ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1384                 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1385             }
1386             _ => None,
1387         };
1388         let layout = cx.layout_of(self.ty);
1389         self.component_types
1390             .iter()
1391             .enumerate()
1392             .map(|(i, &component_type)| {
1393                 let (size, align) = cx.size_and_align_of(component_type);
1394                 let name = if let Some(names) = capture_names.as_mut() {
1395                     names.next().unwrap()
1396                 } else {
1397                     format!("__{}", i)
1398                 };
1399                 MemberDescription {
1400                     name,
1401                     type_metadata: type_metadata(cx, component_type),
1402                     offset: layout.fields.offset(i),
1403                     size,
1404                     align,
1405                     flags: DIFlags::FlagZero,
1406                     discriminant: None,
1407                     source_info: None,
1408                 }
1409             })
1410             .collect()
1411     }
1412 }
1413
1414 fn prepare_tuple_metadata<'ll, 'tcx>(
1415     cx: &CodegenCx<'ll, 'tcx>,
1416     tuple_type: Ty<'tcx>,
1417     component_types: &[Ty<'tcx>],
1418     unique_type_id: UniqueTypeId,
1419     containing_scope: Option<&'ll DIScope>,
1420 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1421     let (size, align) = cx.size_and_align_of(tuple_type);
1422     let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1423
1424     let struct_stub = create_struct_stub(
1425         cx,
1426         size,
1427         align,
1428         &tuple_name[..],
1429         unique_type_id,
1430         containing_scope,
1431         DIFlags::FlagZero,
1432         None,
1433     );
1434
1435     create_and_register_recursive_type_forward_declaration(
1436         cx,
1437         tuple_type,
1438         unique_type_id,
1439         struct_stub,
1440         struct_stub,
1441         TupleMDF(TupleMemberDescriptionFactory {
1442             ty: tuple_type,
1443             component_types: component_types.to_vec(),
1444         }),
1445     )
1446 }
1447
1448 //=-----------------------------------------------------------------------------
1449 // Unions
1450 //=-----------------------------------------------------------------------------
1451
1452 struct UnionMemberDescriptionFactory<'tcx> {
1453     layout: TyAndLayout<'tcx>,
1454     variant: &'tcx ty::VariantDef,
1455 }
1456
1457 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1458     fn create_member_descriptions<'ll>(
1459         &self,
1460         cx: &CodegenCx<'ll, 'tcx>,
1461     ) -> Vec<MemberDescription<'ll>> {
1462         self.variant
1463             .fields
1464             .iter()
1465             .enumerate()
1466             .map(|(i, f)| {
1467                 let field = self.layout.field(cx, i);
1468                 MemberDescription {
1469                     name: f.name.to_string(),
1470                     type_metadata: type_metadata(cx, field.ty),
1471                     offset: Size::ZERO,
1472                     size: field.size,
1473                     align: field.align.abi,
1474                     flags: DIFlags::FlagZero,
1475                     discriminant: None,
1476                     source_info: None,
1477                 }
1478             })
1479             .collect()
1480     }
1481 }
1482
1483 fn prepare_union_metadata<'ll, 'tcx>(
1484     cx: &CodegenCx<'ll, 'tcx>,
1485     union_type: Ty<'tcx>,
1486     unique_type_id: UniqueTypeId,
1487 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1488     let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1489
1490     let (union_def_id, variant) = match union_type.kind() {
1491         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1492         _ => bug!("prepare_union_metadata on a non-ADT"),
1493     };
1494
1495     let containing_scope = get_namespace_for_item(cx, union_def_id);
1496
1497     let union_metadata_stub =
1498         create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1499
1500     create_and_register_recursive_type_forward_declaration(
1501         cx,
1502         union_type,
1503         unique_type_id,
1504         union_metadata_stub,
1505         union_metadata_stub,
1506         UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant }),
1507     )
1508 }
1509
1510 //=-----------------------------------------------------------------------------
1511 // Enums
1512 //=-----------------------------------------------------------------------------
1513
1514 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1515 // per generator monomorphization, but it doesn't depend on substs.
1516 fn generator_layout_and_saved_local_names<'tcx>(
1517     tcx: TyCtxt<'tcx>,
1518     def_id: DefId,
1519 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1520     let body = tcx.optimized_mir(def_id);
1521     let generator_layout = body.generator_layout().unwrap();
1522     let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1523
1524     let state_arg = mir::Local::new(1);
1525     for var in &body.var_debug_info {
1526         let mir::VarDebugInfoContents::Place(place) = &var.value else { continue };
1527         if place.local != state_arg {
1528             continue;
1529         }
1530         match place.projection[..] {
1531             [
1532                 // Deref of the `Pin<&mut Self>` state argument.
1533                 mir::ProjectionElem::Field(..),
1534                 mir::ProjectionElem::Deref,
1535                 // Field of a variant of the state.
1536                 mir::ProjectionElem::Downcast(_, variant),
1537                 mir::ProjectionElem::Field(field, _),
1538             ] => {
1539                 let name = &mut generator_saved_local_names
1540                     [generator_layout.variant_fields[variant][field]];
1541                 if name.is_none() {
1542                     name.replace(var.name);
1543                 }
1544             }
1545             _ => {}
1546         }
1547     }
1548     (generator_layout, generator_saved_local_names)
1549 }
1550
1551 /// Describes the members of an enum value; an enum is described as a union of
1552 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1553 /// the members of this union; so for every variant of the given enum, this
1554 /// factory will produce one `MemberDescription` (all with no name and a fixed
1555 /// offset of zero bytes).
1556 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1557     enum_type: Ty<'tcx>,
1558     layout: TyAndLayout<'tcx>,
1559     tag_type_metadata: Option<&'ll DIType>,
1560     common_members: Vec<Option<&'ll DIType>>,
1561 }
1562
1563 impl<'ll, 'tcx> EnumMemberDescriptionFactory<'ll, 'tcx> {
1564     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1565         let generator_variant_info_data = match *self.enum_type.kind() {
1566             ty::Generator(def_id, ..) => {
1567                 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1568             }
1569             _ => None,
1570         };
1571
1572         let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1573             ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1574             ty::Generator(def_id, _, _) => {
1575                 let (generator_layout, generator_saved_local_names) =
1576                     generator_variant_info_data.as_ref().unwrap();
1577                 VariantInfo::Generator {
1578                     def_id,
1579                     generator_layout: *generator_layout,
1580                     generator_saved_local_names,
1581                     variant_index: index,
1582                 }
1583             }
1584             _ => bug!(),
1585         };
1586
1587         // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
1588         // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
1589         // msvc, then we need to use a different, fallback encoding of the debuginfo.
1590         let fallback = cpp_like_debuginfo(cx.tcx);
1591         // This will always find the metadata in the type map.
1592         let self_metadata = type_metadata(cx, self.enum_type);
1593
1594         match self.layout.variants {
1595             Variants::Single { index } => {
1596                 if let ty::Adt(adt, _) = self.enum_type.kind() {
1597                     if adt.variants.is_empty() {
1598                         return vec![];
1599                     }
1600                 }
1601
1602                 let variant_info = variant_info_for(index);
1603                 let (variant_type_metadata, member_description_factory) =
1604                     describe_enum_variant(cx, self.layout, variant_info, self_metadata);
1605
1606                 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1607                 let type_params = compute_type_parameters(cx, self.enum_type);
1608
1609                 set_members_of_composite_type(
1610                     cx,
1611                     variant_type_metadata,
1612                     member_descriptions,
1613                     Some(&self.common_members),
1614                     type_params,
1615                 );
1616                 vec![MemberDescription {
1617                     name: variant_info.variant_name(),
1618                     type_metadata: variant_type_metadata,
1619                     offset: Size::ZERO,
1620                     size: self.layout.size,
1621                     align: self.layout.align.abi,
1622                     flags: DIFlags::FlagZero,
1623                     discriminant: None,
1624                     source_info: variant_info.source_info(cx),
1625                 }]
1626             }
1627             Variants::Multiple {
1628                 tag_encoding: TagEncoding::Direct,
1629                 tag_field,
1630                 ref variants,
1631                 ..
1632             } => {
1633                 let fallback_discr_variant = if fallback {
1634                     // For MSVC, we generate a union of structs for each variant and an
1635                     // explicit discriminant field roughly equivalent to the following C:
1636                     // ```c
1637                     // union enum$<{name}> {
1638                     //   struct {variant 0 name} {
1639                     //     <variant 0 fields>
1640                     //   } variant0;
1641                     //   <other variant structs>
1642                     //   {name} discriminant;
1643                     // }
1644                     // ```
1645                     // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1646                     // determine which variant is active and then displays it.
1647                     let enum_layout = self.layout;
1648                     let offset = enum_layout.fields.offset(tag_field);
1649                     let discr_ty = enum_layout.field(cx, tag_field).ty;
1650                     let (size, align) = cx.size_and_align_of(discr_ty);
1651                     Some(MemberDescription {
1652                         name: "discriminant".into(),
1653                         type_metadata: self.tag_type_metadata.unwrap(),
1654                         offset,
1655                         size,
1656                         align,
1657                         flags: DIFlags::FlagZero,
1658                         discriminant: None,
1659                         source_info: None,
1660                     })
1661                 } else {
1662                     None
1663                 };
1664
1665                 variants
1666                     .iter_enumerated()
1667                     .map(|(i, _)| {
1668                         let variant = self.layout.for_variant(cx, i);
1669                         let variant_info = variant_info_for(i);
1670                         let (variant_type_metadata, member_desc_factory) =
1671                             describe_enum_variant(cx, variant, variant_info, self_metadata);
1672
1673                         let member_descriptions =
1674                             member_desc_factory.create_member_descriptions(cx);
1675                         let type_params = compute_type_parameters(cx, self.enum_type);
1676
1677                         set_members_of_composite_type(
1678                             cx,
1679                             variant_type_metadata,
1680                             member_descriptions,
1681                             Some(&self.common_members),
1682                             type_params,
1683                         );
1684
1685                         MemberDescription {
1686                             name: if fallback {
1687                                 format!("variant{}", i.as_u32())
1688                             } else {
1689                                 variant_info.variant_name()
1690                             },
1691                             type_metadata: variant_type_metadata,
1692                             offset: Size::ZERO,
1693                             size: self.layout.size,
1694                             align: self.layout.align.abi,
1695                             flags: DIFlags::FlagZero,
1696                             discriminant: Some(
1697                                 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1698                                     as u64,
1699                             ),
1700                             source_info: variant_info.source_info(cx),
1701                         }
1702                     })
1703                     .chain(fallback_discr_variant.into_iter())
1704                     .collect()
1705             }
1706             Variants::Multiple {
1707                 tag_encoding:
1708                     TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1709                 tag,
1710                 ref variants,
1711                 tag_field,
1712             } => {
1713                 let calculate_niche_value = |i: VariantIdx| {
1714                     if i == dataful_variant {
1715                         None
1716                     } else {
1717                         let value = (i.as_u32() as u128)
1718                             .wrapping_sub(niche_variants.start().as_u32() as u128)
1719                             .wrapping_add(niche_start);
1720                         let value = tag.value.size(cx).truncate(value);
1721                         // NOTE(eddyb) do *NOT* remove this assert, until
1722                         // we pass the full 128-bit value to LLVM, otherwise
1723                         // truncation will be silent and remain undetected.
1724                         assert_eq!(value as u64 as u128, value);
1725                         Some(value as u64)
1726                     }
1727                 };
1728
1729                 // For MSVC, we will generate a union of two fields, one for the dataful variant
1730                 // and one that just points to the discriminant. We also create an enum that
1731                 // contains tag values for the non-dataful variants and make the discriminant field
1732                 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1733                 // This will generate debuginfo roughly equivalent to the following C:
1734                 // ```c
1735                 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1736                 //   struct <dataful variant name> {
1737                 //     <fields in dataful variant>
1738                 //   } dataful_variant;
1739                 //   enum Discriminant$ {
1740                 //     <non-dataful variants>
1741                 //   } discriminant;
1742                 // }
1743                 // ```
1744                 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1745                 // and evaluates `this.discriminant`. If the value is between the min niche and max
1746                 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1747                 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1748                 // case, we just need to render the name of the `this.discriminant` enum.
1749                 if fallback {
1750                     let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1751
1752                     let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1753                     // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1754                     // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1755                     // to just be `usize`.
1756                     if let ty::RawPtr(_) = discr_enum_ty.kind() {
1757                         discr_enum_ty = cx.tcx.types.usize;
1758                     }
1759
1760                     let tags: Vec<_> = variants
1761                         .iter_enumerated()
1762                         .filter_map(|(variant_idx, _)| {
1763                             calculate_niche_value(variant_idx).map(|tag| {
1764                                 let variant = variant_info_for(variant_idx);
1765                                 let name = variant.variant_name();
1766
1767                                 Some(unsafe {
1768                                     llvm::LLVMRustDIBuilderCreateEnumerator(
1769                                         DIB(cx),
1770                                         name.as_ptr().cast(),
1771                                         name.len(),
1772                                         tag as i64,
1773                                         !discr_enum_ty.is_signed(),
1774                                     )
1775                                 })
1776                             })
1777                         })
1778                         .collect();
1779
1780                     let discr_enum = unsafe {
1781                         llvm::LLVMRustDIBuilderCreateEnumerationType(
1782                             DIB(cx),
1783                             self_metadata,
1784                             "Discriminant$".as_ptr().cast(),
1785                             "Discriminant$".len(),
1786                             unknown_file_metadata(cx),
1787                             UNKNOWN_LINE_NUMBER,
1788                             tag.value.size(cx).bits(),
1789                             tag.value.align(cx).abi.bits() as u32,
1790                             create_DIArray(DIB(cx), &tags),
1791                             type_metadata(cx, discr_enum_ty),
1792                             true,
1793                         )
1794                     };
1795
1796                     let variant_info = variant_info_for(dataful_variant);
1797                     let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1798                         cx,
1799                         dataful_variant_layout,
1800                         variant_info,
1801                         self_metadata,
1802                     );
1803
1804                     let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1805                     let type_params = compute_type_parameters(cx, self.enum_type);
1806
1807                     set_members_of_composite_type(
1808                         cx,
1809                         variant_type_metadata,
1810                         member_descriptions,
1811                         Some(&self.common_members),
1812                         type_params,
1813                     );
1814
1815                     let (size, align) =
1816                         cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1817
1818                     vec![
1819                         MemberDescription {
1820                             // Name the dataful variant so that we can identify it for natvis
1821                             name: "dataful_variant".to_string(),
1822                             type_metadata: variant_type_metadata,
1823                             offset: Size::ZERO,
1824                             size: self.layout.size,
1825                             align: self.layout.align.abi,
1826                             flags: DIFlags::FlagZero,
1827                             discriminant: None,
1828                             source_info: variant_info.source_info(cx),
1829                         },
1830                         MemberDescription {
1831                             name: "discriminant".into(),
1832                             type_metadata: discr_enum,
1833                             offset: dataful_variant_layout.fields.offset(tag_field),
1834                             size,
1835                             align,
1836                             flags: DIFlags::FlagZero,
1837                             discriminant: None,
1838                             source_info: None,
1839                         },
1840                     ]
1841                 } else {
1842                     variants
1843                         .iter_enumerated()
1844                         .map(|(i, _)| {
1845                             let variant = self.layout.for_variant(cx, i);
1846                             let variant_info = variant_info_for(i);
1847                             let (variant_type_metadata, member_desc_factory) =
1848                                 describe_enum_variant(cx, variant, variant_info, self_metadata);
1849
1850                             let member_descriptions =
1851                                 member_desc_factory.create_member_descriptions(cx);
1852                             let type_params = compute_type_parameters(cx, self.enum_type);
1853
1854                             set_members_of_composite_type(
1855                                 cx,
1856                                 variant_type_metadata,
1857                                 member_descriptions,
1858                                 Some(&self.common_members),
1859                                 type_params,
1860                             );
1861
1862                             let niche_value = calculate_niche_value(i);
1863
1864                             MemberDescription {
1865                                 name: variant_info.variant_name(),
1866                                 type_metadata: variant_type_metadata,
1867                                 offset: Size::ZERO,
1868                                 size: self.layout.size,
1869                                 align: self.layout.align.abi,
1870                                 flags: DIFlags::FlagZero,
1871                                 discriminant: niche_value,
1872                                 source_info: variant_info.source_info(cx),
1873                             }
1874                         })
1875                         .collect()
1876                 }
1877             }
1878         }
1879     }
1880 }
1881
1882 // Creates `MemberDescription`s for the fields of a single enum variant.
1883 struct VariantMemberDescriptionFactory<'tcx> {
1884     /// Cloned from the `layout::Struct` describing the variant.
1885     offsets: Vec<Size>,
1886     args: Vec<(String, Ty<'tcx>)>,
1887 }
1888
1889 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1890     fn create_member_descriptions<'ll>(
1891         &self,
1892         cx: &CodegenCx<'ll, 'tcx>,
1893     ) -> Vec<MemberDescription<'ll>> {
1894         self.args
1895             .iter()
1896             .enumerate()
1897             .map(|(i, &(ref name, ty))| {
1898                 let (size, align) = cx.size_and_align_of(ty);
1899                 MemberDescription {
1900                     name: name.to_string(),
1901                     type_metadata: type_metadata(cx, ty),
1902                     offset: self.offsets[i],
1903                     size,
1904                     align,
1905                     flags: DIFlags::FlagZero,
1906                     discriminant: None,
1907                     source_info: None,
1908                 }
1909             })
1910             .collect()
1911     }
1912 }
1913
1914 #[derive(Copy, Clone)]
1915 enum VariantInfo<'a, 'tcx> {
1916     Adt(&'tcx ty::VariantDef),
1917     Generator {
1918         def_id: DefId,
1919         generator_layout: &'tcx GeneratorLayout<'tcx>,
1920         generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1921         variant_index: VariantIdx,
1922     },
1923 }
1924
1925 impl<'tcx> VariantInfo<'_, 'tcx> {
1926     fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1927         match self {
1928             VariantInfo::Adt(variant) => f(variant.name.as_str()),
1929             VariantInfo::Generator { variant_index, .. } => {
1930                 f(&GeneratorSubsts::variant_name(*variant_index))
1931             }
1932         }
1933     }
1934
1935     fn variant_name(&self) -> String {
1936         match self {
1937             VariantInfo::Adt(variant) => variant.name.to_string(),
1938             VariantInfo::Generator { variant_index, .. } => {
1939                 // Since GDB currently prints out the raw discriminant along
1940                 // with every variant, make each variant name be just the value
1941                 // of the discriminant. The struct name for the variant includes
1942                 // the actual variant description.
1943                 format!("{}", variant_index.as_usize())
1944             }
1945         }
1946     }
1947
1948     fn field_name(&self, i: usize) -> String {
1949         let field_name = match *self {
1950             VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1951                 Some(variant.fields[i].name)
1952             }
1953             VariantInfo::Generator {
1954                 generator_layout,
1955                 generator_saved_local_names,
1956                 variant_index,
1957                 ..
1958             } => {
1959                 generator_saved_local_names
1960                     [generator_layout.variant_fields[variant_index][i.into()]]
1961             }
1962             _ => None,
1963         };
1964         field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1965     }
1966
1967     fn source_info<'ll>(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1968         if let VariantInfo::Generator { def_id, variant_index, .. } = self {
1969             let span =
1970                 cx.tcx.generator_layout(*def_id).unwrap().variant_source_info[*variant_index].span;
1971             if !span.is_dummy() {
1972                 let loc = cx.lookup_debug_loc(span.lo());
1973                 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
1974             }
1975         }
1976         None
1977     }
1978 }
1979
1980 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1981 /// `MemberDescriptionFactory` for producing the descriptions of the
1982 /// fields of the variant. This is a rudimentary version of a full
1983 /// `RecursiveTypeDescription`.
1984 fn describe_enum_variant<'ll, 'tcx>(
1985     cx: &CodegenCx<'ll, 'tcx>,
1986     layout: layout::TyAndLayout<'tcx>,
1987     variant: VariantInfo<'_, 'tcx>,
1988     containing_scope: &'ll DIScope,
1989 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1990     let metadata_stub = variant.map_struct_name(|variant_name| {
1991         let unique_type_id = debug_context(cx)
1992             .type_map
1993             .borrow_mut()
1994             .get_unique_type_id_of_enum_variant(cx, layout.ty, variant_name);
1995
1996         let (size, align) = cx.size_and_align_of(layout.ty);
1997
1998         create_struct_stub(
1999             cx,
2000             size,
2001             align,
2002             variant_name,
2003             unique_type_id,
2004             Some(containing_scope),
2005             DIFlags::FlagZero,
2006             None,
2007         )
2008     });
2009
2010     let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
2011     let args = (0..layout.fields.count())
2012         .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
2013         .collect();
2014
2015     let member_description_factory = VariantMDF(VariantMemberDescriptionFactory { offsets, args });
2016
2017     (metadata_stub, member_description_factory)
2018 }
2019
2020 fn prepare_enum_metadata<'ll, 'tcx>(
2021     cx: &CodegenCx<'ll, 'tcx>,
2022     enum_type: Ty<'tcx>,
2023     enum_def_id: DefId,
2024     unique_type_id: UniqueTypeId,
2025     outer_field_tys: Vec<Ty<'tcx>>,
2026 ) -> RecursiveTypeDescription<'ll, 'tcx> {
2027     let tcx = cx.tcx;
2028     let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
2029
2030     let containing_scope = get_namespace_for_item(cx, enum_def_id);
2031     // FIXME: This should emit actual file metadata for the enum, but we
2032     // currently can't get the necessary information when it comes to types
2033     // imported from other crates. Formerly we violated the ODR when performing
2034     // LTO because we emitted debuginfo for the same type with varying file
2035     // metadata, so as a workaround we pretend that the type comes from
2036     // <unknown>
2037     let file_metadata = unknown_file_metadata(cx);
2038
2039     let discriminant_type_metadata = |discr: Primitive| {
2040         let enumerators_metadata: Vec<_> = match enum_type.kind() {
2041             ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
2042                 .map(|((_, discr), v)| {
2043                     let name = v.name.as_str();
2044                     let is_unsigned = match discr.ty.kind() {
2045                         ty::Int(_) => false,
2046                         ty::Uint(_) => true,
2047                         _ => bug!("non integer discriminant"),
2048                     };
2049                     unsafe {
2050                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2051                             DIB(cx),
2052                             name.as_ptr().cast(),
2053                             name.len(),
2054                             // FIXME: what if enumeration has i128 discriminant?
2055                             discr.val as i64,
2056                             is_unsigned,
2057                         ))
2058                     }
2059                 })
2060                 .collect(),
2061             ty::Generator(_, substs, _) => substs
2062                 .as_generator()
2063                 .variant_range(enum_def_id, tcx)
2064                 .map(|variant_index| {
2065                     debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
2066                     let name = GeneratorSubsts::variant_name(variant_index);
2067                     unsafe {
2068                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2069                             DIB(cx),
2070                             name.as_ptr().cast(),
2071                             name.len(),
2072                             // Generators use u32 as discriminant type, verified above.
2073                             variant_index.as_u32().into(),
2074                             true, // IsUnsigned
2075                         ))
2076                     }
2077                 })
2078                 .collect(),
2079             _ => bug!(),
2080         };
2081
2082         let disr_type_key = (enum_def_id, discr);
2083         let cached_discriminant_type_metadata =
2084             debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2085         match cached_discriminant_type_metadata {
2086             Some(discriminant_type_metadata) => discriminant_type_metadata,
2087             None => {
2088                 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2089                 let discriminant_base_type_metadata = type_metadata(cx, discr.to_ty(tcx));
2090
2091                 let item_name;
2092                 let discriminant_name = match enum_type.kind() {
2093                     ty::Adt(..) => {
2094                         item_name = tcx.item_name(enum_def_id);
2095                         item_name.as_str()
2096                     }
2097                     ty::Generator(..) => enum_name.as_str(),
2098                     _ => bug!(),
2099                 };
2100
2101                 let discriminant_type_metadata = unsafe {
2102                     llvm::LLVMRustDIBuilderCreateEnumerationType(
2103                         DIB(cx),
2104                         containing_scope,
2105                         discriminant_name.as_ptr().cast(),
2106                         discriminant_name.len(),
2107                         file_metadata,
2108                         UNKNOWN_LINE_NUMBER,
2109                         discriminant_size.bits(),
2110                         discriminant_align.abi.bits() as u32,
2111                         create_DIArray(DIB(cx), &enumerators_metadata),
2112                         discriminant_base_type_metadata,
2113                         true,
2114                     )
2115                 };
2116
2117                 debug_context(cx)
2118                     .created_enum_disr_types
2119                     .borrow_mut()
2120                     .insert(disr_type_key, discriminant_type_metadata);
2121
2122                 discriminant_type_metadata
2123             }
2124         }
2125     };
2126
2127     let layout = cx.layout_of(enum_type);
2128
2129     if let (Abi::Scalar(_), Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. }) =
2130         (layout.abi, &layout.variants)
2131     {
2132         return FinalMetadata(discriminant_type_metadata(tag.value));
2133     }
2134
2135     // While LLVM supports generating debuginfo for variant types (enums), it doesn't support
2136     // lowering that debuginfo to CodeView records for msvc targets. So if we are targeting
2137     // msvc, then we need to use a different encoding of the debuginfo.
2138     if cpp_like_debuginfo(tcx) {
2139         let discriminant_type_metadata = match layout.variants {
2140             Variants::Single { .. } => None,
2141             Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, .. }
2142             | Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. } => {
2143                 Some(discriminant_type_metadata(tag.value))
2144             }
2145         };
2146
2147         let enum_metadata = {
2148             let type_map = debug_context(cx).type_map.borrow();
2149             let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2150
2151             unsafe {
2152                 llvm::LLVMRustDIBuilderCreateUnionType(
2153                     DIB(cx),
2154                     None,
2155                     enum_name.as_ptr().cast(),
2156                     enum_name.len(),
2157                     file_metadata,
2158                     UNKNOWN_LINE_NUMBER,
2159                     layout.size.bits(),
2160                     layout.align.abi.bits() as u32,
2161                     DIFlags::FlagZero,
2162                     None,
2163                     0, // RuntimeLang
2164                     unique_type_id_str.as_ptr().cast(),
2165                     unique_type_id_str.len(),
2166                 )
2167             }
2168         };
2169
2170         return create_and_register_recursive_type_forward_declaration(
2171             cx,
2172             enum_type,
2173             unique_type_id,
2174             enum_metadata,
2175             enum_metadata,
2176             EnumMDF(EnumMemberDescriptionFactory {
2177                 enum_type,
2178                 layout,
2179                 tag_type_metadata: discriminant_type_metadata,
2180                 common_members: vec![],
2181             }),
2182         );
2183     }
2184
2185     let discriminator_name = match enum_type.kind() {
2186         ty::Generator(..) => "__state",
2187         _ => "",
2188     };
2189     let discriminator_metadata = match layout.variants {
2190         // A single-variant enum has no discriminant.
2191         Variants::Single { .. } => None,
2192
2193         Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, tag_field, .. } => {
2194             // Find the integer type of the correct size.
2195             let size = tag.value.size(cx);
2196             let align = tag.value.align(cx);
2197
2198             let tag_type = match tag.value {
2199                 Int(t, _) => t,
2200                 F32 => Integer::I32,
2201                 F64 => Integer::I64,
2202                 Pointer => cx.data_layout().ptr_sized_integer(),
2203             }
2204             .to_ty(cx.tcx, false);
2205
2206             let tag_metadata = basic_type_metadata(cx, tag_type);
2207             unsafe {
2208                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2209                     DIB(cx),
2210                     containing_scope,
2211                     discriminator_name.as_ptr().cast(),
2212                     discriminator_name.len(),
2213                     file_metadata,
2214                     UNKNOWN_LINE_NUMBER,
2215                     size.bits(),
2216                     align.abi.bits() as u32,
2217                     layout.fields.offset(tag_field).bits(),
2218                     DIFlags::FlagArtificial,
2219                     tag_metadata,
2220                 ))
2221             }
2222         }
2223
2224         Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, tag_field, .. } => {
2225             let discr_type = tag.value.to_ty(cx.tcx);
2226             let (size, align) = cx.size_and_align_of(discr_type);
2227
2228             let discr_metadata = basic_type_metadata(cx, discr_type);
2229             unsafe {
2230                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2231                     DIB(cx),
2232                     containing_scope,
2233                     discriminator_name.as_ptr().cast(),
2234                     discriminator_name.len(),
2235                     file_metadata,
2236                     UNKNOWN_LINE_NUMBER,
2237                     size.bits(),
2238                     align.bits() as u32,
2239                     layout.fields.offset(tag_field).bits(),
2240                     DIFlags::FlagArtificial,
2241                     discr_metadata,
2242                 ))
2243             }
2244         }
2245     };
2246
2247     let outer_fields = match layout.variants {
2248         Variants::Single { .. } => vec![],
2249         Variants::Multiple { .. } => {
2250             let tuple_mdf =
2251                 TupleMemberDescriptionFactory { ty: enum_type, component_types: outer_field_tys };
2252             tuple_mdf
2253                 .create_member_descriptions(cx)
2254                 .into_iter()
2255                 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2256                 .collect()
2257         }
2258     };
2259
2260     let variant_part_unique_type_id_str = debug_context(cx)
2261         .type_map
2262         .borrow_mut()
2263         .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2264     let empty_array = create_DIArray(DIB(cx), &[]);
2265     let name = "";
2266     let variant_part = unsafe {
2267         llvm::LLVMRustDIBuilderCreateVariantPart(
2268             DIB(cx),
2269             containing_scope,
2270             name.as_ptr().cast(),
2271             name.len(),
2272             file_metadata,
2273             UNKNOWN_LINE_NUMBER,
2274             layout.size.bits(),
2275             layout.align.abi.bits() as u32,
2276             DIFlags::FlagZero,
2277             discriminator_metadata,
2278             empty_array,
2279             variant_part_unique_type_id_str.as_ptr().cast(),
2280             variant_part_unique_type_id_str.len(),
2281         )
2282     };
2283
2284     let struct_wrapper = {
2285         // The variant part must be wrapped in a struct according to DWARF.
2286         // All fields except the discriminant (including `outer_fields`)
2287         // should be put into structures inside the variant part, which gives
2288         // an equivalent layout but offers us much better integration with
2289         // debuggers.
2290         let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2291
2292         let type_map = debug_context(cx).type_map.borrow();
2293         let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2294
2295         unsafe {
2296             llvm::LLVMRustDIBuilderCreateStructType(
2297                 DIB(cx),
2298                 Some(containing_scope),
2299                 enum_name.as_ptr().cast(),
2300                 enum_name.len(),
2301                 file_metadata,
2302                 UNKNOWN_LINE_NUMBER,
2303                 layout.size.bits(),
2304                 layout.align.abi.bits() as u32,
2305                 DIFlags::FlagZero,
2306                 None,
2307                 type_array,
2308                 0,
2309                 None,
2310                 unique_type_id_str.as_ptr().cast(),
2311                 unique_type_id_str.len(),
2312             )
2313         }
2314     };
2315
2316     create_and_register_recursive_type_forward_declaration(
2317         cx,
2318         enum_type,
2319         unique_type_id,
2320         struct_wrapper,
2321         variant_part,
2322         EnumMDF(EnumMemberDescriptionFactory {
2323             enum_type,
2324             layout,
2325             tag_type_metadata: None,
2326             common_members: outer_fields,
2327         }),
2328     )
2329 }
2330
2331 /// Creates debug information for a composite type, that is, anything that
2332 /// results in a LLVM struct.
2333 ///
2334 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2335 fn composite_type_metadata<'ll, 'tcx>(
2336     cx: &CodegenCx<'ll, 'tcx>,
2337     composite_type: Ty<'tcx>,
2338     composite_type_name: &str,
2339     composite_type_unique_id: UniqueTypeId,
2340     member_descriptions: Vec<MemberDescription<'ll>>,
2341     containing_scope: Option<&'ll DIScope>,
2342 ) -> &'ll DICompositeType {
2343     let (size, align) = cx.size_and_align_of(composite_type);
2344
2345     // Create the (empty) struct metadata node ...
2346     let composite_type_metadata = create_struct_stub(
2347         cx,
2348         size,
2349         align,
2350         composite_type_name,
2351         composite_type_unique_id,
2352         containing_scope,
2353         DIFlags::FlagZero,
2354         None,
2355     );
2356
2357     // ... and immediately create and add the member descriptions.
2358     set_members_of_composite_type(
2359         cx,
2360         composite_type_metadata,
2361         member_descriptions,
2362         None,
2363         compute_type_parameters(cx, composite_type),
2364     );
2365
2366     composite_type_metadata
2367 }
2368
2369 fn set_members_of_composite_type<'ll, 'tcx>(
2370     cx: &CodegenCx<'ll, 'tcx>,
2371     composite_type_metadata: &'ll DICompositeType,
2372     member_descriptions: Vec<MemberDescription<'ll>>,
2373     common_members: Option<&Vec<Option<&'ll DIType>>>,
2374     type_params: &'ll DIArray,
2375 ) {
2376     // In some rare cases LLVM metadata uniquing would lead to an existing type
2377     // description being used instead of a new one created in
2378     // create_struct_stub. This would cause a hard to trace assertion in
2379     // DICompositeType::SetTypeArray(). The following check makes sure that we
2380     // get a better error message if this should happen again due to some
2381     // regression.
2382     {
2383         let mut composite_types_completed =
2384             debug_context(cx).composite_types_completed.borrow_mut();
2385         if !composite_types_completed.insert(composite_type_metadata) {
2386             bug!(
2387                 "debuginfo::set_members_of_composite_type() - \
2388                   Already completed forward declaration re-encountered."
2389             );
2390         }
2391     }
2392
2393     let mut member_metadata: Vec<_> = member_descriptions
2394         .into_iter()
2395         .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2396         .collect();
2397     if let Some(other_members) = common_members {
2398         member_metadata.extend(other_members.iter());
2399     }
2400
2401     unsafe {
2402         let field_array = create_DIArray(DIB(cx), &member_metadata);
2403         llvm::LLVMRustDICompositeTypeReplaceArrays(
2404             DIB(cx),
2405             composite_type_metadata,
2406             Some(field_array),
2407             Some(type_params),
2408         );
2409     }
2410 }
2411
2412 /// Computes the type parameters for a type, if any, for the given metadata.
2413 fn compute_type_parameters<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2414     if let ty::Adt(def, substs) = *ty.kind() {
2415         if substs.types().next().is_some() {
2416             let generics = cx.tcx.generics_of(def.did);
2417             let names = get_parameter_names(cx, generics);
2418             let template_params: Vec<_> = iter::zip(substs, names)
2419                 .filter_map(|(kind, name)| {
2420                     if let GenericArgKind::Type(ty) = kind.unpack() {
2421                         let actual_type =
2422                             cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2423                         let actual_type_metadata = type_metadata(cx, actual_type);
2424                         let name = name.as_str();
2425                         Some(unsafe {
2426                             Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2427                                 DIB(cx),
2428                                 None,
2429                                 name.as_ptr().cast(),
2430                                 name.len(),
2431                                 actual_type_metadata,
2432                             ))
2433                         })
2434                     } else {
2435                         None
2436                     }
2437                 })
2438                 .collect();
2439
2440             return create_DIArray(DIB(cx), &template_params);
2441         }
2442     }
2443     return create_DIArray(DIB(cx), &[]);
2444
2445     fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2446         let mut names = generics
2447             .parent
2448             .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2449         names.extend(generics.params.iter().map(|param| param.name));
2450         names
2451     }
2452 }
2453
2454 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2455 /// any caching, does not add any fields to the struct. This can be done later
2456 /// with `set_members_of_composite_type()`.
2457 fn create_struct_stub<'ll, 'tcx>(
2458     cx: &CodegenCx<'ll, 'tcx>,
2459     size: Size,
2460     align: Align,
2461     type_name: &str,
2462     unique_type_id: UniqueTypeId,
2463     containing_scope: Option<&'ll DIScope>,
2464     flags: DIFlags,
2465     vtable_holder: Option<&'ll DIType>,
2466 ) -> &'ll DICompositeType {
2467     let type_map = debug_context(cx).type_map.borrow();
2468     let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2469
2470     let metadata_stub = unsafe {
2471         // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2472         // pointer will lead to hard to trace and debug LLVM assertions
2473         // later on in `llvm/lib/IR/Value.cpp`.
2474         let empty_array = create_DIArray(DIB(cx), &[]);
2475
2476         llvm::LLVMRustDIBuilderCreateStructType(
2477             DIB(cx),
2478             containing_scope,
2479             type_name.as_ptr().cast(),
2480             type_name.len(),
2481             unknown_file_metadata(cx),
2482             UNKNOWN_LINE_NUMBER,
2483             size.bits(),
2484             align.bits() as u32,
2485             flags,
2486             None,
2487             empty_array,
2488             0,
2489             vtable_holder,
2490             unique_type_id.as_ptr().cast(),
2491             unique_type_id.len(),
2492         )
2493     };
2494
2495     metadata_stub
2496 }
2497
2498 fn create_union_stub<'ll, 'tcx>(
2499     cx: &CodegenCx<'ll, 'tcx>,
2500     union_type: Ty<'tcx>,
2501     union_type_name: &str,
2502     unique_type_id: UniqueTypeId,
2503     containing_scope: &'ll DIScope,
2504 ) -> &'ll DICompositeType {
2505     let (union_size, union_align) = cx.size_and_align_of(union_type);
2506
2507     let type_map = debug_context(cx).type_map.borrow();
2508     let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2509
2510     let metadata_stub = unsafe {
2511         // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2512         // pointer will lead to hard to trace and debug LLVM assertions
2513         // later on in `llvm/lib/IR/Value.cpp`.
2514         let empty_array = create_DIArray(DIB(cx), &[]);
2515
2516         llvm::LLVMRustDIBuilderCreateUnionType(
2517             DIB(cx),
2518             Some(containing_scope),
2519             union_type_name.as_ptr().cast(),
2520             union_type_name.len(),
2521             unknown_file_metadata(cx),
2522             UNKNOWN_LINE_NUMBER,
2523             union_size.bits(),
2524             union_align.bits() as u32,
2525             DIFlags::FlagZero,
2526             Some(empty_array),
2527             0, // RuntimeLang
2528             unique_type_id.as_ptr().cast(),
2529             unique_type_id.len(),
2530         )
2531     };
2532
2533     metadata_stub
2534 }
2535
2536 /// Creates debug information for the given global variable.
2537 ///
2538 /// Adds the created metadata nodes directly to the crate's IR.
2539 pub fn create_global_var_metadata<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2540     if cx.dbg_cx.is_none() {
2541         return;
2542     }
2543
2544     // Only create type information if full debuginfo is enabled
2545     if cx.sess().opts.debuginfo != DebugInfo::Full {
2546         return;
2547     }
2548
2549     let tcx = cx.tcx;
2550
2551     // We may want to remove the namespace scope if we're in an extern block (see
2552     // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2553     let var_scope = get_namespace_for_item(cx, def_id);
2554     let span = tcx.def_span(def_id);
2555
2556     let (file_metadata, line_number) = if !span.is_dummy() {
2557         let loc = cx.lookup_debug_loc(span.lo());
2558         (file_metadata(cx, &loc.file), loc.line)
2559     } else {
2560         (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2561     };
2562
2563     let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2564     let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2565     let type_metadata = type_metadata(cx, variable_type);
2566     let var_name = tcx.item_name(def_id);
2567     let var_name = var_name.as_str();
2568     let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2569     // When empty, linkage_name field is omitted,
2570     // which is what we want for no_mangle statics
2571     let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2572
2573     let global_align = cx.align_of(variable_type);
2574
2575     unsafe {
2576         llvm::LLVMRustDIBuilderCreateStaticVariable(
2577             DIB(cx),
2578             Some(var_scope),
2579             var_name.as_ptr().cast(),
2580             var_name.len(),
2581             linkage_name.as_ptr().cast(),
2582             linkage_name.len(),
2583             file_metadata,
2584             line_number,
2585             type_metadata,
2586             is_local_to_unit,
2587             global,
2588             None,
2589             global_align.bytes() as u32,
2590         );
2591     }
2592 }
2593
2594 /// Generates LLVM debuginfo for a vtable.
2595 ///
2596 /// The vtable type looks like a struct with a field for each function pointer and super-trait
2597 /// pointer it contains (plus the `size` and `align` fields).
2598 ///
2599 /// Except for `size`, `align`, and `drop_in_place`, the field names don't try to mirror
2600 /// the name of the method they implement. This can be implemented in the future once there
2601 /// is a proper disambiguation scheme for dealing with methods from different traits that have
2602 /// the same name.
2603 fn vtable_type_metadata<'ll, 'tcx>(
2604     cx: &CodegenCx<'ll, 'tcx>,
2605     ty: Ty<'tcx>,
2606     poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2607 ) -> &'ll DIType {
2608     let tcx = cx.tcx;
2609
2610     let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
2611         let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
2612         let trait_ref = tcx.erase_regions(trait_ref);
2613
2614         tcx.vtable_entries(trait_ref)
2615     } else {
2616         COMMON_VTABLE_ENTRIES
2617     };
2618
2619     // All function pointers are described as opaque pointers. This could be improved in the future
2620     // by describing them as actual function pointers.
2621     let void_pointer_ty = tcx.mk_imm_ptr(tcx.types.unit);
2622     let void_pointer_type_debuginfo = type_metadata(cx, void_pointer_ty);
2623     let usize_debuginfo = type_metadata(cx, tcx.types.usize);
2624     let (pointer_size, pointer_align) = cx.size_and_align_of(void_pointer_ty);
2625     // If `usize` is not pointer-sized and -aligned then the size and alignment computations
2626     // for the vtable as a whole would be wrong. Let's make sure this holds even on weird
2627     // platforms.
2628     assert_eq!(cx.size_and_align_of(tcx.types.usize), (pointer_size, pointer_align));
2629
2630     let vtable_type_name =
2631         compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
2632     let unique_type_id = debug_context(cx)
2633         .type_map
2634         .borrow_mut()
2635         .get_unique_type_id_of_vtable_type(&vtable_type_name);
2636     let size = pointer_size * vtable_entries.len() as u64;
2637
2638     // This gets mapped to a DW_AT_containing_type attribute which allows GDB to correlate
2639     // the vtable to the type it is for.
2640     let vtable_holder = type_metadata(cx, ty);
2641
2642     let vtable_type_metadata = create_struct_stub(
2643         cx,
2644         size,
2645         pointer_align,
2646         &vtable_type_name,
2647         unique_type_id,
2648         NO_SCOPE_METADATA,
2649         DIFlags::FlagArtificial,
2650         Some(vtable_holder),
2651     );
2652
2653     // Create a field for each entry in the vtable.
2654     let fields: Vec<_> = vtable_entries
2655         .iter()
2656         .enumerate()
2657         .filter_map(|(index, vtable_entry)| {
2658             let (field_name, field_type) = match vtable_entry {
2659                 ty::VtblEntry::MetadataDropInPlace => {
2660                     ("drop_in_place".to_string(), void_pointer_type_debuginfo)
2661                 }
2662                 ty::VtblEntry::Method(_) => {
2663                     // Note: This code does not try to give a proper name to each method
2664                     //       because there might be multiple methods with the same name
2665                     //       (coming from different traits).
2666                     (format!("__method{}", index), void_pointer_type_debuginfo)
2667                 }
2668                 ty::VtblEntry::TraitVPtr(_) => {
2669                     // Note: In the future we could try to set the type of this pointer
2670                     //       to the type that we generate for the corresponding vtable.
2671                     (format!("__super_trait_ptr{}", index), void_pointer_type_debuginfo)
2672                 }
2673                 ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_debuginfo),
2674                 ty::VtblEntry::MetadataSize => ("size".to_string(), usize_debuginfo),
2675                 ty::VtblEntry::Vacant => return None,
2676             };
2677
2678             Some(MemberDescription {
2679                 name: field_name,
2680                 type_metadata: field_type,
2681                 offset: pointer_size * index as u64,
2682                 size: pointer_size,
2683                 align: pointer_align,
2684                 flags: DIFlags::FlagZero,
2685                 discriminant: None,
2686                 source_info: None,
2687             })
2688         })
2689         .collect();
2690
2691     let type_params = create_DIArray(DIB(cx), &[]);
2692     set_members_of_composite_type(cx, vtable_type_metadata, fields, None, type_params);
2693     vtable_type_metadata
2694 }
2695
2696 /// Creates debug information for the given vtable, which is for the
2697 /// given type.
2698 ///
2699 /// Adds the created metadata nodes directly to the crate's IR.
2700 pub fn create_vtable_metadata<'ll, 'tcx>(
2701     cx: &CodegenCx<'ll, 'tcx>,
2702     ty: Ty<'tcx>,
2703     poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2704     vtable: &'ll Value,
2705 ) {
2706     if cx.dbg_cx.is_none() {
2707         return;
2708     }
2709
2710     // Only create type information if full debuginfo is enabled
2711     if cx.sess().opts.debuginfo != DebugInfo::Full {
2712         return;
2713     }
2714
2715     let vtable_name =
2716         compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
2717     let vtable_type = vtable_type_metadata(cx, ty, poly_trait_ref);
2718     let linkage_name = "";
2719
2720     unsafe {
2721         llvm::LLVMRustDIBuilderCreateStaticVariable(
2722             DIB(cx),
2723             NO_SCOPE_METADATA,
2724             vtable_name.as_ptr().cast(),
2725             vtable_name.len(),
2726             linkage_name.as_ptr().cast(),
2727             linkage_name.len(),
2728             unknown_file_metadata(cx),
2729             UNKNOWN_LINE_NUMBER,
2730             vtable_type,
2731             true,
2732             vtable,
2733             None,
2734             0,
2735         );
2736     }
2737 }
2738
2739 /// Creates an "extension" of an existing `DIScope` into another file.
2740 pub fn extend_scope_to_file<'ll>(
2741     cx: &CodegenCx<'ll, '_>,
2742     scope_metadata: &'ll DIScope,
2743     file: &SourceFile,
2744 ) -> &'ll DILexicalBlock {
2745     let file_metadata = file_metadata(cx, file);
2746     unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }
2747 }