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