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