]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Rollup merge of #91597 - r00ster91:lessthangreaterthan, r=oli-obk
[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 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(
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 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(
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(
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(
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(
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(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Span) -> &'ll DIType {
592     // Get the unique type ID of this type.
593     let unique_type_id = {
594         let mut type_map = debug_context(cx).type_map.borrow_mut();
595         // First, try to find the type in `TypeMap`. If we have seen it before, we
596         // can exit early here.
597         match type_map.find_metadata_for_type(t) {
598             Some(metadata) => {
599                 return metadata;
600             }
601             None => {
602                 // The Ty is not in the `TypeMap` but maybe we have already seen
603                 // an equivalent type (e.g., only differing in region arguments).
604                 // In order to find out, generate the unique type ID and look
605                 // that up.
606                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
607                 match type_map.find_metadata_for_unique_id(unique_type_id) {
608                     Some(metadata) => {
609                         // There is already an equivalent type in the TypeMap.
610                         // Register this Ty as an alias in the cache and
611                         // return the cached metadata.
612                         type_map.register_type_with_metadata(t, metadata);
613                         return metadata;
614                     }
615                     None => {
616                         // There really is no type metadata for this type, so
617                         // proceed by creating it.
618                         unique_type_id
619                     }
620                 }
621             }
622         }
623     };
624
625     debug!("type_metadata: {:?}", t);
626
627     let ptr_metadata = |ty: Ty<'tcx>| match *ty.kind() {
628         ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)),
629         ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)),
630         ty::Dynamic(..) => Ok(MetadataCreationResult::new(
631             trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
632             false,
633         )),
634         _ => {
635             let pointee_metadata = type_metadata(cx, ty, usage_site_span);
636
637             if let Some(metadata) =
638                 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
639             {
640                 return Err(metadata);
641             }
642
643             Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), false))
644         }
645     };
646
647     let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
648         ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
649             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
650         }
651         ty::Tuple(elements) if elements.is_empty() => {
652             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
653         }
654         ty::Array(typ, _) | ty::Slice(typ) => {
655             fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
656         }
657         ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span),
658         ty::Dynamic(..) => {
659             MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false)
660         }
661         ty::Foreign(..) => {
662             MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
663         }
664         ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => match ptr_metadata(ty) {
665             Ok(res) => res,
666             Err(metadata) => return metadata,
667         },
668         ty::Adt(def, _) if def.is_box() => match ptr_metadata(t.boxed_ty()) {
669             Ok(res) => res,
670             Err(metadata) => return metadata,
671         },
672         ty::FnDef(..) | ty::FnPtr(_) => {
673             if let Some(metadata) =
674                 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
675             {
676                 return metadata;
677             }
678
679             // It's possible to create a self-referential
680             // type in Rust by using 'impl trait':
681             //
682             // fn foo() -> impl Copy { foo }
683             //
684             // See `TypeMap::remove_type` for more detals
685             // about the workaround.
686
687             let temp_type = {
688                 unsafe {
689                     // The choice of type here is pretty arbitrary -
690                     // anything reading the debuginfo for a recursive
691                     // type is going to see *something* weird - the only
692                     // question is what exactly it will see.
693                     let name = "<recur_type>";
694                     llvm::LLVMRustDIBuilderCreateBasicType(
695                         DIB(cx),
696                         name.as_ptr().cast(),
697                         name.len(),
698                         cx.size_of(t).bits(),
699                         DW_ATE_unsigned,
700                     )
701                 }
702             };
703
704             let type_map = &debug_context(cx).type_map;
705             type_map.borrow_mut().register_type_with_metadata(t, temp_type);
706
707             let fn_metadata =
708                 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx), usage_site_span)
709                     .metadata;
710
711             type_map.borrow_mut().remove_type(t);
712
713             // This is actually a function pointer, so wrap it in pointer DI.
714             MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
715         }
716         ty::Closure(def_id, substs) => {
717             let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
718             let containing_scope = get_namespace_for_item(cx, def_id);
719             prepare_tuple_metadata(
720                 cx,
721                 t,
722                 &upvar_tys,
723                 unique_type_id,
724                 usage_site_span,
725                 Some(containing_scope),
726             )
727             .finalize(cx)
728         }
729         ty::Generator(def_id, substs, _) => {
730             let upvar_tys: Vec<_> = substs
731                 .as_generator()
732                 .prefix_tys()
733                 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
734                 .collect();
735             prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span, upvar_tys)
736                 .finalize(cx)
737         }
738         ty::Adt(def, ..) => match def.adt_kind() {
739             AdtKind::Struct => {
740                 prepare_struct_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
741             }
742             AdtKind::Union => {
743                 prepare_union_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
744             }
745             AdtKind::Enum => {
746                 prepare_enum_metadata(cx, t, def.did, unique_type_id, usage_site_span, vec![])
747                     .finalize(cx)
748             }
749         },
750         ty::Tuple(elements) => {
751             let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
752             prepare_tuple_metadata(cx, t, &tys, unique_type_id, usage_site_span, NO_SCOPE_METADATA)
753                 .finalize(cx)
754         }
755         // Type parameters from polymorphized functions.
756         ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
757         _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
758     };
759
760     {
761         let mut type_map = debug_context(cx).type_map.borrow_mut();
762
763         if already_stored_in_typemap {
764             // Also make sure that we already have a `TypeMap` entry for the unique type ID.
765             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
766                 Some(metadata) => metadata,
767                 None => {
768                     span_bug!(
769                         usage_site_span,
770                         "expected type metadata for unique \
771                                type ID '{}' to already be in \
772                                the `debuginfo::TypeMap` but it \
773                                was not. (Ty = {})",
774                         type_map.get_unique_type_id_as_string(unique_type_id),
775                         t
776                     );
777                 }
778             };
779
780             match type_map.find_metadata_for_type(t) {
781                 Some(metadata) => {
782                     if metadata != metadata_for_uid {
783                         span_bug!(
784                             usage_site_span,
785                             "mismatch between `Ty` and \
786                                    `UniqueTypeId` maps in \
787                                    `debuginfo::TypeMap`. \
788                                    UniqueTypeId={}, Ty={}",
789                             type_map.get_unique_type_id_as_string(unique_type_id),
790                             t
791                         );
792                     }
793                 }
794                 None => {
795                     type_map.register_type_with_metadata(t, metadata);
796                 }
797             }
798         } else {
799             type_map.register_type_with_metadata(t, metadata);
800             type_map.register_unique_id_with_metadata(unique_type_id, metadata);
801         }
802     }
803
804     metadata
805 }
806
807 fn hex_encode(data: &[u8]) -> String {
808     let mut hex_string = String::with_capacity(data.len() * 2);
809     for byte in data.iter() {
810         write!(&mut hex_string, "{:02x}", byte).unwrap();
811     }
812     hex_string
813 }
814
815 pub fn file_metadata(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
816     debug!("file_metadata: file_name: {:?}", source_file.name);
817
818     let hash = Some(&source_file.src_hash);
819     let file_name = Some(source_file.name.prefer_remapped().to_string());
820     let directory = if source_file.is_real_file() && !source_file.is_imported() {
821         Some(
822             cx.sess()
823                 .opts
824                 .working_dir
825                 .to_string_lossy(FileNameDisplayPreference::Remapped)
826                 .to_string(),
827         )
828     } else {
829         // If the path comes from an upstream crate we assume it has been made
830         // independent of the compiler's working directory one way or another.
831         None
832     };
833     file_metadata_raw(cx, file_name, directory, hash)
834 }
835
836 pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
837     file_metadata_raw(cx, None, None, None)
838 }
839
840 fn file_metadata_raw(
841     cx: &CodegenCx<'ll, '_>,
842     file_name: Option<String>,
843     directory: Option<String>,
844     hash: Option<&SourceFileHash>,
845 ) -> &'ll DIFile {
846     let key = (file_name, directory);
847
848     match debug_context(cx).created_files.borrow_mut().entry(key) {
849         Entry::Occupied(o) => o.get(),
850         Entry::Vacant(v) => {
851             let (file_name, directory) = v.key();
852             debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
853
854             let file_name = file_name.as_deref().unwrap_or("<unknown>");
855             let directory = directory.as_deref().unwrap_or("");
856
857             let (hash_kind, hash_value) = match hash {
858                 Some(hash) => {
859                     let kind = match hash.kind {
860                         rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
861                         rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
862                         rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
863                     };
864                     (kind, hex_encode(hash.hash_bytes()))
865                 }
866                 None => (llvm::ChecksumKind::None, String::new()),
867             };
868
869             let file_metadata = unsafe {
870                 llvm::LLVMRustDIBuilderCreateFile(
871                     DIB(cx),
872                     file_name.as_ptr().cast(),
873                     file_name.len(),
874                     directory.as_ptr().cast(),
875                     directory.len(),
876                     hash_kind,
877                     hash_value.as_ptr().cast(),
878                     hash_value.len(),
879                 )
880             };
881
882             v.insert(file_metadata);
883             file_metadata
884         }
885     }
886 }
887
888 trait MsvcBasicName {
889     fn msvc_basic_name(self) -> &'static str;
890 }
891
892 impl MsvcBasicName for ty::IntTy {
893     fn msvc_basic_name(self) -> &'static str {
894         match self {
895             ty::IntTy::Isize => "ptrdiff_t",
896             ty::IntTy::I8 => "__int8",
897             ty::IntTy::I16 => "__int16",
898             ty::IntTy::I32 => "__int32",
899             ty::IntTy::I64 => "__int64",
900             ty::IntTy::I128 => "__int128",
901         }
902     }
903 }
904
905 impl MsvcBasicName for ty::UintTy {
906     fn msvc_basic_name(self) -> &'static str {
907         match self {
908             ty::UintTy::Usize => "size_t",
909             ty::UintTy::U8 => "unsigned __int8",
910             ty::UintTy::U16 => "unsigned __int16",
911             ty::UintTy::U32 => "unsigned __int32",
912             ty::UintTy::U64 => "unsigned __int64",
913             ty::UintTy::U128 => "unsigned __int128",
914         }
915     }
916 }
917
918 impl MsvcBasicName for ty::FloatTy {
919     fn msvc_basic_name(self) -> &'static str {
920         match self {
921             ty::FloatTy::F32 => "float",
922             ty::FloatTy::F64 => "double",
923         }
924     }
925 }
926
927 fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
928     debug!("basic_type_metadata: {:?}", t);
929
930     // When targeting MSVC, emit MSVC style type names for compatibility with
931     // .natvis visualizers (and perhaps other existing native debuggers?)
932     let msvc_like_names = cx.tcx.sess.target.is_like_msvc;
933
934     let (name, encoding) = match t.kind() {
935         ty::Never => ("!", DW_ATE_unsigned),
936         ty::Tuple(elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
937         ty::Bool => ("bool", DW_ATE_boolean),
938         ty::Char => ("char", DW_ATE_unsigned_char),
939         ty::Int(int_ty) if msvc_like_names => (int_ty.msvc_basic_name(), DW_ATE_signed),
940         ty::Uint(uint_ty) if msvc_like_names => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
941         ty::Float(float_ty) if msvc_like_names => (float_ty.msvc_basic_name(), DW_ATE_float),
942         ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
943         ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
944         ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
945         _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
946     };
947
948     let ty_metadata = unsafe {
949         llvm::LLVMRustDIBuilderCreateBasicType(
950             DIB(cx),
951             name.as_ptr().cast(),
952             name.len(),
953             cx.size_of(t).bits(),
954             encoding,
955         )
956     };
957
958     if !msvc_like_names {
959         return ty_metadata;
960     }
961
962     let typedef_name = match t.kind() {
963         ty::Int(int_ty) => int_ty.name_str(),
964         ty::Uint(uint_ty) => uint_ty.name_str(),
965         ty::Float(float_ty) => float_ty.name_str(),
966         _ => return ty_metadata,
967     };
968
969     let typedef_metadata = unsafe {
970         llvm::LLVMRustDIBuilderCreateTypedef(
971             DIB(cx),
972             ty_metadata,
973             typedef_name.as_ptr().cast(),
974             typedef_name.len(),
975             unknown_file_metadata(cx),
976             0,
977             None,
978         )
979     };
980
981     typedef_metadata
982 }
983
984 fn foreign_type_metadata(
985     cx: &CodegenCx<'ll, 'tcx>,
986     t: Ty<'tcx>,
987     unique_type_id: UniqueTypeId,
988 ) -> &'ll DIType {
989     debug!("foreign_type_metadata: {:?}", t);
990
991     let name = compute_debuginfo_type_name(cx.tcx, t, false);
992     create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA, DIFlags::FlagZero)
993 }
994
995 fn pointer_type_metadata(
996     cx: &CodegenCx<'ll, 'tcx>,
997     pointer_type: Ty<'tcx>,
998     pointee_type_metadata: &'ll DIType,
999 ) -> &'ll DIType {
1000     let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
1001     let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
1002     unsafe {
1003         llvm::LLVMRustDIBuilderCreatePointerType(
1004             DIB(cx),
1005             pointee_type_metadata,
1006             pointer_size.bits(),
1007             pointer_align.bits() as u32,
1008             0, // Ignore DWARF address space.
1009             name.as_ptr().cast(),
1010             name.len(),
1011         )
1012     }
1013 }
1014
1015 fn param_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
1016     debug!("param_type_metadata: {:?}", t);
1017     let name = format!("{:?}", t);
1018     unsafe {
1019         llvm::LLVMRustDIBuilderCreateBasicType(
1020             DIB(cx),
1021             name.as_ptr().cast(),
1022             name.len(),
1023             Size::ZERO.bits(),
1024             DW_ATE_unsigned,
1025         )
1026     }
1027 }
1028
1029 pub fn compile_unit_metadata(
1030     tcx: TyCtxt<'_>,
1031     codegen_unit_name: &str,
1032     debug_context: &CrateDebugContext<'ll, '_>,
1033 ) -> &'ll DIDescriptor {
1034     let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
1035         Some(ref path) => path.clone(),
1036         None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
1037     };
1038
1039     // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
1040     // if multiple object files with the same `DW_AT_name` are linked together.
1041     // As a workaround we generate unique names for each object file. Those do
1042     // not correspond to an actual source file but that is harmless.
1043     if tcx.sess.target.is_like_osx {
1044         name_in_debuginfo.push("@");
1045         name_in_debuginfo.push(codegen_unit_name);
1046     }
1047
1048     debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
1049     let rustc_producer =
1050         format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
1051     // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
1052     let producer = format!("clang LLVM ({})", rustc_producer);
1053
1054     let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1055     let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
1056     let flags = "\0";
1057     let output_filenames = tcx.output_filenames(());
1058     let out_dir = &output_filenames.out_directory;
1059     let split_name = if tcx.sess.target_can_use_split_dwarf() {
1060         output_filenames
1061             .split_dwarf_path(tcx.sess.split_debuginfo(), Some(codegen_unit_name))
1062             .map(|f| out_dir.join(f))
1063     } else {
1064         None
1065     }
1066     .unwrap_or_default();
1067     let split_name = split_name.to_str().unwrap();
1068
1069     // FIXME(#60020):
1070     //
1071     //    This should actually be
1072     //
1073     //        let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1074     //
1075     //    That is, we should set LLVM's emission kind to `LineTablesOnly` if
1076     //    we are compiling with "limited" debuginfo. However, some of the
1077     //    existing tools relied on slightly more debuginfo being generated than
1078     //    would be the case with `LineTablesOnly`, and we did not want to break
1079     //    these tools in a "drive-by fix", without a good idea or plan about
1080     //    what limited debuginfo should exactly look like. So for now we keep
1081     //    the emission kind as `FullDebug`.
1082     //
1083     //    See https://github.com/rust-lang/rust/issues/60020 for details.
1084     let kind = DebugEmissionKind::FullDebug;
1085     assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1086
1087     unsafe {
1088         let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
1089             debug_context.builder,
1090             name_in_debuginfo.as_ptr().cast(),
1091             name_in_debuginfo.len(),
1092             work_dir.as_ptr().cast(),
1093             work_dir.len(),
1094             llvm::ChecksumKind::None,
1095             ptr::null(),
1096             0,
1097         );
1098
1099         let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1100             debug_context.builder,
1101             DW_LANG_RUST,
1102             compile_unit_file,
1103             producer.as_ptr().cast(),
1104             producer.len(),
1105             tcx.sess.opts.optimize != config::OptLevel::No,
1106             flags.as_ptr().cast(),
1107             0,
1108             // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1109             // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1110             // output(s).
1111             split_name.as_ptr().cast(),
1112             split_name.len(),
1113             kind,
1114             0,
1115             tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1116         );
1117
1118         if tcx.sess.opts.debugging_opts.profile {
1119             let cu_desc_metadata =
1120                 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1121             let default_gcda_path = &output_filenames.with_extension("gcda");
1122             let gcda_path =
1123                 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1124
1125             let gcov_cu_info = [
1126                 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1127                 path_to_mdstring(debug_context.llcontext, gcda_path),
1128                 cu_desc_metadata,
1129             ];
1130             let gcov_metadata = llvm::LLVMMDNodeInContext(
1131                 debug_context.llcontext,
1132                 gcov_cu_info.as_ptr(),
1133                 gcov_cu_info.len() as c_uint,
1134             );
1135
1136             let llvm_gcov_ident = cstr!("llvm.gcov");
1137             llvm::LLVMAddNamedMetadataOperand(
1138                 debug_context.llmod,
1139                 llvm_gcov_ident.as_ptr(),
1140                 gcov_metadata,
1141             );
1142         }
1143
1144         // Insert `llvm.ident` metadata on the wasm targets since that will
1145         // get hooked up to the "producer" sections `processed-by` information.
1146         if tcx.sess.target.is_like_wasm {
1147             let name_metadata = llvm::LLVMMDStringInContext(
1148                 debug_context.llcontext,
1149                 rustc_producer.as_ptr().cast(),
1150                 rustc_producer.as_bytes().len() as c_uint,
1151             );
1152             llvm::LLVMAddNamedMetadataOperand(
1153                 debug_context.llmod,
1154                 cstr!("llvm.ident").as_ptr(),
1155                 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1156             );
1157         }
1158
1159         return unit_metadata;
1160     };
1161
1162     fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1163         let path_str = path_to_c_string(path);
1164         unsafe {
1165             llvm::LLVMMDStringInContext(
1166                 llcx,
1167                 path_str.as_ptr(),
1168                 path_str.as_bytes().len() as c_uint,
1169             )
1170         }
1171     }
1172 }
1173
1174 struct MetadataCreationResult<'ll> {
1175     metadata: &'ll DIType,
1176     already_stored_in_typemap: bool,
1177 }
1178
1179 impl MetadataCreationResult<'ll> {
1180     fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1181         MetadataCreationResult { metadata, already_stored_in_typemap }
1182     }
1183 }
1184
1185 #[derive(Debug)]
1186 struct SourceInfo<'ll> {
1187     file: &'ll DIFile,
1188     line: u32,
1189 }
1190
1191 /// Description of a type member, which can either be a regular field (as in
1192 /// structs or tuples) or an enum variant.
1193 #[derive(Debug)]
1194 struct MemberDescription<'ll> {
1195     name: String,
1196     type_metadata: &'ll DIType,
1197     offset: Size,
1198     size: Size,
1199     align: Align,
1200     flags: DIFlags,
1201     discriminant: Option<u64>,
1202     source_info: Option<SourceInfo<'ll>>,
1203 }
1204
1205 impl<'ll> MemberDescription<'ll> {
1206     fn into_metadata(
1207         self,
1208         cx: &CodegenCx<'ll, '_>,
1209         composite_type_metadata: &'ll DIScope,
1210     ) -> &'ll DIType {
1211         let (file, line) = self
1212             .source_info
1213             .map(|info| (info.file, info.line))
1214             .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1215         unsafe {
1216             llvm::LLVMRustDIBuilderCreateVariantMemberType(
1217                 DIB(cx),
1218                 composite_type_metadata,
1219                 self.name.as_ptr().cast(),
1220                 self.name.len(),
1221                 file,
1222                 line,
1223                 self.size.bits(),
1224                 self.align.bits() as u32,
1225                 self.offset.bits(),
1226                 self.discriminant.map(|v| cx.const_u64(v)),
1227                 self.flags,
1228                 self.type_metadata,
1229             )
1230         }
1231     }
1232 }
1233
1234 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1235 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1236 /// creation of type member descriptions in order to break cycles arising from
1237 /// recursive type definitions.
1238 enum MemberDescriptionFactory<'ll, 'tcx> {
1239     StructMDF(StructMemberDescriptionFactory<'tcx>),
1240     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1241     EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1242     UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1243     VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1244 }
1245
1246 impl MemberDescriptionFactory<'ll, 'tcx> {
1247     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1248         match *self {
1249             StructMDF(ref this) => this.create_member_descriptions(cx),
1250             TupleMDF(ref this) => this.create_member_descriptions(cx),
1251             EnumMDF(ref this) => this.create_member_descriptions(cx),
1252             UnionMDF(ref this) => this.create_member_descriptions(cx),
1253             VariantMDF(ref this) => this.create_member_descriptions(cx),
1254         }
1255     }
1256 }
1257
1258 //=-----------------------------------------------------------------------------
1259 // Structs
1260 //=-----------------------------------------------------------------------------
1261
1262 /// Creates `MemberDescription`s for the fields of a struct.
1263 struct StructMemberDescriptionFactory<'tcx> {
1264     ty: Ty<'tcx>,
1265     variant: &'tcx ty::VariantDef,
1266     span: Span,
1267 }
1268
1269 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1270     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1271         let layout = cx.layout_of(self.ty);
1272         self.variant
1273             .fields
1274             .iter()
1275             .enumerate()
1276             .map(|(i, f)| {
1277                 let name = if self.variant.ctor_kind == CtorKind::Fn {
1278                     format!("__{}", i)
1279                 } else {
1280                     f.ident.to_string()
1281                 };
1282                 let field = layout.field(cx, i);
1283                 MemberDescription {
1284                     name,
1285                     type_metadata: type_metadata(cx, field.ty, self.span),
1286                     offset: layout.fields.offset(i),
1287                     size: field.size,
1288                     align: field.align.abi,
1289                     flags: DIFlags::FlagZero,
1290                     discriminant: None,
1291                     source_info: None,
1292                 }
1293             })
1294             .collect()
1295     }
1296 }
1297
1298 fn prepare_struct_metadata(
1299     cx: &CodegenCx<'ll, 'tcx>,
1300     struct_type: Ty<'tcx>,
1301     unique_type_id: UniqueTypeId,
1302     span: Span,
1303 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1304     let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1305
1306     let (struct_def_id, variant) = match struct_type.kind() {
1307         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1308         _ => bug!("prepare_struct_metadata on a non-ADT"),
1309     };
1310
1311     let containing_scope = get_namespace_for_item(cx, struct_def_id);
1312
1313     let struct_metadata_stub = create_struct_stub(
1314         cx,
1315         struct_type,
1316         &struct_name,
1317         unique_type_id,
1318         Some(containing_scope),
1319         DIFlags::FlagZero,
1320     );
1321
1322     create_and_register_recursive_type_forward_declaration(
1323         cx,
1324         struct_type,
1325         unique_type_id,
1326         struct_metadata_stub,
1327         struct_metadata_stub,
1328         StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant, span }),
1329     )
1330 }
1331
1332 //=-----------------------------------------------------------------------------
1333 // Tuples
1334 //=-----------------------------------------------------------------------------
1335
1336 /// Returns names of captured upvars for closures and generators.
1337 ///
1338 /// Here are some examples:
1339 ///  - `name__field1__field2` when the upvar is captured by value.
1340 ///  - `_ref__name__field` when the upvar is captured by reference.
1341 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'tcx>, def_id: DefId) -> Vec<String> {
1342     let body = tcx.optimized_mir(def_id);
1343
1344     body.var_debug_info
1345         .iter()
1346         .filter_map(|var| {
1347             let is_ref = match var.value {
1348                 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1349                     // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1350                     // implies whether the variable is captured by value or by reference.
1351                     matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1352                 }
1353                 _ => return None,
1354             };
1355             let prefix = if is_ref { "_ref__" } else { "" };
1356             Some(prefix.to_owned() + &var.name.as_str())
1357         })
1358         .collect::<Vec<_>>()
1359 }
1360
1361 /// Creates `MemberDescription`s for the fields of a tuple.
1362 struct TupleMemberDescriptionFactory<'tcx> {
1363     ty: Ty<'tcx>,
1364     component_types: Vec<Ty<'tcx>>,
1365     span: Span,
1366 }
1367
1368 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1369     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1370         let mut capture_names = match *self.ty.kind() {
1371             ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1372                 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1373             }
1374             _ => None,
1375         };
1376         let layout = cx.layout_of(self.ty);
1377         self.component_types
1378             .iter()
1379             .enumerate()
1380             .map(|(i, &component_type)| {
1381                 let (size, align) = cx.size_and_align_of(component_type);
1382                 let name = if let Some(names) = capture_names.as_mut() {
1383                     names.next().unwrap()
1384                 } else {
1385                     format!("__{}", i)
1386                 };
1387                 MemberDescription {
1388                     name,
1389                     type_metadata: type_metadata(cx, component_type, self.span),
1390                     offset: layout.fields.offset(i),
1391                     size,
1392                     align,
1393                     flags: DIFlags::FlagZero,
1394                     discriminant: None,
1395                     source_info: None,
1396                 }
1397             })
1398             .collect()
1399     }
1400 }
1401
1402 fn prepare_tuple_metadata(
1403     cx: &CodegenCx<'ll, 'tcx>,
1404     tuple_type: Ty<'tcx>,
1405     component_types: &[Ty<'tcx>],
1406     unique_type_id: UniqueTypeId,
1407     span: Span,
1408     containing_scope: Option<&'ll DIScope>,
1409 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1410     let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1411
1412     let struct_stub = create_struct_stub(
1413         cx,
1414         tuple_type,
1415         &tuple_name[..],
1416         unique_type_id,
1417         containing_scope,
1418         DIFlags::FlagZero,
1419     );
1420
1421     create_and_register_recursive_type_forward_declaration(
1422         cx,
1423         tuple_type,
1424         unique_type_id,
1425         struct_stub,
1426         struct_stub,
1427         TupleMDF(TupleMemberDescriptionFactory {
1428             ty: tuple_type,
1429             component_types: component_types.to_vec(),
1430             span,
1431         }),
1432     )
1433 }
1434
1435 //=-----------------------------------------------------------------------------
1436 // Unions
1437 //=-----------------------------------------------------------------------------
1438
1439 struct UnionMemberDescriptionFactory<'tcx> {
1440     layout: TyAndLayout<'tcx>,
1441     variant: &'tcx ty::VariantDef,
1442     span: Span,
1443 }
1444
1445 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1446     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1447         self.variant
1448             .fields
1449             .iter()
1450             .enumerate()
1451             .map(|(i, f)| {
1452                 let field = self.layout.field(cx, i);
1453                 MemberDescription {
1454                     name: f.ident.to_string(),
1455                     type_metadata: type_metadata(cx, field.ty, self.span),
1456                     offset: Size::ZERO,
1457                     size: field.size,
1458                     align: field.align.abi,
1459                     flags: DIFlags::FlagZero,
1460                     discriminant: None,
1461                     source_info: None,
1462                 }
1463             })
1464             .collect()
1465     }
1466 }
1467
1468 fn prepare_union_metadata(
1469     cx: &CodegenCx<'ll, 'tcx>,
1470     union_type: Ty<'tcx>,
1471     unique_type_id: UniqueTypeId,
1472     span: Span,
1473 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1474     let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1475
1476     let (union_def_id, variant) = match union_type.kind() {
1477         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1478         _ => bug!("prepare_union_metadata on a non-ADT"),
1479     };
1480
1481     let containing_scope = get_namespace_for_item(cx, union_def_id);
1482
1483     let union_metadata_stub =
1484         create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1485
1486     create_and_register_recursive_type_forward_declaration(
1487         cx,
1488         union_type,
1489         unique_type_id,
1490         union_metadata_stub,
1491         union_metadata_stub,
1492         UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant, span }),
1493     )
1494 }
1495
1496 //=-----------------------------------------------------------------------------
1497 // Enums
1498 //=-----------------------------------------------------------------------------
1499
1500 /// DWARF variant support is only available starting in LLVM 8, but
1501 /// on MSVC we have to use the fallback mode, because LLVM doesn't
1502 /// lower variant parts to PDB.
1503 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1504     cx.sess().target.is_like_msvc
1505 }
1506
1507 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1508 // per generator monomorphization, but it doesn't depend on substs.
1509 fn generator_layout_and_saved_local_names(
1510     tcx: TyCtxt<'tcx>,
1511     def_id: DefId,
1512 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1513     let body = tcx.optimized_mir(def_id);
1514     let generator_layout = body.generator_layout().unwrap();
1515     let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1516
1517     let state_arg = mir::Local::new(1);
1518     for var in &body.var_debug_info {
1519         let place = if let mir::VarDebugInfoContents::Place(p) = var.value { p } else { continue };
1520         if place.local != state_arg {
1521             continue;
1522         }
1523         match place.projection[..] {
1524             [
1525                 // Deref of the `Pin<&mut Self>` state argument.
1526                 mir::ProjectionElem::Field(..),
1527                 mir::ProjectionElem::Deref,
1528                 // Field of a variant of the state.
1529                 mir::ProjectionElem::Downcast(_, variant),
1530                 mir::ProjectionElem::Field(field, _),
1531             ] => {
1532                 let name = &mut generator_saved_local_names
1533                     [generator_layout.variant_fields[variant][field]];
1534                 if name.is_none() {
1535                     name.replace(var.name);
1536                 }
1537             }
1538             _ => {}
1539         }
1540     }
1541     (generator_layout, generator_saved_local_names)
1542 }
1543
1544 /// Describes the members of an enum value; an enum is described as a union of
1545 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1546 /// the members of this union; so for every variant of the given enum, this
1547 /// factory will produce one `MemberDescription` (all with no name and a fixed
1548 /// offset of zero bytes).
1549 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1550     enum_type: Ty<'tcx>,
1551     layout: TyAndLayout<'tcx>,
1552     tag_type_metadata: Option<&'ll DIType>,
1553     common_members: Vec<Option<&'ll DIType>>,
1554     span: Span,
1555 }
1556
1557 impl EnumMemberDescriptionFactory<'ll, 'tcx> {
1558     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1559         let generator_variant_info_data = match *self.enum_type.kind() {
1560             ty::Generator(def_id, ..) => {
1561                 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1562             }
1563             _ => None,
1564         };
1565
1566         let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1567             ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1568             ty::Generator(def_id, _, _) => {
1569                 let (generator_layout, generator_saved_local_names) =
1570                     generator_variant_info_data.as_ref().unwrap();
1571                 VariantInfo::Generator {
1572                     def_id,
1573                     generator_layout: *generator_layout,
1574                     generator_saved_local_names,
1575                     variant_index: index,
1576                 }
1577             }
1578             _ => bug!(),
1579         };
1580
1581         let fallback = use_enum_fallback(cx);
1582         // This will always find the metadata in the type map.
1583         let self_metadata = type_metadata(cx, self.enum_type, self.span);
1584
1585         match self.layout.variants {
1586             Variants::Single { index } => {
1587                 if let ty::Adt(adt, _) = self.enum_type.kind() {
1588                     if adt.variants.is_empty() {
1589                         return vec![];
1590                     }
1591                 }
1592
1593                 let variant_info = variant_info_for(index);
1594                 let (variant_type_metadata, member_description_factory) =
1595                     describe_enum_variant(cx, self.layout, variant_info, self_metadata, self.span);
1596
1597                 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1598
1599                 set_members_of_composite_type(
1600                     cx,
1601                     self.enum_type,
1602                     variant_type_metadata,
1603                     member_descriptions,
1604                     Some(&self.common_members),
1605                 );
1606                 vec![MemberDescription {
1607                     name: variant_info.variant_name(),
1608                     type_metadata: variant_type_metadata,
1609                     offset: Size::ZERO,
1610                     size: self.layout.size,
1611                     align: self.layout.align.abi,
1612                     flags: DIFlags::FlagZero,
1613                     discriminant: None,
1614                     source_info: variant_info.source_info(cx),
1615                 }]
1616             }
1617             Variants::Multiple {
1618                 tag_encoding: TagEncoding::Direct,
1619                 tag_field,
1620                 ref variants,
1621                 ..
1622             } => {
1623                 let fallback_discr_variant = if fallback {
1624                     // For MSVC, we generate a union of structs for each variant and an
1625                     // explicit discriminant field roughly equivalent to the following C:
1626                     // ```c
1627                     // union enum$<{name}> {
1628                     //   struct {variant 0 name} {
1629                     //     <variant 0 fields>
1630                     //   } variant0;
1631                     //   <other variant structs>
1632                     //   {name} discriminant;
1633                     // }
1634                     // ```
1635                     // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1636                     // determine which variant is active and then displays it.
1637                     let enum_layout = self.layout;
1638                     let offset = enum_layout.fields.offset(tag_field);
1639                     let discr_ty = enum_layout.field(cx, tag_field).ty;
1640                     let (size, align) = cx.size_and_align_of(discr_ty);
1641                     Some(MemberDescription {
1642                         name: "discriminant".into(),
1643                         type_metadata: self.tag_type_metadata.unwrap(),
1644                         offset,
1645                         size,
1646                         align,
1647                         flags: DIFlags::FlagZero,
1648                         discriminant: None,
1649                         source_info: None,
1650                     })
1651                 } else {
1652                     None
1653                 };
1654
1655                 variants
1656                     .iter_enumerated()
1657                     .map(|(i, _)| {
1658                         let variant = self.layout.for_variant(cx, i);
1659                         let variant_info = variant_info_for(i);
1660                         let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1661                             cx,
1662                             variant,
1663                             variant_info,
1664                             self_metadata,
1665                             self.span,
1666                         );
1667
1668                         let member_descriptions =
1669                             member_desc_factory.create_member_descriptions(cx);
1670
1671                         set_members_of_composite_type(
1672                             cx,
1673                             self.enum_type,
1674                             variant_type_metadata,
1675                             member_descriptions,
1676                             Some(&self.common_members),
1677                         );
1678
1679                         MemberDescription {
1680                             name: if fallback {
1681                                 format!("variant{}", i.as_u32())
1682                             } else {
1683                                 variant_info.variant_name()
1684                             },
1685                             type_metadata: variant_type_metadata,
1686                             offset: Size::ZERO,
1687                             size: self.layout.size,
1688                             align: self.layout.align.abi,
1689                             flags: DIFlags::FlagZero,
1690                             discriminant: Some(
1691                                 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1692                                     as u64,
1693                             ),
1694                             source_info: variant_info.source_info(cx),
1695                         }
1696                     })
1697                     .chain(fallback_discr_variant.into_iter())
1698                     .collect()
1699             }
1700             Variants::Multiple {
1701                 tag_encoding:
1702                     TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1703                 tag,
1704                 ref variants,
1705                 tag_field,
1706             } => {
1707                 let calculate_niche_value = |i: VariantIdx| {
1708                     if i == dataful_variant {
1709                         None
1710                     } else {
1711                         let value = (i.as_u32() as u128)
1712                             .wrapping_sub(niche_variants.start().as_u32() as u128)
1713                             .wrapping_add(niche_start);
1714                         let value = tag.value.size(cx).truncate(value);
1715                         // NOTE(eddyb) do *NOT* remove this assert, until
1716                         // we pass the full 128-bit value to LLVM, otherwise
1717                         // truncation will be silent and remain undetected.
1718                         assert_eq!(value as u64 as u128, value);
1719                         Some(value as u64)
1720                     }
1721                 };
1722
1723                 // For MSVC, we will generate a union of two fields, one for the dataful variant
1724                 // and one that just points to the discriminant. We also create an enum that
1725                 // contains tag values for the non-dataful variants and make the discriminant field
1726                 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1727                 // This will generate debuginfo roughly equivalent to the following C:
1728                 // ```c
1729                 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1730                 //   struct <dataful variant name> {
1731                 //     <fields in dataful variant>
1732                 //   } dataful_variant;
1733                 //   enum Discriminant$ {
1734                 //     <non-dataful variants>
1735                 //   } discriminant;
1736                 // }
1737                 // ```
1738                 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1739                 // and evaluates `this.discriminant`. If the value is between the min niche and max
1740                 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1741                 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1742                 // case, we just need to render the name of the `this.discriminant` enum.
1743                 if fallback {
1744                     let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1745
1746                     let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1747                     // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1748                     // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1749                     // to just be `usize`.
1750                     if let ty::RawPtr(_) = discr_enum_ty.kind() {
1751                         discr_enum_ty = cx.tcx.types.usize;
1752                     }
1753
1754                     let tags: Vec<_> = variants
1755                         .iter_enumerated()
1756                         .filter_map(|(variant_idx, _)| {
1757                             calculate_niche_value(variant_idx).map(|tag| {
1758                                 let variant = variant_info_for(variant_idx);
1759                                 let name = variant.variant_name();
1760
1761                                 Some(unsafe {
1762                                     llvm::LLVMRustDIBuilderCreateEnumerator(
1763                                         DIB(cx),
1764                                         name.as_ptr().cast(),
1765                                         name.len(),
1766                                         tag as i64,
1767                                         !discr_enum_ty.is_signed(),
1768                                     )
1769                                 })
1770                             })
1771                         })
1772                         .collect();
1773
1774                     let discr_enum = unsafe {
1775                         llvm::LLVMRustDIBuilderCreateEnumerationType(
1776                             DIB(cx),
1777                             self_metadata,
1778                             "Discriminant$".as_ptr().cast(),
1779                             "Discriminant$".len(),
1780                             unknown_file_metadata(cx),
1781                             UNKNOWN_LINE_NUMBER,
1782                             tag.value.size(cx).bits(),
1783                             tag.value.align(cx).abi.bits() as u32,
1784                             create_DIArray(DIB(cx), &tags),
1785                             type_metadata(cx, discr_enum_ty, self.span),
1786                             true,
1787                         )
1788                     };
1789
1790                     let variant_info = variant_info_for(dataful_variant);
1791                     let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1792                         cx,
1793                         dataful_variant_layout,
1794                         variant_info,
1795                         self_metadata,
1796                         self.span,
1797                     );
1798
1799                     let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1800
1801                     set_members_of_composite_type(
1802                         cx,
1803                         self.enum_type,
1804                         variant_type_metadata,
1805                         member_descriptions,
1806                         Some(&self.common_members),
1807                     );
1808
1809                     let (size, align) =
1810                         cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1811
1812                     vec![
1813                         MemberDescription {
1814                             // Name the dataful variant so that we can identify it for natvis
1815                             name: "dataful_variant".to_string(),
1816                             type_metadata: variant_type_metadata,
1817                             offset: Size::ZERO,
1818                             size: self.layout.size,
1819                             align: self.layout.align.abi,
1820                             flags: DIFlags::FlagZero,
1821                             discriminant: None,
1822                             source_info: variant_info.source_info(cx),
1823                         },
1824                         MemberDescription {
1825                             name: "discriminant".into(),
1826                             type_metadata: discr_enum,
1827                             offset: dataful_variant_layout.fields.offset(tag_field),
1828                             size,
1829                             align,
1830                             flags: DIFlags::FlagZero,
1831                             discriminant: None,
1832                             source_info: None,
1833                         },
1834                     ]
1835                 } else {
1836                     variants
1837                         .iter_enumerated()
1838                         .map(|(i, _)| {
1839                             let variant = self.layout.for_variant(cx, i);
1840                             let variant_info = variant_info_for(i);
1841                             let (variant_type_metadata, member_desc_factory) =
1842                                 describe_enum_variant(
1843                                     cx,
1844                                     variant,
1845                                     variant_info,
1846                                     self_metadata,
1847                                     self.span,
1848                                 );
1849
1850                             let member_descriptions =
1851                                 member_desc_factory.create_member_descriptions(cx);
1852
1853                             set_members_of_composite_type(
1854                                 cx,
1855                                 self.enum_type,
1856                                 variant_type_metadata,
1857                                 member_descriptions,
1858                                 Some(&self.common_members),
1859                             );
1860
1861                             let niche_value = calculate_niche_value(i);
1862
1863                             MemberDescription {
1864                                 name: variant_info.variant_name(),
1865                                 type_metadata: variant_type_metadata,
1866                                 offset: Size::ZERO,
1867                                 size: self.layout.size,
1868                                 align: self.layout.align.abi,
1869                                 flags: DIFlags::FlagZero,
1870                                 discriminant: niche_value,
1871                                 source_info: variant_info.source_info(cx),
1872                             }
1873                         })
1874                         .collect()
1875                 }
1876             }
1877         }
1878     }
1879 }
1880
1881 // Creates `MemberDescription`s for the fields of a single enum variant.
1882 struct VariantMemberDescriptionFactory<'tcx> {
1883     /// Cloned from the `layout::Struct` describing the variant.
1884     offsets: Vec<Size>,
1885     args: Vec<(String, Ty<'tcx>)>,
1886     span: Span,
1887 }
1888
1889 impl VariantMemberDescriptionFactory<'tcx> {
1890     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1891         self.args
1892             .iter()
1893             .enumerate()
1894             .map(|(i, &(ref name, ty))| {
1895                 let (size, align) = cx.size_and_align_of(ty);
1896                 MemberDescription {
1897                     name: name.to_string(),
1898                     type_metadata: type_metadata(cx, ty, self.span),
1899                     offset: self.offsets[i],
1900                     size,
1901                     align,
1902                     flags: DIFlags::FlagZero,
1903                     discriminant: None,
1904                     source_info: None,
1905                 }
1906             })
1907             .collect()
1908     }
1909 }
1910
1911 #[derive(Copy, Clone)]
1912 enum VariantInfo<'a, 'tcx> {
1913     Adt(&'tcx ty::VariantDef),
1914     Generator {
1915         def_id: DefId,
1916         generator_layout: &'tcx GeneratorLayout<'tcx>,
1917         generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1918         variant_index: VariantIdx,
1919     },
1920 }
1921
1922 impl<'tcx> VariantInfo<'_, 'tcx> {
1923     fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1924         match self {
1925             VariantInfo::Adt(variant) => f(&variant.ident.as_str()),
1926             VariantInfo::Generator { variant_index, .. } => {
1927                 f(&GeneratorSubsts::variant_name(*variant_index))
1928             }
1929         }
1930     }
1931
1932     fn variant_name(&self) -> String {
1933         match self {
1934             VariantInfo::Adt(variant) => variant.ident.to_string(),
1935             VariantInfo::Generator { variant_index, .. } => {
1936                 // Since GDB currently prints out the raw discriminant along
1937                 // with every variant, make each variant name be just the value
1938                 // of the discriminant. The struct name for the variant includes
1939                 // the actual variant description.
1940                 format!("{}", variant_index.as_usize())
1941             }
1942         }
1943     }
1944
1945     fn field_name(&self, i: usize) -> String {
1946         let field_name = match *self {
1947             VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1948                 Some(variant.fields[i].ident.name)
1949             }
1950             VariantInfo::Generator {
1951                 generator_layout,
1952                 generator_saved_local_names,
1953                 variant_index,
1954                 ..
1955             } => {
1956                 generator_saved_local_names
1957                     [generator_layout.variant_fields[variant_index][i.into()]]
1958             }
1959             _ => None,
1960         };
1961         field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1962     }
1963
1964     fn source_info(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1965         if let VariantInfo::Generator { def_id, variant_index, .. } = self {
1966             let span =
1967                 cx.tcx.generator_layout(*def_id).unwrap().variant_source_info[*variant_index].span;
1968             if !span.is_dummy() {
1969                 let loc = cx.lookup_debug_loc(span.lo());
1970                 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
1971             }
1972         }
1973         None
1974     }
1975 }
1976
1977 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1978 /// `MemberDescriptionFactory` for producing the descriptions of the
1979 /// fields of the variant. This is a rudimentary version of a full
1980 /// `RecursiveTypeDescription`.
1981 fn describe_enum_variant(
1982     cx: &CodegenCx<'ll, 'tcx>,
1983     layout: layout::TyAndLayout<'tcx>,
1984     variant: VariantInfo<'_, 'tcx>,
1985     containing_scope: &'ll DIScope,
1986     span: Span,
1987 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1988     let metadata_stub = variant.map_struct_name(|variant_name| {
1989         let unique_type_id = debug_context(cx)
1990             .type_map
1991             .borrow_mut()
1992             .get_unique_type_id_of_enum_variant(cx, layout.ty, variant_name);
1993         create_struct_stub(
1994             cx,
1995             layout.ty,
1996             variant_name,
1997             unique_type_id,
1998             Some(containing_scope),
1999             DIFlags::FlagZero,
2000         )
2001     });
2002
2003     let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
2004     let args = (0..layout.fields.count())
2005         .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
2006         .collect();
2007
2008     let member_description_factory =
2009         VariantMDF(VariantMemberDescriptionFactory { offsets, args, span });
2010
2011     (metadata_stub, member_description_factory)
2012 }
2013
2014 fn prepare_enum_metadata(
2015     cx: &CodegenCx<'ll, 'tcx>,
2016     enum_type: Ty<'tcx>,
2017     enum_def_id: DefId,
2018     unique_type_id: UniqueTypeId,
2019     span: Span,
2020     outer_field_tys: Vec<Ty<'tcx>>,
2021 ) -> RecursiveTypeDescription<'ll, 'tcx> {
2022     let tcx = cx.tcx;
2023     let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
2024
2025     let containing_scope = get_namespace_for_item(cx, enum_def_id);
2026     // FIXME: This should emit actual file metadata for the enum, but we
2027     // currently can't get the necessary information when it comes to types
2028     // imported from other crates. Formerly we violated the ODR when performing
2029     // LTO because we emitted debuginfo for the same type with varying file
2030     // metadata, so as a workaround we pretend that the type comes from
2031     // <unknown>
2032     let file_metadata = unknown_file_metadata(cx);
2033
2034     let discriminant_type_metadata = |discr: Primitive| {
2035         let enumerators_metadata: Vec<_> = match enum_type.kind() {
2036             ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
2037                 .map(|((_, discr), v)| {
2038                     let name = v.ident.as_str();
2039                     let is_unsigned = match discr.ty.kind() {
2040                         ty::Int(_) => false,
2041                         ty::Uint(_) => true,
2042                         _ => bug!("non integer discriminant"),
2043                     };
2044                     unsafe {
2045                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2046                             DIB(cx),
2047                             name.as_ptr().cast(),
2048                             name.len(),
2049                             // FIXME: what if enumeration has i128 discriminant?
2050                             discr.val as i64,
2051                             is_unsigned,
2052                         ))
2053                     }
2054                 })
2055                 .collect(),
2056             ty::Generator(_, substs, _) => substs
2057                 .as_generator()
2058                 .variant_range(enum_def_id, tcx)
2059                 .map(|variant_index| {
2060                     debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
2061                     let name = GeneratorSubsts::variant_name(variant_index);
2062                     unsafe {
2063                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2064                             DIB(cx),
2065                             name.as_ptr().cast(),
2066                             name.len(),
2067                             // Generators use u32 as discriminant type, verified above.
2068                             variant_index.as_u32().into(),
2069                             true, // IsUnsigned
2070                         ))
2071                     }
2072                 })
2073                 .collect(),
2074             _ => bug!(),
2075         };
2076
2077         let disr_type_key = (enum_def_id, discr);
2078         let cached_discriminant_type_metadata =
2079             debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2080         match cached_discriminant_type_metadata {
2081             Some(discriminant_type_metadata) => discriminant_type_metadata,
2082             None => {
2083                 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2084                 let discriminant_base_type_metadata =
2085                     type_metadata(cx, discr.to_ty(tcx), rustc_span::DUMMY_SP);
2086
2087                 let item_name;
2088                 let discriminant_name = match enum_type.kind() {
2089                     ty::Adt(..) => {
2090                         item_name = tcx.item_name(enum_def_id).as_str();
2091                         &*item_name
2092                     }
2093                     ty::Generator(..) => enum_name.as_str(),
2094                     _ => bug!(),
2095                 };
2096
2097                 let discriminant_type_metadata = unsafe {
2098                     llvm::LLVMRustDIBuilderCreateEnumerationType(
2099                         DIB(cx),
2100                         containing_scope,
2101                         discriminant_name.as_ptr().cast(),
2102                         discriminant_name.len(),
2103                         file_metadata,
2104                         UNKNOWN_LINE_NUMBER,
2105                         discriminant_size.bits(),
2106                         discriminant_align.abi.bits() as u32,
2107                         create_DIArray(DIB(cx), &enumerators_metadata),
2108                         discriminant_base_type_metadata,
2109                         true,
2110                     )
2111                 };
2112
2113                 debug_context(cx)
2114                     .created_enum_disr_types
2115                     .borrow_mut()
2116                     .insert(disr_type_key, discriminant_type_metadata);
2117
2118                 discriminant_type_metadata
2119             }
2120         }
2121     };
2122
2123     let layout = cx.layout_of(enum_type);
2124
2125     if let (Abi::Scalar(_), Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. }) =
2126         (layout.abi, &layout.variants)
2127     {
2128         return FinalMetadata(discriminant_type_metadata(tag.value));
2129     }
2130
2131     if use_enum_fallback(cx) {
2132         let discriminant_type_metadata = match layout.variants {
2133             Variants::Single { .. } => None,
2134             Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, .. }
2135             | Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. } => {
2136                 Some(discriminant_type_metadata(tag.value))
2137             }
2138         };
2139
2140         let enum_metadata = {
2141             let type_map = debug_context(cx).type_map.borrow();
2142             let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2143
2144             unsafe {
2145                 llvm::LLVMRustDIBuilderCreateUnionType(
2146                     DIB(cx),
2147                     None,
2148                     enum_name.as_ptr().cast(),
2149                     enum_name.len(),
2150                     file_metadata,
2151                     UNKNOWN_LINE_NUMBER,
2152                     layout.size.bits(),
2153                     layout.align.abi.bits() as u32,
2154                     DIFlags::FlagZero,
2155                     None,
2156                     0, // RuntimeLang
2157                     unique_type_id_str.as_ptr().cast(),
2158                     unique_type_id_str.len(),
2159                 )
2160             }
2161         };
2162
2163         return create_and_register_recursive_type_forward_declaration(
2164             cx,
2165             enum_type,
2166             unique_type_id,
2167             enum_metadata,
2168             enum_metadata,
2169             EnumMDF(EnumMemberDescriptionFactory {
2170                 enum_type,
2171                 layout,
2172                 tag_type_metadata: discriminant_type_metadata,
2173                 common_members: vec![],
2174                 span,
2175             }),
2176         );
2177     }
2178
2179     let discriminator_name = match enum_type.kind() {
2180         ty::Generator(..) => "__state",
2181         _ => "",
2182     };
2183     let discriminator_metadata = match layout.variants {
2184         // A single-variant enum has no discriminant.
2185         Variants::Single { .. } => None,
2186
2187         Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, tag_field, .. } => {
2188             // Find the integer type of the correct size.
2189             let size = tag.value.size(cx);
2190             let align = tag.value.align(cx);
2191
2192             let tag_type = match tag.value {
2193                 Int(t, _) => t,
2194                 F32 => Integer::I32,
2195                 F64 => Integer::I64,
2196                 Pointer => cx.data_layout().ptr_sized_integer(),
2197             }
2198             .to_ty(cx.tcx, false);
2199
2200             let tag_metadata = basic_type_metadata(cx, tag_type);
2201             unsafe {
2202                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2203                     DIB(cx),
2204                     containing_scope,
2205                     discriminator_name.as_ptr().cast(),
2206                     discriminator_name.len(),
2207                     file_metadata,
2208                     UNKNOWN_LINE_NUMBER,
2209                     size.bits(),
2210                     align.abi.bits() as u32,
2211                     layout.fields.offset(tag_field).bits(),
2212                     DIFlags::FlagArtificial,
2213                     tag_metadata,
2214                 ))
2215             }
2216         }
2217
2218         Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, tag_field, .. } => {
2219             let discr_type = tag.value.to_ty(cx.tcx);
2220             let (size, align) = cx.size_and_align_of(discr_type);
2221
2222             let discr_metadata = basic_type_metadata(cx, discr_type);
2223             unsafe {
2224                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2225                     DIB(cx),
2226                     containing_scope,
2227                     discriminator_name.as_ptr().cast(),
2228                     discriminator_name.len(),
2229                     file_metadata,
2230                     UNKNOWN_LINE_NUMBER,
2231                     size.bits(),
2232                     align.bits() as u32,
2233                     layout.fields.offset(tag_field).bits(),
2234                     DIFlags::FlagArtificial,
2235                     discr_metadata,
2236                 ))
2237             }
2238         }
2239     };
2240
2241     let outer_fields = match layout.variants {
2242         Variants::Single { .. } => vec![],
2243         Variants::Multiple { .. } => {
2244             let tuple_mdf = TupleMemberDescriptionFactory {
2245                 ty: enum_type,
2246                 component_types: outer_field_tys,
2247                 span,
2248             };
2249             tuple_mdf
2250                 .create_member_descriptions(cx)
2251                 .into_iter()
2252                 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2253                 .collect()
2254         }
2255     };
2256
2257     let variant_part_unique_type_id_str = debug_context(cx)
2258         .type_map
2259         .borrow_mut()
2260         .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2261     let empty_array = create_DIArray(DIB(cx), &[]);
2262     let name = "";
2263     let variant_part = unsafe {
2264         llvm::LLVMRustDIBuilderCreateVariantPart(
2265             DIB(cx),
2266             containing_scope,
2267             name.as_ptr().cast(),
2268             name.len(),
2269             file_metadata,
2270             UNKNOWN_LINE_NUMBER,
2271             layout.size.bits(),
2272             layout.align.abi.bits() as u32,
2273             DIFlags::FlagZero,
2274             discriminator_metadata,
2275             empty_array,
2276             variant_part_unique_type_id_str.as_ptr().cast(),
2277             variant_part_unique_type_id_str.len(),
2278         )
2279     };
2280
2281     let struct_wrapper = {
2282         // The variant part must be wrapped in a struct according to DWARF.
2283         // All fields except the discriminant (including `outer_fields`)
2284         // should be put into structures inside the variant part, which gives
2285         // an equivalent layout but offers us much better integration with
2286         // debuggers.
2287         let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2288
2289         let type_map = debug_context(cx).type_map.borrow();
2290         let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2291
2292         unsafe {
2293             llvm::LLVMRustDIBuilderCreateStructType(
2294                 DIB(cx),
2295                 Some(containing_scope),
2296                 enum_name.as_ptr().cast(),
2297                 enum_name.len(),
2298                 file_metadata,
2299                 UNKNOWN_LINE_NUMBER,
2300                 layout.size.bits(),
2301                 layout.align.abi.bits() as u32,
2302                 DIFlags::FlagZero,
2303                 None,
2304                 type_array,
2305                 0,
2306                 None,
2307                 unique_type_id_str.as_ptr().cast(),
2308                 unique_type_id_str.len(),
2309             )
2310         }
2311     };
2312
2313     create_and_register_recursive_type_forward_declaration(
2314         cx,
2315         enum_type,
2316         unique_type_id,
2317         struct_wrapper,
2318         variant_part,
2319         EnumMDF(EnumMemberDescriptionFactory {
2320             enum_type,
2321             layout,
2322             tag_type_metadata: None,
2323             common_members: outer_fields,
2324             span,
2325         }),
2326     )
2327 }
2328
2329 /// Creates debug information for a composite type, that is, anything that
2330 /// results in a LLVM struct.
2331 ///
2332 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2333 fn composite_type_metadata(
2334     cx: &CodegenCx<'ll, 'tcx>,
2335     composite_type: Ty<'tcx>,
2336     composite_type_name: &str,
2337     composite_type_unique_id: UniqueTypeId,
2338     member_descriptions: Vec<MemberDescription<'ll>>,
2339     containing_scope: Option<&'ll DIScope>,
2340
2341     // Ignore source location information as long as it
2342     // can't be reconstructed for non-local crates.
2343     _file_metadata: &'ll DIFile,
2344     _definition_span: Span,
2345 ) -> &'ll DICompositeType {
2346     // Create the (empty) struct metadata node ...
2347     let composite_type_metadata = create_struct_stub(
2348         cx,
2349         composite_type,
2350         composite_type_name,
2351         composite_type_unique_id,
2352         containing_scope,
2353         DIFlags::FlagZero,
2354     );
2355     // ... and immediately create and add the member descriptions.
2356     set_members_of_composite_type(
2357         cx,
2358         composite_type,
2359         composite_type_metadata,
2360         member_descriptions,
2361         None,
2362     );
2363
2364     composite_type_metadata
2365 }
2366
2367 fn set_members_of_composite_type(
2368     cx: &CodegenCx<'ll, 'tcx>,
2369     composite_type: Ty<'tcx>,
2370     composite_type_metadata: &'ll DICompositeType,
2371     member_descriptions: Vec<MemberDescription<'ll>>,
2372     common_members: Option<&Vec<Option<&'ll DIType>>>,
2373 ) {
2374     // In some rare cases LLVM metadata uniquing would lead to an existing type
2375     // description being used instead of a new one created in
2376     // create_struct_stub. This would cause a hard to trace assertion in
2377     // DICompositeType::SetTypeArray(). The following check makes sure that we
2378     // get a better error message if this should happen again due to some
2379     // regression.
2380     {
2381         let mut composite_types_completed =
2382             debug_context(cx).composite_types_completed.borrow_mut();
2383         if !composite_types_completed.insert(composite_type_metadata) {
2384             bug!(
2385                 "debuginfo::set_members_of_composite_type() - \
2386                   Already completed forward declaration re-encountered."
2387             );
2388         }
2389     }
2390
2391     let mut member_metadata: Vec<_> = member_descriptions
2392         .into_iter()
2393         .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2394         .collect();
2395     if let Some(other_members) = common_members {
2396         member_metadata.extend(other_members.iter());
2397     }
2398
2399     let type_params = compute_type_parameters(cx, composite_type);
2400     unsafe {
2401         let type_array = create_DIArray(DIB(cx), &member_metadata);
2402         llvm::LLVMRustDICompositeTypeReplaceArrays(
2403             DIB(cx),
2404             composite_type_metadata,
2405             Some(type_array),
2406             Some(type_params),
2407         );
2408     }
2409 }
2410
2411 /// Computes the type parameters for a type, if any, for the given metadata.
2412 fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2413     if let ty::Adt(def, substs) = *ty.kind() {
2414         if substs.types().next().is_some() {
2415             let generics = cx.tcx.generics_of(def.did);
2416             let names = get_parameter_names(cx, generics);
2417             let template_params: Vec<_> = iter::zip(substs, names)
2418                 .filter_map(|(kind, name)| {
2419                     if let GenericArgKind::Type(ty) = kind.unpack() {
2420                         let actual_type =
2421                             cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2422                         let actual_type_metadata =
2423                             type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
2424                         let name = &name.as_str();
2425                         Some(unsafe {
2426                             Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2427                                 DIB(cx),
2428                                 None,
2429                                 name.as_ptr().cast(),
2430                                 name.len(),
2431                                 actual_type_metadata,
2432                             ))
2433                         })
2434                     } else {
2435                         None
2436                     }
2437                 })
2438                 .collect();
2439
2440             return create_DIArray(DIB(cx), &template_params);
2441         }
2442     }
2443     return create_DIArray(DIB(cx), &[]);
2444
2445     fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2446         let mut names = generics
2447             .parent
2448             .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2449         names.extend(generics.params.iter().map(|param| param.name));
2450         names
2451     }
2452 }
2453
2454 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2455 /// any caching, does not add any fields to the struct. This can be done later
2456 /// with `set_members_of_composite_type()`.
2457 fn create_struct_stub(
2458     cx: &CodegenCx<'ll, 'tcx>,
2459     struct_type: Ty<'tcx>,
2460     struct_type_name: &str,
2461     unique_type_id: UniqueTypeId,
2462     containing_scope: Option<&'ll DIScope>,
2463     flags: DIFlags,
2464 ) -> &'ll DICompositeType {
2465     let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2466
2467     let type_map = debug_context(cx).type_map.borrow();
2468     let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2469
2470     let metadata_stub = unsafe {
2471         // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2472         // pointer will lead to hard to trace and debug LLVM assertions
2473         // later on in `llvm/lib/IR/Value.cpp`.
2474         let empty_array = create_DIArray(DIB(cx), &[]);
2475
2476         llvm::LLVMRustDIBuilderCreateStructType(
2477             DIB(cx),
2478             containing_scope,
2479             struct_type_name.as_ptr().cast(),
2480             struct_type_name.len(),
2481             unknown_file_metadata(cx),
2482             UNKNOWN_LINE_NUMBER,
2483             struct_size.bits(),
2484             struct_align.bits() as u32,
2485             flags,
2486             None,
2487             empty_array,
2488             0,
2489             None,
2490             unique_type_id.as_ptr().cast(),
2491             unique_type_id.len(),
2492         )
2493     };
2494
2495     metadata_stub
2496 }
2497
2498 fn create_union_stub(
2499     cx: &CodegenCx<'ll, 'tcx>,
2500     union_type: Ty<'tcx>,
2501     union_type_name: &str,
2502     unique_type_id: UniqueTypeId,
2503     containing_scope: &'ll DIScope,
2504 ) -> &'ll DICompositeType {
2505     let (union_size, union_align) = cx.size_and_align_of(union_type);
2506
2507     let type_map = debug_context(cx).type_map.borrow();
2508     let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2509
2510     let metadata_stub = unsafe {
2511         // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2512         // pointer will lead to hard to trace and debug LLVM assertions
2513         // later on in `llvm/lib/IR/Value.cpp`.
2514         let empty_array = create_DIArray(DIB(cx), &[]);
2515
2516         llvm::LLVMRustDIBuilderCreateUnionType(
2517             DIB(cx),
2518             Some(containing_scope),
2519             union_type_name.as_ptr().cast(),
2520             union_type_name.len(),
2521             unknown_file_metadata(cx),
2522             UNKNOWN_LINE_NUMBER,
2523             union_size.bits(),
2524             union_align.bits() as u32,
2525             DIFlags::FlagZero,
2526             Some(empty_array),
2527             0, // RuntimeLang
2528             unique_type_id.as_ptr().cast(),
2529             unique_type_id.len(),
2530         )
2531     };
2532
2533     metadata_stub
2534 }
2535
2536 /// Creates debug information for the given global variable.
2537 ///
2538 /// Adds the created metadata nodes directly to the crate's IR.
2539 pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2540     if cx.dbg_cx.is_none() {
2541         return;
2542     }
2543
2544     // Only create type information if full debuginfo is enabled
2545     if cx.sess().opts.debuginfo != DebugInfo::Full {
2546         return;
2547     }
2548
2549     let tcx = cx.tcx;
2550
2551     // We may want to remove the namespace scope if we're in an extern block (see
2552     // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2553     let var_scope = get_namespace_for_item(cx, def_id);
2554     let span = tcx.def_span(def_id);
2555
2556     let (file_metadata, line_number) = if !span.is_dummy() {
2557         let loc = cx.lookup_debug_loc(span.lo());
2558         (file_metadata(cx, &loc.file), loc.line)
2559     } else {
2560         (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2561     };
2562
2563     let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2564     let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2565     let type_metadata = type_metadata(cx, variable_type, span);
2566     let var_name = tcx.item_name(def_id).as_str();
2567     let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2568     // When empty, linkage_name field is omitted,
2569     // which is what we want for no_mangle statics
2570     let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2571
2572     let global_align = cx.align_of(variable_type);
2573
2574     unsafe {
2575         llvm::LLVMRustDIBuilderCreateStaticVariable(
2576             DIB(cx),
2577             Some(var_scope),
2578             var_name.as_ptr().cast(),
2579             var_name.len(),
2580             linkage_name.as_ptr().cast(),
2581             linkage_name.len(),
2582             file_metadata,
2583             line_number,
2584             type_metadata,
2585             is_local_to_unit,
2586             global,
2587             None,
2588             global_align.bytes() as u32,
2589         );
2590     }
2591 }
2592
2593 /// Generates LLVM debuginfo for a vtable.
2594 fn vtable_type_metadata(
2595     cx: &CodegenCx<'ll, 'tcx>,
2596     ty: Ty<'tcx>,
2597     poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2598 ) -> &'ll DIType {
2599     let tcx = cx.tcx;
2600
2601     let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
2602         let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
2603         let trait_ref = tcx.erase_regions(trait_ref);
2604
2605         tcx.vtable_entries(trait_ref)
2606     } else {
2607         COMMON_VTABLE_ENTRIES
2608     };
2609
2610     // FIXME: We describe the vtable as an array of *const () pointers. The length of the array is
2611     //        correct - but we could create a more accurate description, e.g. by describing it
2612     //        as a struct where each field has a name that corresponds to the name of the method
2613     //        it points to.
2614     //        However, this is not entirely straightforward because there might be multiple
2615     //        methods with the same name if the vtable is for multiple traits. So for now we keep
2616     //        things simple instead of adding some ad-hoc disambiguation scheme.
2617     let vtable_type = tcx.mk_array(tcx.mk_imm_ptr(tcx.types.unit), vtable_entries.len() as u64);
2618
2619     type_metadata(cx, vtable_type, rustc_span::DUMMY_SP)
2620 }
2621
2622 /// Creates debug information for the given vtable, which is for the
2623 /// given type.
2624 ///
2625 /// Adds the created metadata nodes directly to the crate's IR.
2626 pub fn create_vtable_metadata(
2627     cx: &CodegenCx<'ll, 'tcx>,
2628     ty: Ty<'tcx>,
2629     poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2630     vtable: &'ll Value,
2631 ) {
2632     if cx.dbg_cx.is_none() {
2633         return;
2634     }
2635
2636     // Only create type information if full debuginfo is enabled
2637     if cx.sess().opts.debuginfo != DebugInfo::Full {
2638         return;
2639     }
2640
2641     let vtable_name = compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref);
2642     let vtable_type = vtable_type_metadata(cx, ty, poly_trait_ref);
2643
2644     unsafe {
2645         let linkage_name = "";
2646         llvm::LLVMRustDIBuilderCreateStaticVariable(
2647             DIB(cx),
2648             NO_SCOPE_METADATA,
2649             vtable_name.as_ptr().cast(),
2650             vtable_name.len(),
2651             linkage_name.as_ptr().cast(),
2652             linkage_name.len(),
2653             unknown_file_metadata(cx),
2654             UNKNOWN_LINE_NUMBER,
2655             vtable_type,
2656             true,
2657             vtable,
2658             None,
2659             0,
2660         );
2661     }
2662 }
2663
2664 /// Creates an "extension" of an existing `DIScope` into another file.
2665 pub fn extend_scope_to_file(
2666     cx: &CodegenCx<'ll, '_>,
2667     scope_metadata: &'ll DIScope,
2668     file: &SourceFile,
2669 ) -> &'ll DILexicalBlock {
2670     let file_metadata = file_metadata(cx, file);
2671     unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }
2672 }