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