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