]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/debuginfo/metadata.rs
Use `assert_usize` instead of `unwrap_usize` in several places
[rust.git] / src / librustc_codegen_llvm / debuginfo / metadata.rs
1 use self::RecursiveTypeDescription::*;
2 use self::MemberDescriptionFactory::*;
3 use self::EnumDiscriminantInfo::*;
4
5 use super::utils::{debug_context, DIB, span_start,
6                    get_namespace_for_item, create_DIArray, is_node_local_to_unit};
7 use super::namespace::mangled_name_of_instance;
8 use super::type_names::compute_debuginfo_type_name;
9 use super::{CrateDebugContext};
10 use crate::abi;
11 use crate::value::Value;
12 use rustc_codegen_ssa::traits::*;
13
14 use crate::llvm;
15 use crate::llvm::debuginfo::{DIArray, DIType, DIFile, DIScope, DIDescriptor,
16                       DICompositeType, DILexicalBlock, DIFlags, DebugEmissionKind};
17 use crate::llvm_util;
18
19 use crate::common::CodegenCx;
20 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
21 use rustc::hir::CodegenFnAttrFlags;
22 use rustc::hir::def::CtorKind;
23 use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
24 use rustc::ich::NodeIdHashingMode;
25 use rustc::mir::Field;
26 use rustc::mir::GeneratorLayout;
27 use rustc::mir::interpret::truncate;
28 use rustc_data_structures::fingerprint::Fingerprint;
29 use rustc::ty::Instance;
30 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
31 use rustc::ty::layout::{self, Align, Integer, IntegerExt, LayoutOf,
32                         PrimitiveExt, Size, TyLayout, VariantIdx};
33 use rustc::ty::subst::UnpackedKind;
34 use rustc::session::config::{self, DebugInfo};
35 use rustc::util::nodemap::FxHashMap;
36 use rustc_fs_util::path_to_c_string;
37 use rustc_data_structures::small_c_str::SmallCStr;
38 use rustc_target::abi::HasDataLayout;
39
40 use libc::{c_uint, c_longlong};
41 use std::collections::hash_map::Entry;
42 use std::ffi::CString;
43 use std::fmt::{self, Write};
44 use std::hash::{Hash, Hasher};
45 use std::iter;
46 use std::ptr;
47 use std::path::{Path, PathBuf};
48 use syntax::ast;
49 use syntax::symbol::{Interner, InternedString};
50 use syntax_pos::{self, Span, FileName};
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(ast::Name);
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 // UniqueTypeIds.
98 #[derive(Default)]
99 pub struct TypeMap<'ll, 'tcx> {
100     // The UniqueTypeIds 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 a N:1 mapping.
105     type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
106     // A map from types to UniqueTypeId. This is a 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(
114         &mut self,
115         type_: Ty<'tcx>,
116         metadata: &'ll DIType,
117     ) {
118         if self.type_to_metadata.insert(type_, metadata).is_some() {
119             bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
120         }
121     }
122
123     // Removes a Ty to metadata mapping
124     // This is useful when computing the metadata for a potentially
125     // recursive type (e.g. a function ptr of the form:
126     //
127     // fn foo() -> impl Copy { foo }
128     //
129     // This kind of type cannot be properly represented
130     // via LLVM debuginfo. As a workaround,
131     // we register a temporary Ty to metadata mapping
132     // for the function before we compute its actual metadata.
133     // If the metadata computation ends up recursing back to the
134     // original function, it will use the temporary mapping
135     // for the inner self-reference, preventing us from
136     // recursing forever.
137     //
138     // This function is used to remove the temporary metadata
139     // mapping after we've computed the actual metadata
140     fn remove_type(
141         &mut self,
142         type_: Ty<'tcx>,
143     ) {
144         if self.type_to_metadata.remove(type_).is_none() {
145             bug!("Type metadata Ty '{}' is not in the TypeMap!", type_);
146         }
147     }
148
149     // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
150     // fail if the mapping already exists.
151     fn register_unique_id_with_metadata(
152         &mut self,
153         unique_type_id: UniqueTypeId,
154         metadata: &'ll DIType,
155     ) {
156         if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
157             bug!("Type metadata for unique id '{}' is already in the TypeMap!",
158                  self.get_unique_type_id_as_string(unique_type_id));
159         }
160     }
161
162     fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
163         self.type_to_metadata.get(&type_).cloned()
164     }
165
166     fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
167         self.unique_id_to_metadata.get(&unique_type_id).cloned()
168     }
169
170     // Get the string representation of a UniqueTypeId. This method will fail if
171     // the id is unknown.
172     fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
173         let UniqueTypeId(interner_key) = unique_type_id;
174         self.unique_id_interner.get(interner_key)
175     }
176
177     // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
178     // type has been requested before, this is just a table lookup. Otherwise an
179     // ID will be generated and stored for later lookup.
180     fn get_unique_type_id_of_type<'a>(&mut self, cx: &CodegenCx<'a, 'tcx>,
181                                       type_: Ty<'tcx>) -> UniqueTypeId {
182         // Let's see if we already have something in the cache
183         if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
184             return unique_type_id;
185         }
186         // if not, generate one
187
188         // The hasher we are using to generate the UniqueTypeId. We want
189         // something that provides more than the 64 bits of the DefaultHasher.
190         let mut hasher = StableHasher::<Fingerprint>::new();
191         let mut hcx = cx.tcx.create_stable_hashing_context();
192         let type_ = cx.tcx.erase_regions(&type_);
193         hcx.while_hashing_spans(false, |hcx| {
194             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
195                 type_.hash_stable(hcx, &mut hasher);
196             });
197         });
198         let unique_type_id = hasher.finish().to_hex();
199
200         let key = self.unique_id_interner.intern(&unique_type_id);
201         self.type_to_unique_id.insert(type_, UniqueTypeId(key));
202
203         return UniqueTypeId(key);
204     }
205
206     // Get the UniqueTypeId for an enum variant. Enum variants are not really
207     // types of their own, so they need special handling. We still need a
208     // UniqueTypeId for them, since to debuginfo they *are* real types.
209     fn get_unique_type_id_of_enum_variant<'a>(&mut self,
210                                               cx: &CodegenCx<'a, 'tcx>,
211                                               enum_type: Ty<'tcx>,
212                                               variant_name: &str)
213                                               -> UniqueTypeId {
214         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
215         let enum_variant_type_id = format!("{}::{}",
216                                            self.get_unique_type_id_as_string(enum_type_id),
217                                            variant_name);
218         let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
219         UniqueTypeId(interner_key)
220     }
221
222     // Get the unique type id string for an enum variant part.
223     // Variant parts are not types and shouldn't really have their own id,
224     // but it makes set_members_of_composite_type() simpler.
225     fn get_unique_type_id_str_of_enum_variant_part<'a>(&mut self,
226                                                        enum_type_id: UniqueTypeId) -> &str {
227         let variant_part_type_id = format!("{}_variant_part",
228                                            self.get_unique_type_id_as_string(enum_type_id));
229         let interner_key = self.unique_id_interner.intern(&variant_part_type_id);
230         self.unique_id_interner.get(interner_key)
231     }
232 }
233
234 // A description of some recursive type. It can either be already finished (as
235 // with FinalMetadata) or it is not yet finished, but contains all information
236 // needed to generate the missing parts of the description. See the
237 // documentation section on Recursive Types at the top of this file for more
238 // information.
239 enum RecursiveTypeDescription<'ll, 'tcx> {
240     UnfinishedMetadata {
241         unfinished_type: Ty<'tcx>,
242         unique_type_id: UniqueTypeId,
243         metadata_stub: &'ll DICompositeType,
244         member_holding_stub: &'ll DICompositeType,
245         member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
246     },
247     FinalMetadata(&'ll DICompositeType)
248 }
249
250 fn create_and_register_recursive_type_forward_declaration(
251     cx: &CodegenCx<'ll, 'tcx>,
252     unfinished_type: Ty<'tcx>,
253     unique_type_id: UniqueTypeId,
254     metadata_stub: &'ll DICompositeType,
255     member_holding_stub: &'ll DICompositeType,
256     member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
257 ) -> RecursiveTypeDescription<'ll, 'tcx> {
258
259     // Insert the stub into the TypeMap in order to allow for recursive references
260     let mut type_map = debug_context(cx).type_map.borrow_mut();
261     type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
262     type_map.register_type_with_metadata(unfinished_type, metadata_stub);
263
264     UnfinishedMetadata {
265         unfinished_type,
266         unique_type_id,
267         metadata_stub,
268         member_holding_stub,
269         member_description_factory,
270     }
271 }
272
273 impl RecursiveTypeDescription<'ll, 'tcx> {
274     // Finishes up the description of the type in question (mostly by providing
275     // descriptions of the fields of the given type) and returns the final type
276     // metadata.
277     fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
278         match *self {
279             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
280             UnfinishedMetadata {
281                 unfinished_type,
282                 unique_type_id,
283                 metadata_stub,
284                 member_holding_stub,
285                 ref member_description_factory,
286             } => {
287                 // Make sure that we have a forward declaration of the type in
288                 // the TypeMap so that recursive references are possible. This
289                 // will always be the case if the RecursiveTypeDescription has
290                 // been properly created through the
291                 // create_and_register_recursive_type_forward_declaration()
292                 // function.
293                 {
294                     let type_map = debug_context(cx).type_map.borrow();
295                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
296                        type_map.find_metadata_for_type(unfinished_type).is_none() {
297                         bug!("Forward declaration of potentially recursive type \
298                               '{:?}' was not found in TypeMap!",
299                              unfinished_type);
300                     }
301                 }
302
303                 // ... then create the member descriptions ...
304                 let member_descriptions =
305                     member_description_factory.create_member_descriptions(cx);
306
307                 // ... and attach them to the stub to complete it.
308                 set_members_of_composite_type(cx,
309                                               unfinished_type,
310                                               member_holding_stub,
311                                               member_descriptions);
312                 return MetadataCreationResult::new(metadata_stub, true);
313             }
314         }
315     }
316 }
317
318 // Returns from the enclosing function if the type metadata with the given
319 // unique id can be found in the type map
320 macro_rules! return_if_metadata_created_in_meantime {
321     ($cx: expr, $unique_type_id: expr) => (
322         if let Some(metadata) = debug_context($cx).type_map
323             .borrow()
324             .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.sty {
345         ty::Array(_, len) => len.unwrap_usize(cx.tcx) as c_longlong,
346         _ => -1
347     };
348
349     let subrange = unsafe {
350         Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound))
351     };
352
353     let subscripts = create_DIArray(DIB(cx), &[subrange]);
354     let metadata = unsafe {
355         llvm::LLVMRustDIBuilderCreateArrayType(
356             DIB(cx),
357             size.bits(),
358             align.bits() as u32,
359             element_type_metadata,
360             subscripts)
361     };
362
363     return 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         },
394         MemberDescription {
395             name: "length".to_owned(),
396             type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
397             offset: pointer_size,
398             size: usize_size,
399             align: usize_align,
400             flags: DIFlags::FlagZero,
401             discriminant: None,
402         },
403     ];
404
405     let file_metadata = unknown_file_metadata(cx);
406
407     let metadata = composite_type_metadata(cx,
408                                            slice_ptr_type,
409                                            &slice_type_name[..],
410                                            unique_type_id,
411                                            member_descriptions,
412                                            NO_SCOPE_METADATA,
413                                            file_metadata,
414                                            span);
415     MetadataCreationResult::new(metadata, false)
416 }
417
418 fn subroutine_type_metadata(
419     cx: &CodegenCx<'ll, 'tcx>,
420     unique_type_id: UniqueTypeId,
421     signature: ty::PolyFnSig<'tcx>,
422     span: Span,
423 ) -> MetadataCreationResult<'ll> {
424     let signature = cx.tcx.normalize_erasing_late_bound_regions(
425         ty::ParamEnv::reveal_all(),
426         &signature,
427     );
428
429     let signature_metadata: Vec<_> = iter::once(
430         // return type
431         match signature.output().sty {
432             ty::Tuple(ref tys) if tys.is_empty() => None,
433             _ => Some(type_metadata(cx, signature.output(), span))
434         }
435     ).chain(
436         // regular arguments
437         signature.inputs().iter().map(|argument_type| {
438             Some(type_metadata(cx, argument_type, span))
439         })
440     ).collect();
441
442     return_if_metadata_created_in_meantime!(cx, unique_type_id);
443
444     return MetadataCreationResult::new(
445         unsafe {
446             llvm::LLVMRustDIBuilderCreateSubroutineType(
447                 DIB(cx),
448                 unknown_file_metadata(cx),
449                 create_DIArray(DIB(cx), &signature_metadata[..]))
450         },
451         false);
452 }
453
454 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
455 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
456 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
457 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
458 // of a DST struct, there is no trait_object_type and the results of this
459 // function will be a little bit weird.
460 fn trait_pointer_metadata(
461     cx: &CodegenCx<'ll, 'tcx>,
462     trait_type: Ty<'tcx>,
463     trait_object_type: Option<Ty<'tcx>>,
464     unique_type_id: UniqueTypeId,
465 ) -> &'ll DIType {
466     // The implementation provided here is a stub. It makes sure that the trait
467     // type is assigned the correct name, size, namespace, and source location.
468     // But it does not describe the trait's methods.
469
470     let containing_scope = match trait_type.sty {
471         ty::Dynamic(ref data, ..) =>
472             data.principal_def_id().map(|did| get_namespace_for_item(cx, did)),
473         _ => {
474             bug!("debuginfo: Unexpected trait-object type in \
475                   trait_pointer_metadata(): {:?}",
476                  trait_type);
477         }
478     };
479
480     let trait_object_type = trait_object_type.unwrap_or(trait_type);
481     let trait_type_name =
482         compute_debuginfo_type_name(cx.tcx, trait_object_type, false);
483
484     let file_metadata = unknown_file_metadata(cx);
485
486     let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
487
488     assert_eq!(abi::FAT_PTR_ADDR, 0);
489     assert_eq!(abi::FAT_PTR_EXTRA, 1);
490
491     let data_ptr_field = layout.field(cx, 0);
492     let vtable_field = layout.field(cx, 1);
493     let member_descriptions = vec![
494         MemberDescription {
495             name: "pointer".to_owned(),
496             type_metadata: type_metadata(cx,
497                 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
498                 syntax_pos::DUMMY_SP),
499             offset: layout.fields.offset(0),
500             size: data_ptr_field.size,
501             align: data_ptr_field.align.abi,
502             flags: DIFlags::FlagArtificial,
503             discriminant: None,
504         },
505         MemberDescription {
506             name: "vtable".to_owned(),
507             type_metadata: type_metadata(cx, vtable_field.ty, syntax_pos::DUMMY_SP),
508             offset: layout.fields.offset(1),
509             size: vtable_field.size,
510             align: vtable_field.align.abi,
511             flags: DIFlags::FlagArtificial,
512             discriminant: None,
513         },
514     ];
515
516     composite_type_metadata(cx,
517                             trait_object_type,
518                             &trait_type_name[..],
519                             unique_type_id,
520                             member_descriptions,
521                             containing_scope,
522                             file_metadata,
523                             syntax_pos::DUMMY_SP)
524 }
525
526 pub fn type_metadata(
527     cx: &CodegenCx<'ll, 'tcx>,
528     t: Ty<'tcx>,
529     usage_site_span: Span,
530 ) -> &'ll DIType {
531     // Get the unique type id of this type.
532     let unique_type_id = {
533         let mut type_map = debug_context(cx).type_map.borrow_mut();
534         // First, try to find the type in TypeMap. If we have seen it before, we
535         // can exit early here.
536         match type_map.find_metadata_for_type(t) {
537             Some(metadata) => {
538                 return metadata;
539             },
540             None => {
541                 // The Ty is not in the TypeMap but maybe we have already seen
542                 // an equivalent type (e.g., only differing in region arguments).
543                 // In order to find out, generate the unique type id and look
544                 // that up.
545                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
546                 match type_map.find_metadata_for_unique_id(unique_type_id) {
547                     Some(metadata) => {
548                         // There is already an equivalent type in the TypeMap.
549                         // Register this Ty as an alias in the cache and
550                         // return the cached metadata.
551                         type_map.register_type_with_metadata(t, metadata);
552                         return metadata;
553                     },
554                     None => {
555                         // There really is no type metadata for this type, so
556                         // proceed by creating it.
557                         unique_type_id
558                     }
559                 }
560             }
561         }
562     };
563
564     debug!("type_metadata: {:?}", t);
565
566     let ptr_metadata = |ty: Ty<'tcx>| {
567         match ty.sty {
568             ty::Slice(typ) => {
569                 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
570             }
571             ty::Str => {
572                 Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span))
573             }
574             ty::Dynamic(..) => {
575                 Ok(MetadataCreationResult::new(
576                     trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
577                     false))
578             }
579             _ => {
580                 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
581
582                 if let Some(metadata) = debug_context(cx).type_map
583                     .borrow()
584                     .find_metadata_for_unique_id(unique_type_id)
585                 {
586                     return Err(metadata);
587                 }
588
589                 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
590                    false))
591             }
592         }
593     };
594
595     let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.sty {
596         ty::Never    |
597         ty::Bool     |
598         ty::Char     |
599         ty::Int(_)   |
600         ty::Uint(_)  |
601         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, _) |
608         ty::Slice(typ) => {
609             fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
610         }
611         ty::Str => {
612             fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span)
613         }
614         ty::Dynamic(..) => {
615             MetadataCreationResult::new(
616                 trait_pointer_metadata(cx, t, None, unique_type_id),
617                 false)
618         }
619         ty::Foreign(..) => {
620             MetadataCreationResult::new(
621             foreign_type_metadata(cx, t, unique_type_id),
622             false)
623         }
624         ty::RawPtr(ty::TypeAndMut{ty, ..}) |
625         ty::Ref(_, ty, _) => {
626             match ptr_metadata(ty) {
627                 Ok(res) => res,
628                 Err(metadata) => return metadata,
629             }
630         }
631         ty::Adt(def, _) if def.is_box() => {
632             match ptr_metadata(t.boxed_ty()) {
633                 Ok(res) => res,
634                 Err(metadata) => return metadata,
635             }
636         }
637         ty::FnDef(..) | ty::FnPtr(_) => {
638
639             if let Some(metadata) = debug_context(cx).type_map
640                .borrow()
641                .find_metadata_for_unique_id(unique_type_id)
642             {
643                 return metadata;
644             }
645
646             // It's possible to create a self-referential
647             // type in Rust by using 'impl trait':
648             //
649             // fn foo() -> impl Copy { foo }
650             //
651             // See TypeMap::remove_type for more detals
652             // about the workaround
653
654             let temp_type = {
655                 unsafe {
656                     // The choice of type here is pretty arbitrary -
657                     // anything reading the debuginfo for a recursive
658                     // type is going to see *somthing* weird - the only
659                     // question is what exactly it will see
660                     let (size, align) = cx.size_and_align_of(t);
661                     llvm::LLVMRustDIBuilderCreateBasicType(
662                         DIB(cx),
663                         SmallCStr::new("<recur_type>").as_ptr(),
664                         size.bits(),
665                         align.bits() as u32,
666                         DW_ATE_unsigned)
667                 }
668             };
669
670             let type_map = &debug_context(cx).type_map;
671             type_map.borrow_mut().register_type_with_metadata(t, temp_type);
672
673             let fn_metadata = subroutine_type_metadata(cx,
674                                                        unique_type_id,
675                                                        t.fn_sig(cx.tcx),
676                                                        usage_site_span).metadata;
677
678             type_map.borrow_mut().remove_type(t);
679
680
681             // This is actually a function pointer, so wrap it in pointer DI
682             MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
683
684         }
685         ty::Closure(def_id, substs) => {
686             let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx).collect();
687             prepare_tuple_metadata(cx,
688                                    t,
689                                    &upvar_tys,
690                                    unique_type_id,
691                                    usage_site_span).finalize(cx)
692         }
693         ty::Generator(def_id, substs,  _) => {
694             let upvar_tys : Vec<_> = substs.prefix_tys(def_id, cx.tcx).map(|t| {
695                 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)
696             }).collect();
697             prepare_enum_metadata(cx,
698                                   t,
699                                   def_id,
700                                   unique_type_id,
701                                   usage_site_span,
702                                   upvar_tys).finalize(cx)
703         }
704         ty::Adt(def, ..) => match def.adt_kind() {
705             AdtKind::Struct => {
706                 prepare_struct_metadata(cx,
707                                         t,
708                                         unique_type_id,
709                                         usage_site_span).finalize(cx)
710             }
711             AdtKind::Union => {
712                 prepare_union_metadata(cx,
713                                        t,
714                                        unique_type_id,
715                                        usage_site_span).finalize(cx)
716             }
717             AdtKind::Enum => {
718                 prepare_enum_metadata(cx,
719                                       t,
720                                       def.did,
721                                       unique_type_id,
722                                       usage_site_span,
723                                       vec![]).finalize(cx)
724             }
725         },
726         ty::Tuple(ref elements) => {
727             let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
728             prepare_tuple_metadata(cx,
729                                    t,
730                                    &tys,
731                                    unique_type_id,
732                                    usage_site_span).finalize(cx)
733         }
734         _ => {
735             bug!("debuginfo: unexpected type in type_metadata: {:?}", t)
736         }
737     };
738
739     {
740         let mut type_map = debug_context(cx).type_map.borrow_mut();
741
742         if already_stored_in_typemap {
743             // Also make sure that we already have a TypeMap entry for the unique type id.
744             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
745                 Some(metadata) => metadata,
746                 None => {
747                     span_bug!(usage_site_span,
748                               "Expected type metadata for unique \
749                                type id '{}' to already be in \
750                                the debuginfo::TypeMap but it \
751                                was not. (Ty = {})",
752                               type_map.get_unique_type_id_as_string(unique_type_id),
753                               t);
754                 }
755             };
756
757             match type_map.find_metadata_for_type(t) {
758                 Some(metadata) => {
759                     if metadata != metadata_for_uid {
760                         span_bug!(usage_site_span,
761                                   "Mismatch between Ty and \
762                                    UniqueTypeId maps in \
763                                    debuginfo::TypeMap. \
764                                    UniqueTypeId={}, Ty={}",
765                                   type_map.get_unique_type_id_as_string(unique_type_id),
766                                   t);
767                     }
768                 }
769                 None => {
770                     type_map.register_type_with_metadata(t, metadata);
771                 }
772             }
773         } else {
774             type_map.register_type_with_metadata(t, metadata);
775             type_map.register_unique_id_with_metadata(unique_type_id, metadata);
776         }
777     }
778
779     metadata
780 }
781
782 pub fn file_metadata(cx: &CodegenCx<'ll, '_>,
783                      file_name: &FileName,
784                      defining_crate: CrateNum) -> &'ll DIFile {
785     debug!("file_metadata: file_name: {}, defining_crate: {}",
786            file_name,
787            defining_crate);
788
789     let file_name = Some(file_name.to_string());
790     let directory = if defining_crate == LOCAL_CRATE {
791         Some(cx.sess().working_dir.0.to_string_lossy().to_string())
792     } else {
793         // If the path comes from an upstream crate we assume it has been made
794         // independent of the compiler's working directory one way or another.
795         None
796     };
797     file_metadata_raw(cx, file_name, directory)
798 }
799
800 pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
801     file_metadata_raw(cx, None, None)
802 }
803
804 fn file_metadata_raw(cx: &CodegenCx<'ll, '_>,
805                      file_name: Option<String>,
806                      directory: Option<String>)
807                      -> &'ll DIFile {
808     let key = (file_name, directory);
809
810     match debug_context(cx).created_files.borrow_mut().entry(key) {
811         Entry::Occupied(o) => return o.get(),
812         Entry::Vacant(v) => {
813             let (file_name, directory) = v.key();
814             debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
815
816             let file_name = SmallCStr::new(
817                 if let Some(file_name) = file_name { &file_name } else { "<unknown>" });
818             let directory = SmallCStr::new(
819                 if let Some(directory) = directory { &directory } else { "" });
820
821             let file_metadata = unsafe {
822                 llvm::LLVMRustDIBuilderCreateFile(DIB(cx),
823                                                   file_name.as_ptr(),
824                                                   directory.as_ptr())
825             };
826
827             v.insert(file_metadata);
828             file_metadata
829         }
830     }
831 }
832
833 fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
834     debug!("basic_type_metadata: {:?}", t);
835
836     let (name, encoding) = match t.sty {
837         ty::Never => ("!", DW_ATE_unsigned),
838         ty::Tuple(ref elements) if elements.is_empty() =>
839             ("()", DW_ATE_unsigned),
840         ty::Bool => ("bool", DW_ATE_boolean),
841         ty::Char => ("char", DW_ATE_unsigned_char),
842         ty::Int(int_ty) => {
843             (int_ty.ty_to_string(), DW_ATE_signed)
844         },
845         ty::Uint(uint_ty) => {
846             (uint_ty.ty_to_string(), DW_ATE_unsigned)
847         },
848         ty::Float(float_ty) => {
849             (float_ty.ty_to_string(), DW_ATE_float)
850         },
851         _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
852     };
853
854     let (size, align) = cx.size_and_align_of(t);
855     let name = SmallCStr::new(name);
856     let ty_metadata = unsafe {
857         llvm::LLVMRustDIBuilderCreateBasicType(
858             DIB(cx),
859             name.as_ptr(),
860             size.bits(),
861             align.bits() as u32,
862             encoding)
863     };
864
865     return ty_metadata;
866 }
867
868 fn foreign_type_metadata(
869     cx: &CodegenCx<'ll, 'tcx>,
870     t: Ty<'tcx>,
871     unique_type_id: UniqueTypeId,
872 ) -> &'ll DIType {
873     debug!("foreign_type_metadata: {:?}", t);
874
875     let name = compute_debuginfo_type_name(cx.tcx, t, false);
876     create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA)
877 }
878
879 fn pointer_type_metadata(
880     cx: &CodegenCx<'ll, 'tcx>,
881     pointer_type: Ty<'tcx>,
882     pointee_type_metadata: &'ll DIType,
883 ) -> &'ll DIType {
884     let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
885     let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
886     let name = SmallCStr::new(&name);
887     unsafe {
888         llvm::LLVMRustDIBuilderCreatePointerType(
889             DIB(cx),
890             pointee_type_metadata,
891             pointer_size.bits(),
892             pointer_align.bits() as u32,
893             name.as_ptr())
894     }
895 }
896
897 pub fn compile_unit_metadata(tcx: TyCtxt<'_, '_, '_>,
898                              codegen_unit_name: &str,
899                              debug_context: &CrateDebugContext<'ll, '_>)
900                              -> &'ll DIDescriptor {
901     let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
902         Some(ref path) => path.clone(),
903         None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
904     };
905
906     // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
907     // if multiple object files with the same DW_AT_name are linked together.
908     // As a workaround we generate unique names for each object file. Those do
909     // not correspond to an actual source file but that should be harmless.
910     if tcx.sess.target.target.options.is_like_osx {
911         name_in_debuginfo.push("@");
912         name_in_debuginfo.push(codegen_unit_name);
913     }
914
915     debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
916     // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
917     let producer = format!("clang LLVM (rustc version {})",
918                            (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
919
920     let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
921     let name_in_debuginfo = SmallCStr::new(&name_in_debuginfo);
922     let work_dir = SmallCStr::new(&tcx.sess.working_dir.0.to_string_lossy());
923     let producer = CString::new(producer).unwrap();
924     let flags = "\0";
925     let split_name = "\0";
926
927     // FIXME(#60020):
928     //
929     //    This should actually be
930     //
931     //    ```
932     //      let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
933     //    ```
934     //
935     //    that is, we should set LLVM's emission kind to `LineTablesOnly` if
936     //    we are compiling with "limited" debuginfo. However, some of the
937     //    existing tools relied on slightly more debuginfo being generated than
938     //    would be the case with `LineTablesOnly`, and we did not want to break
939     //    these tools in a "drive-by fix", without a good idea or plan about
940     //    what limited debuginfo should exactly look like. So for now we keep
941     //    the emission kind as `FullDebug`.
942     //
943     //    See https://github.com/rust-lang/rust/issues/60020 for details.
944     let kind = DebugEmissionKind::FullDebug;
945     assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
946
947     unsafe {
948         let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
949             debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr());
950
951         let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
952             debug_context.builder,
953             DW_LANG_RUST,
954             file_metadata,
955             producer.as_ptr(),
956             tcx.sess.opts.optimize != config::OptLevel::No,
957             flags.as_ptr() as *const _,
958             0,
959             split_name.as_ptr() as *const _,
960             kind);
961
962         if tcx.sess.opts.debugging_opts.profile {
963             let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext,
964                                                                  unit_metadata);
965
966             let gcov_cu_info = [
967                 path_to_mdstring(debug_context.llcontext,
968                                  &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno")),
969                 path_to_mdstring(debug_context.llcontext,
970                                  &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda")),
971                 cu_desc_metadata,
972             ];
973             let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext,
974                                                           gcov_cu_info.as_ptr(),
975                                                           gcov_cu_info.len() as c_uint);
976
977             let llvm_gcov_ident = const_cstr!("llvm.gcov");
978             llvm::LLVMAddNamedMetadataOperand(debug_context.llmod,
979                                               llvm_gcov_ident.as_ptr(),
980                                               gcov_metadata);
981         }
982
983         return unit_metadata;
984     };
985
986     fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
987         let path_str = path_to_c_string(path);
988         unsafe {
989             llvm::LLVMMDStringInContext(llcx,
990                                         path_str.as_ptr(),
991                                         path_str.as_bytes().len() as c_uint)
992         }
993     }
994 }
995
996 struct MetadataCreationResult<'ll> {
997     metadata: &'ll DIType,
998     already_stored_in_typemap: bool
999 }
1000
1001 impl MetadataCreationResult<'ll> {
1002     fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1003         MetadataCreationResult {
1004             metadata,
1005             already_stored_in_typemap,
1006         }
1007     }
1008 }
1009
1010 // Description of a type member, which can either be a regular field (as in
1011 // structs or tuples) or an enum variant.
1012 #[derive(Debug)]
1013 struct MemberDescription<'ll> {
1014     name: String,
1015     type_metadata: &'ll DIType,
1016     offset: Size,
1017     size: Size,
1018     align: Align,
1019     flags: DIFlags,
1020     discriminant: Option<u64>,
1021 }
1022
1023 impl<'ll> MemberDescription<'ll> {
1024     fn into_metadata(self,
1025                      cx: &CodegenCx<'ll, '_>,
1026                      composite_type_metadata: &'ll DIScope) -> &'ll DIType {
1027         let member_name = CString::new(self.name).unwrap();
1028         unsafe {
1029             llvm::LLVMRustDIBuilderCreateVariantMemberType(
1030                 DIB(cx),
1031                 composite_type_metadata,
1032                 member_name.as_ptr(),
1033                 unknown_file_metadata(cx),
1034                 UNKNOWN_LINE_NUMBER,
1035                 self.size.bits(),
1036                 self.align.bits() as u32,
1037                 self.offset.bits(),
1038                 match self.discriminant {
1039                     None => None,
1040                     Some(value) => Some(cx.const_u64(value)),
1041                 },
1042                 self.flags,
1043                 self.type_metadata)
1044         }
1045     }
1046 }
1047
1048 // A factory for MemberDescriptions. It produces a list of member descriptions
1049 // for some record-like type. MemberDescriptionFactories are used to defer the
1050 // creation of type member descriptions in order to break cycles arising from
1051 // recursive type definitions.
1052 enum MemberDescriptionFactory<'ll, 'tcx> {
1053     StructMDF(StructMemberDescriptionFactory<'tcx>),
1054     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1055     EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1056     UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1057     VariantMDF(VariantMemberDescriptionFactory<'ll, 'tcx>)
1058 }
1059
1060 impl MemberDescriptionFactory<'ll, 'tcx> {
1061     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1062                                   -> Vec<MemberDescription<'ll>> {
1063         match *self {
1064             StructMDF(ref this) => {
1065                 this.create_member_descriptions(cx)
1066             }
1067             TupleMDF(ref this) => {
1068                 this.create_member_descriptions(cx)
1069             }
1070             EnumMDF(ref this) => {
1071                 this.create_member_descriptions(cx)
1072             }
1073             UnionMDF(ref this) => {
1074                 this.create_member_descriptions(cx)
1075             }
1076             VariantMDF(ref this) => {
1077                 this.create_member_descriptions(cx)
1078             }
1079         }
1080     }
1081 }
1082
1083 //=-----------------------------------------------------------------------------
1084 // Structs
1085 //=-----------------------------------------------------------------------------
1086
1087 // Creates MemberDescriptions for the fields of a struct
1088 struct StructMemberDescriptionFactory<'tcx> {
1089     ty: Ty<'tcx>,
1090     variant: &'tcx ty::VariantDef,
1091     span: Span,
1092 }
1093
1094 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1095     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1096                                   -> Vec<MemberDescription<'ll>> {
1097         let layout = cx.layout_of(self.ty);
1098         self.variant.fields.iter().enumerate().map(|(i, f)| {
1099             let name = if self.variant.ctor_kind == CtorKind::Fn {
1100                 format!("__{}", i)
1101             } else {
1102                 f.ident.to_string()
1103             };
1104             let field = layout.field(cx, i);
1105             MemberDescription {
1106                 name,
1107                 type_metadata: type_metadata(cx, field.ty, self.span),
1108                 offset: layout.fields.offset(i),
1109                 size: field.size,
1110                 align: field.align.abi,
1111                 flags: DIFlags::FlagZero,
1112                 discriminant: None,
1113             }
1114         }).collect()
1115     }
1116 }
1117
1118
1119 fn prepare_struct_metadata(
1120     cx: &CodegenCx<'ll, 'tcx>,
1121     struct_type: Ty<'tcx>,
1122     unique_type_id: UniqueTypeId,
1123     span: Span,
1124 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1125     let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1126
1127     let (struct_def_id, variant) = match struct_type.sty {
1128         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1129         _ => bug!("prepare_struct_metadata on a non-ADT")
1130     };
1131
1132     let containing_scope = get_namespace_for_item(cx, struct_def_id);
1133
1134     let struct_metadata_stub = create_struct_stub(cx,
1135                                                   struct_type,
1136                                                   &struct_name,
1137                                                   unique_type_id,
1138                                                   Some(containing_scope));
1139
1140     create_and_register_recursive_type_forward_declaration(
1141         cx,
1142         struct_type,
1143         unique_type_id,
1144         struct_metadata_stub,
1145         struct_metadata_stub,
1146         StructMDF(StructMemberDescriptionFactory {
1147             ty: struct_type,
1148             variant,
1149             span,
1150         })
1151     )
1152 }
1153
1154 //=-----------------------------------------------------------------------------
1155 // Tuples
1156 //=-----------------------------------------------------------------------------
1157
1158 // Creates MemberDescriptions for the fields of a tuple
1159 struct TupleMemberDescriptionFactory<'tcx> {
1160     ty: Ty<'tcx>,
1161     component_types: Vec<Ty<'tcx>>,
1162     span: Span,
1163 }
1164
1165 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1166     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1167                                   -> Vec<MemberDescription<'ll>> {
1168         let layout = cx.layout_of(self.ty);
1169         self.component_types.iter().enumerate().map(|(i, &component_type)| {
1170             let (size, align) = cx.size_and_align_of(component_type);
1171             MemberDescription {
1172                 name: format!("__{}", i),
1173                 type_metadata: type_metadata(cx, component_type, self.span),
1174                 offset: layout.fields.offset(i),
1175                 size,
1176                 align,
1177                 flags: DIFlags::FlagZero,
1178                 discriminant: None,
1179             }
1180         }).collect()
1181     }
1182 }
1183
1184 fn prepare_tuple_metadata(
1185     cx: &CodegenCx<'ll, 'tcx>,
1186     tuple_type: Ty<'tcx>,
1187     component_types: &[Ty<'tcx>],
1188     unique_type_id: UniqueTypeId,
1189     span: Span,
1190 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1191     let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1192
1193     let struct_stub = create_struct_stub(cx,
1194                                          tuple_type,
1195                                          &tuple_name[..],
1196                                          unique_type_id,
1197                                          NO_SCOPE_METADATA);
1198
1199     create_and_register_recursive_type_forward_declaration(
1200         cx,
1201         tuple_type,
1202         unique_type_id,
1203         struct_stub,
1204         struct_stub,
1205         TupleMDF(TupleMemberDescriptionFactory {
1206             ty: tuple_type,
1207             component_types: component_types.to_vec(),
1208             span,
1209         })
1210     )
1211 }
1212
1213 //=-----------------------------------------------------------------------------
1214 // Unions
1215 //=-----------------------------------------------------------------------------
1216
1217 struct UnionMemberDescriptionFactory<'tcx> {
1218     layout: TyLayout<'tcx>,
1219     variant: &'tcx ty::VariantDef,
1220     span: Span,
1221 }
1222
1223 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1224     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1225                                   -> Vec<MemberDescription<'ll>> {
1226         self.variant.fields.iter().enumerate().map(|(i, f)| {
1227             let field = self.layout.field(cx, i);
1228             MemberDescription {
1229                 name: f.ident.to_string(),
1230                 type_metadata: type_metadata(cx, field.ty, self.span),
1231                 offset: Size::ZERO,
1232                 size: field.size,
1233                 align: field.align.abi,
1234                 flags: DIFlags::FlagZero,
1235                 discriminant: None,
1236             }
1237         }).collect()
1238     }
1239 }
1240
1241 fn prepare_union_metadata(
1242     cx: &CodegenCx<'ll, 'tcx>,
1243     union_type: Ty<'tcx>,
1244     unique_type_id: UniqueTypeId,
1245     span: Span,
1246 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1247     let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1248
1249     let (union_def_id, variant) = match union_type.sty {
1250         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1251         _ => bug!("prepare_union_metadata on a non-ADT")
1252     };
1253
1254     let containing_scope = get_namespace_for_item(cx, union_def_id);
1255
1256     let union_metadata_stub = create_union_stub(cx,
1257                                                 union_type,
1258                                                 &union_name,
1259                                                 unique_type_id,
1260                                                 containing_scope);
1261
1262     create_and_register_recursive_type_forward_declaration(
1263         cx,
1264         union_type,
1265         unique_type_id,
1266         union_metadata_stub,
1267         union_metadata_stub,
1268         UnionMDF(UnionMemberDescriptionFactory {
1269             layout: cx.layout_of(union_type),
1270             variant,
1271             span,
1272         })
1273     )
1274 }
1275
1276 //=-----------------------------------------------------------------------------
1277 // Enums
1278 //=-----------------------------------------------------------------------------
1279
1280 // DWARF variant support is only available starting in LLVM 8.
1281 // Although the earlier enum debug info output did not work properly
1282 // in all situations, it is better for the time being to continue to
1283 // sometimes emit the old style rather than emit something completely
1284 // useless when rust is compiled against LLVM 6 or older. LLVM 7
1285 // contains an early version of the DWARF variant support, and will
1286 // crash when handling the new debug info format. This function
1287 // decides which representation will be emitted.
1288 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1289     // On MSVC we have to use the fallback mode, because LLVM doesn't
1290     // lower variant parts to PDB.
1291     return cx.sess().target.target.options.is_like_msvc
1292         // LLVM version 7 did not release with an important bug fix;
1293         // but the required patch is in the LLVM 8.  Rust LLVM reports
1294         // 8 as well.
1295         || llvm_util::get_major_version() < 8;
1296 }
1297
1298 // Describes the members of an enum value: An enum is described as a union of
1299 // structs in DWARF. This MemberDescriptionFactory provides the description for
1300 // the members of this union; so for every variant of the given enum, this
1301 // factory will produce one MemberDescription (all with no name and a fixed
1302 // offset of zero bytes).
1303 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1304     enum_type: Ty<'tcx>,
1305     layout: TyLayout<'tcx>,
1306     discriminant_type_metadata: Option<&'ll DIType>,
1307     containing_scope: &'ll DIScope,
1308     span: Span,
1309 }
1310
1311 impl EnumMemberDescriptionFactory<'ll, 'tcx> {
1312     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1313                                   -> Vec<MemberDescription<'ll>> {
1314         let variant_info_for = |index: VariantIdx| {
1315             match &self.enum_type.sty {
1316                 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1317                 ty::Generator(def_id, substs, _) => {
1318                     let generator_layout = cx.tcx.generator_layout(*def_id);
1319                     VariantInfo::Generator(*substs, generator_layout, index)
1320                 }
1321                 _ => bug!(),
1322             }
1323         };
1324
1325         // This will always find the metadata in the type map.
1326         let fallback = use_enum_fallback(cx);
1327         let self_metadata = if fallback {
1328             self.containing_scope
1329         } else {
1330             type_metadata(cx, self.enum_type, self.span)
1331         };
1332
1333         match self.layout.variants {
1334             layout::Variants::Single { index } => {
1335                 if let ty::Adt(adt, _) = &self.enum_type.sty {
1336                     if adt.variants.is_empty() {
1337                         return vec![];
1338                     }
1339                 }
1340
1341                 let variant_info = variant_info_for(index);
1342                 let (variant_type_metadata, member_description_factory) =
1343                     describe_enum_variant(cx,
1344                                           self.layout,
1345                                           variant_info,
1346                                           NoDiscriminant,
1347                                           self_metadata,
1348                                           self.span);
1349
1350                 let member_descriptions =
1351                     member_description_factory.create_member_descriptions(cx);
1352
1353                 set_members_of_composite_type(cx,
1354                                               self.enum_type,
1355                                               variant_type_metadata,
1356                                               member_descriptions);
1357                 vec![
1358                     MemberDescription {
1359                         name: if fallback {
1360                             String::new()
1361                         } else {
1362                             variant_info.variant_name()
1363                         },
1364                         type_metadata: variant_type_metadata,
1365                         offset: Size::ZERO,
1366                         size: self.layout.size,
1367                         align: self.layout.align.abi,
1368                         flags: DIFlags::FlagZero,
1369                         discriminant: None,
1370                     }
1371                 ]
1372             }
1373             layout::Variants::Multiple {
1374                 discr_kind: layout::DiscriminantKind::Tag,
1375                 discr_index,
1376                 ref variants,
1377                 ..
1378             } => {
1379                 let discriminant_info = if fallback {
1380                     RegularDiscriminant {
1381                         discr_field: Field::from(discr_index),
1382                         discr_type_metadata: self.discriminant_type_metadata.unwrap()
1383                     }
1384                 } else {
1385                     // This doesn't matter in this case.
1386                     NoDiscriminant
1387                 };
1388                 variants.iter_enumerated().map(|(i, _)| {
1389                     let variant = self.layout.for_variant(cx, i);
1390                     let variant_info = variant_info_for(i);
1391                     let (variant_type_metadata, member_desc_factory) =
1392                         describe_enum_variant(cx,
1393                                               variant,
1394                                               variant_info,
1395                                               discriminant_info,
1396                                               self_metadata,
1397                                               self.span);
1398
1399                     let member_descriptions = member_desc_factory
1400                         .create_member_descriptions(cx);
1401
1402                     set_members_of_composite_type(cx,
1403                                                   self.enum_type,
1404                                                   variant_type_metadata,
1405                                                   member_descriptions);
1406
1407                     MemberDescription {
1408                         name: if fallback {
1409                             String::new()
1410                         } else {
1411                             variant_info.variant_name()
1412                         },
1413                         type_metadata: variant_type_metadata,
1414                         offset: Size::ZERO,
1415                         size: self.layout.size,
1416                         align: self.layout.align.abi,
1417                         flags: DIFlags::FlagZero,
1418                         discriminant: Some(
1419                             self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val as u64
1420                         ),
1421                     }
1422                 }).collect()
1423             }
1424             layout::Variants::Multiple {
1425                 discr_kind: layout::DiscriminantKind::Niche {
1426                     ref niche_variants,
1427                     niche_start,
1428                     dataful_variant,
1429                 },
1430                 ref discr,
1431                 ref variants,
1432                 discr_index,
1433             } => {
1434                 if fallback {
1435                     let variant = self.layout.for_variant(cx, dataful_variant);
1436                     // Create a description of the non-null variant
1437                     let (variant_type_metadata, member_description_factory) =
1438                         describe_enum_variant(cx,
1439                                               variant,
1440                                               variant_info_for(dataful_variant),
1441                                               OptimizedDiscriminant,
1442                                               self.containing_scope,
1443                                               self.span);
1444
1445                     let variant_member_descriptions =
1446                         member_description_factory.create_member_descriptions(cx);
1447
1448                     set_members_of_composite_type(cx,
1449                                                   self.enum_type,
1450                                                   variant_type_metadata,
1451                                                   variant_member_descriptions);
1452
1453                     // Encode the information about the null variant in the union
1454                     // member's name.
1455                     let mut name = String::from("RUST$ENCODED$ENUM$");
1456                     // Right now it's not even going to work for `niche_start > 0`,
1457                     // and for multiple niche variants it only supports the first.
1458                     fn compute_field_path<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1459                                                     name: &mut String,
1460                                                     layout: TyLayout<'tcx>,
1461                                                     offset: Size,
1462                                                     size: Size) {
1463                         for i in 0..layout.fields.count() {
1464                             let field_offset = layout.fields.offset(i);
1465                             if field_offset > offset {
1466                                 continue;
1467                             }
1468                             let inner_offset = offset - field_offset;
1469                             let field = layout.field(cx, i);
1470                             if inner_offset + size <= field.size {
1471                                 write!(name, "{}$", i).unwrap();
1472                                 compute_field_path(cx, name, field, inner_offset, size);
1473                             }
1474                         }
1475                     }
1476                     compute_field_path(cx, &mut name,
1477                                        self.layout,
1478                                        self.layout.fields.offset(discr_index),
1479                                        self.layout.field(cx, discr_index).size);
1480                     variant_info_for(*niche_variants.start()).map_struct_name(|variant_name| {
1481                         name.push_str(variant_name);
1482                     });
1483
1484                     // Create the (singleton) list of descriptions of union members.
1485                     vec![
1486                         MemberDescription {
1487                             name,
1488                             type_metadata: variant_type_metadata,
1489                             offset: Size::ZERO,
1490                             size: variant.size,
1491                             align: variant.align.abi,
1492                             flags: DIFlags::FlagZero,
1493                             discriminant: None,
1494                         }
1495                     ]
1496                 } else {
1497                     variants.iter_enumerated().map(|(i, _)| {
1498                         let variant = self.layout.for_variant(cx, i);
1499                         let variant_info = variant_info_for(i);
1500                         let (variant_type_metadata, member_desc_factory) =
1501                             describe_enum_variant(cx,
1502                                                   variant,
1503                                                   variant_info,
1504                                                   OptimizedDiscriminant,
1505                                                   self_metadata,
1506                                                   self.span);
1507
1508                         let member_descriptions = member_desc_factory
1509                             .create_member_descriptions(cx);
1510
1511                         set_members_of_composite_type(cx,
1512                                                       self.enum_type,
1513                                                       variant_type_metadata,
1514                                                       member_descriptions);
1515
1516                         let niche_value = if i == dataful_variant {
1517                             None
1518                         } else {
1519                             let value = (i.as_u32() as u128)
1520                                 .wrapping_sub(niche_variants.start().as_u32() as u128)
1521                                 .wrapping_add(niche_start);
1522                             let value = truncate(value, discr.value.size(cx));
1523                             // NOTE(eddyb) do *NOT* remove this assert, until
1524                             // we pass the full 128-bit value to LLVM, otherwise
1525                             // truncation will be silent and remain undetected.
1526                             assert_eq!(value as u64 as u128, value);
1527                             Some(value as u64)
1528                         };
1529
1530                         MemberDescription {
1531                             name: variant_info.variant_name(),
1532                             type_metadata: variant_type_metadata,
1533                             offset: Size::ZERO,
1534                             size: self.layout.size,
1535                             align: self.layout.align.abi,
1536                             flags: DIFlags::FlagZero,
1537                             discriminant: niche_value,
1538                         }
1539                     }).collect()
1540                 }
1541             }
1542         }
1543     }
1544 }
1545
1546 // Creates MemberDescriptions for the fields of a single enum variant.
1547 struct VariantMemberDescriptionFactory<'ll, 'tcx> {
1548     // Cloned from the layout::Struct describing the variant.
1549     offsets: Vec<layout::Size>,
1550     args: Vec<(String, Ty<'tcx>)>,
1551     discriminant_type_metadata: Option<&'ll DIType>,
1552     span: Span,
1553 }
1554
1555 impl VariantMemberDescriptionFactory<'ll, 'tcx> {
1556     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1557                                       -> Vec<MemberDescription<'ll>> {
1558         self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1559             let (size, align) = cx.size_and_align_of(ty);
1560             MemberDescription {
1561                 name: name.to_string(),
1562                 type_metadata: if use_enum_fallback(cx) {
1563                     match self.discriminant_type_metadata {
1564                         // Discriminant is always the first field of our variant
1565                         // when using the enum fallback.
1566                         Some(metadata) if i == 0 => metadata,
1567                         _ => type_metadata(cx, ty, self.span)
1568                     }
1569                 } else {
1570                     type_metadata(cx, ty, self.span)
1571                 },
1572                 offset: self.offsets[i],
1573                 size,
1574                 align,
1575                 flags: DIFlags::FlagZero,
1576                 discriminant: None,
1577             }
1578         }).collect()
1579     }
1580 }
1581
1582 #[derive(Copy, Clone)]
1583 enum EnumDiscriminantInfo<'ll> {
1584     RegularDiscriminant{ discr_field: Field, discr_type_metadata: &'ll DIType },
1585     OptimizedDiscriminant,
1586     NoDiscriminant
1587 }
1588
1589 #[derive(Copy, Clone)]
1590 enum VariantInfo<'tcx> {
1591     Adt(&'tcx ty::VariantDef),
1592     Generator(ty::GeneratorSubsts<'tcx>, &'tcx GeneratorLayout<'tcx>, VariantIdx),
1593 }
1594
1595 impl<'tcx> VariantInfo<'tcx> {
1596     fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1597         match self {
1598             VariantInfo::Adt(variant) => f(&variant.ident.as_str()),
1599             VariantInfo::Generator(substs, _, variant_index) =>
1600                 f(&substs.variant_name(*variant_index)),
1601         }
1602     }
1603
1604     fn variant_name(&self) -> String {
1605         match self {
1606             VariantInfo::Adt(variant) => variant.ident.to_string(),
1607             VariantInfo::Generator(_, _, variant_index) => {
1608                 // Since GDB currently prints out the raw discriminant along
1609                 // with every variant, make each variant name be just the value
1610                 // of the discriminant. The struct name for the variant includes
1611                 // the actual variant description.
1612                 format!("{}", variant_index.as_usize()).to_string()
1613             }
1614         }
1615     }
1616
1617     fn field_name(&self, i: usize) -> String {
1618         let field_name = match self {
1619             VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn =>
1620                 Some(variant.fields[i].ident.to_string()),
1621             VariantInfo::Generator(_, generator_layout, variant_index) => {
1622                 let field = generator_layout.variant_fields[*variant_index][i.into()];
1623                 let decl = &generator_layout.__local_debuginfo_codegen_only_do_not_use[field];
1624                 decl.name.map(|name| name.to_string())
1625             }
1626             _ => None,
1627         };
1628         field_name.unwrap_or_else(|| format!("__{}", i))
1629     }
1630 }
1631
1632 // Returns a tuple of (1) type_metadata_stub of the variant, (2) a
1633 // MemberDescriptionFactory for producing the descriptions of the
1634 // fields of the variant. This is a rudimentary version of a full
1635 // RecursiveTypeDescription.
1636 fn describe_enum_variant(
1637     cx: &CodegenCx<'ll, 'tcx>,
1638     layout: layout::TyLayout<'tcx>,
1639     variant: VariantInfo<'tcx>,
1640     discriminant_info: EnumDiscriminantInfo<'ll>,
1641     containing_scope: &'ll DIScope,
1642     span: Span,
1643 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1644     let metadata_stub = variant.map_struct_name(|variant_name| {
1645         let unique_type_id = debug_context(cx).type_map
1646                                               .borrow_mut()
1647                                               .get_unique_type_id_of_enum_variant(
1648                                                   cx,
1649                                                   layout.ty,
1650                                                   &variant_name);
1651         create_struct_stub(cx,
1652                            layout.ty,
1653                            &variant_name,
1654                            unique_type_id,
1655                            Some(containing_scope))
1656     });
1657
1658     // Build an array of (field name, field type) pairs to be captured in the factory closure.
1659     let (offsets, args) = if use_enum_fallback(cx) {
1660         // If this is not a univariant enum, there is also the discriminant field.
1661         let (discr_offset, discr_arg) = match discriminant_info {
1662             RegularDiscriminant { discr_field, .. } => {
1663                 // We have the layout of an enum variant, we need the layout of the outer enum
1664                 let enum_layout = cx.layout_of(layout.ty);
1665                 let offset = enum_layout.fields.offset(discr_field.as_usize());
1666                 let args = (
1667                     "RUST$ENUM$DISR".to_owned(),
1668                     enum_layout.field(cx, discr_field.as_usize()).ty);
1669                 (Some(offset), Some(args))
1670             }
1671             _ => (None, None),
1672         };
1673         (
1674             discr_offset.into_iter().chain((0..layout.fields.count()).map(|i| {
1675                 layout.fields.offset(i)
1676             })).collect(),
1677             discr_arg.into_iter().chain((0..layout.fields.count()).map(|i| {
1678                 (variant.field_name(i), layout.field(cx, i).ty)
1679             })).collect()
1680         )
1681     } else {
1682         (
1683             (0..layout.fields.count()).map(|i| {
1684                 layout.fields.offset(i)
1685             }).collect(),
1686             (0..layout.fields.count()).map(|i| {
1687                 (variant.field_name(i), layout.field(cx, i).ty)
1688             }).collect()
1689         )
1690     };
1691
1692     let member_description_factory =
1693         VariantMDF(VariantMemberDescriptionFactory {
1694             offsets,
1695             args,
1696             discriminant_type_metadata: match discriminant_info {
1697                 RegularDiscriminant { discr_type_metadata, .. } => {
1698                     Some(discr_type_metadata)
1699                 }
1700                 _ => None
1701             },
1702             span,
1703         });
1704
1705     (metadata_stub, member_description_factory)
1706 }
1707
1708 fn prepare_enum_metadata(
1709     cx: &CodegenCx<'ll, 'tcx>,
1710     enum_type: Ty<'tcx>,
1711     enum_def_id: DefId,
1712     unique_type_id: UniqueTypeId,
1713     span: Span,
1714     outer_field_tys: Vec<Ty<'tcx>>,
1715 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1716     let enum_name = compute_debuginfo_type_name(cx.tcx, enum_type, false);
1717
1718     let containing_scope = get_namespace_for_item(cx, enum_def_id);
1719     // FIXME: This should emit actual file metadata for the enum, but we
1720     // currently can't get the necessary information when it comes to types
1721     // imported from other crates. Formerly we violated the ODR when performing
1722     // LTO because we emitted debuginfo for the same type with varying file
1723     // metadata, so as a workaround we pretend that the type comes from
1724     // <unknown>
1725     let file_metadata = unknown_file_metadata(cx);
1726
1727     let discriminant_type_metadata = |discr: layout::Primitive| {
1728         let enumerators_metadata: Vec<_> = match enum_type.sty {
1729             ty::Adt(def, _) => def
1730                 .discriminants(cx.tcx)
1731                 .zip(&def.variants)
1732                 .map(|((_, discr), v)| {
1733                     let name = SmallCStr::new(&v.ident.as_str());
1734                     unsafe {
1735                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1736                             DIB(cx),
1737                             name.as_ptr(),
1738                             // FIXME: what if enumeration has i128 discriminant?
1739                             discr.val as u64))
1740                     }
1741                 })
1742                 .collect(),
1743             ty::Generator(_, substs, _) => substs
1744                 .variant_range(enum_def_id, cx.tcx)
1745                 .map(|variant_index| {
1746                     let name = SmallCStr::new(&substs.variant_name(variant_index));
1747                     unsafe {
1748                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1749                             DIB(cx),
1750                             name.as_ptr(),
1751                             // FIXME: what if enumeration has i128 discriminant?
1752                             variant_index.as_usize() as u64))
1753                     }
1754                 })
1755                 .collect(),
1756             _ => bug!(),
1757         };
1758
1759         let disr_type_key = (enum_def_id, discr);
1760         let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1761                                                                  .borrow()
1762                                                                  .get(&disr_type_key).cloned();
1763         match cached_discriminant_type_metadata {
1764             Some(discriminant_type_metadata) => discriminant_type_metadata,
1765             None => {
1766                 let (discriminant_size, discriminant_align) =
1767                     (discr.size(cx), discr.align(cx));
1768                 let discriminant_base_type_metadata =
1769                     type_metadata(cx, discr.to_ty(cx.tcx), syntax_pos::DUMMY_SP);
1770
1771                 let discriminant_name = match enum_type.sty {
1772                     ty::Adt(..) => SmallCStr::new(&cx.tcx.item_name(enum_def_id).as_str()),
1773                     ty::Generator(..) => SmallCStr::new(&enum_name),
1774                     _ => bug!(),
1775                 };
1776
1777                 let discriminant_type_metadata = unsafe {
1778                     llvm::LLVMRustDIBuilderCreateEnumerationType(
1779                         DIB(cx),
1780                         containing_scope,
1781                         discriminant_name.as_ptr(),
1782                         file_metadata,
1783                         UNKNOWN_LINE_NUMBER,
1784                         discriminant_size.bits(),
1785                         discriminant_align.abi.bits() as u32,
1786                         create_DIArray(DIB(cx), &enumerators_metadata),
1787                         discriminant_base_type_metadata, true)
1788                 };
1789
1790                 debug_context(cx).created_enum_disr_types
1791                                  .borrow_mut()
1792                                  .insert(disr_type_key, discriminant_type_metadata);
1793
1794                 discriminant_type_metadata
1795             }
1796         }
1797     };
1798
1799     let layout = cx.layout_of(enum_type);
1800
1801     match (&layout.abi, &layout.variants) {
1802         (&layout::Abi::Scalar(_), &layout::Variants::Multiple {
1803             discr_kind: layout::DiscriminantKind::Tag,
1804             ref discr,
1805             ..
1806         }) => return FinalMetadata(discriminant_type_metadata(discr.value)),
1807         _ => {}
1808     }
1809
1810     let enum_name = SmallCStr::new(&enum_name);
1811     let unique_type_id_str = SmallCStr::new(
1812         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
1813     );
1814
1815     if use_enum_fallback(cx) {
1816         let discriminant_type_metadata = match layout.variants {
1817             layout::Variants::Single { .. } |
1818             layout::Variants::Multiple {
1819                 discr_kind: layout::DiscriminantKind::Niche { .. },
1820                 ..
1821             } => None,
1822             layout::Variants::Multiple {
1823                 discr_kind: layout::DiscriminantKind::Tag,
1824                 ref discr,
1825                 ..
1826             } => {
1827                 Some(discriminant_type_metadata(discr.value))
1828             }
1829         };
1830
1831         let enum_metadata = unsafe {
1832             llvm::LLVMRustDIBuilderCreateUnionType(
1833                 DIB(cx),
1834                 containing_scope,
1835                 enum_name.as_ptr(),
1836                 file_metadata,
1837                 UNKNOWN_LINE_NUMBER,
1838                 layout.size.bits(),
1839                 layout.align.abi.bits() as u32,
1840                 DIFlags::FlagZero,
1841                 None,
1842                 0, // RuntimeLang
1843                 unique_type_id_str.as_ptr())
1844         };
1845
1846         return create_and_register_recursive_type_forward_declaration(
1847             cx,
1848             enum_type,
1849             unique_type_id,
1850             enum_metadata,
1851             enum_metadata,
1852             EnumMDF(EnumMemberDescriptionFactory {
1853                 enum_type,
1854                 layout,
1855                 discriminant_type_metadata,
1856                 containing_scope,
1857                 span,
1858             }),
1859         );
1860     }
1861
1862     let discriminator_name = match &enum_type.sty {
1863         ty::Generator(..) => Some(SmallCStr::new(&"__state")),
1864         _ => None,
1865     };
1866     let discriminator_name = discriminator_name.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut());
1867     let discriminator_metadata = match layout.variants {
1868         // A single-variant enum has no discriminant.
1869         layout::Variants::Single { .. } => None,
1870
1871         layout::Variants::Multiple {
1872             discr_kind: layout::DiscriminantKind::Niche { .. },
1873             ref discr,
1874             discr_index,
1875             ..
1876         } => {
1877             // Find the integer type of the correct size.
1878             let size = discr.value.size(cx);
1879             let align = discr.value.align(cx);
1880
1881             let discr_type = match discr.value {
1882                 layout::Int(t, _) => t,
1883                 layout::Float(layout::FloatTy::F32) => Integer::I32,
1884                 layout::Float(layout::FloatTy::F64) => Integer::I64,
1885                 layout::Pointer => cx.data_layout().ptr_sized_integer(),
1886             }.to_ty(cx.tcx, false);
1887
1888             let discr_metadata = basic_type_metadata(cx, discr_type);
1889             unsafe {
1890                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1891                     DIB(cx),
1892                     containing_scope,
1893                     discriminator_name,
1894                     file_metadata,
1895                     UNKNOWN_LINE_NUMBER,
1896                     size.bits(),
1897                     align.abi.bits() as u32,
1898                     layout.fields.offset(discr_index).bits(),
1899                     DIFlags::FlagArtificial,
1900                     discr_metadata))
1901             }
1902         },
1903
1904         layout::Variants::Multiple {
1905             discr_kind: layout::DiscriminantKind::Tag,
1906             ref discr,
1907             discr_index,
1908             ..
1909         } => {
1910             let discr_type = discr.value.to_ty(cx.tcx);
1911             let (size, align) = cx.size_and_align_of(discr_type);
1912
1913             let discr_metadata = basic_type_metadata(cx, discr_type);
1914             unsafe {
1915                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1916                     DIB(cx),
1917                     containing_scope,
1918                     discriminator_name,
1919                     file_metadata,
1920                     UNKNOWN_LINE_NUMBER,
1921                     size.bits(),
1922                     align.bits() as u32,
1923                     layout.fields.offset(discr_index).bits(),
1924                     DIFlags::FlagArtificial,
1925                     discr_metadata))
1926             }
1927         },
1928     };
1929
1930     let mut outer_fields = match layout.variants {
1931         layout::Variants::Single { .. } => vec![],
1932         layout::Variants::Multiple { .. } => {
1933             let tuple_mdf = TupleMemberDescriptionFactory {
1934                 ty: enum_type,
1935                 component_types: outer_field_tys,
1936                 span
1937             };
1938             tuple_mdf
1939                 .create_member_descriptions(cx)
1940                 .into_iter()
1941                 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
1942                 .collect()
1943         }
1944     };
1945
1946     let variant_part_unique_type_id_str = SmallCStr::new(
1947         debug_context(cx).type_map
1948             .borrow_mut()
1949             .get_unique_type_id_str_of_enum_variant_part(unique_type_id)
1950     );
1951     let empty_array = create_DIArray(DIB(cx), &[]);
1952     let variant_part = unsafe {
1953         llvm::LLVMRustDIBuilderCreateVariantPart(
1954             DIB(cx),
1955             containing_scope,
1956             ptr::null_mut(),
1957             file_metadata,
1958             UNKNOWN_LINE_NUMBER,
1959             layout.size.bits(),
1960             layout.align.abi.bits() as u32,
1961             DIFlags::FlagZero,
1962             discriminator_metadata,
1963             empty_array,
1964             variant_part_unique_type_id_str.as_ptr())
1965     };
1966     outer_fields.push(Some(variant_part));
1967
1968     // The variant part must be wrapped in a struct according to DWARF.
1969     let type_array = create_DIArray(DIB(cx), &outer_fields);
1970     let struct_wrapper = unsafe {
1971         llvm::LLVMRustDIBuilderCreateStructType(
1972             DIB(cx),
1973             Some(containing_scope),
1974             enum_name.as_ptr(),
1975             file_metadata,
1976             UNKNOWN_LINE_NUMBER,
1977             layout.size.bits(),
1978             layout.align.abi.bits() as u32,
1979             DIFlags::FlagZero,
1980             None,
1981             type_array,
1982             0,
1983             None,
1984             unique_type_id_str.as_ptr())
1985     };
1986
1987     return create_and_register_recursive_type_forward_declaration(
1988         cx,
1989         enum_type,
1990         unique_type_id,
1991         struct_wrapper,
1992         variant_part,
1993         EnumMDF(EnumMemberDescriptionFactory {
1994             enum_type,
1995             layout,
1996             discriminant_type_metadata: None,
1997             containing_scope,
1998             span,
1999         }),
2000     );
2001 }
2002
2003 /// Creates debug information for a composite type, that is, anything that
2004 /// results in a LLVM struct.
2005 ///
2006 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2007 fn composite_type_metadata(
2008     cx: &CodegenCx<'ll, 'tcx>,
2009     composite_type: Ty<'tcx>,
2010     composite_type_name: &str,
2011     composite_type_unique_id: UniqueTypeId,
2012     member_descriptions: Vec<MemberDescription<'ll>>,
2013     containing_scope: Option<&'ll DIScope>,
2014
2015     // Ignore source location information as long as it
2016     // can't be reconstructed for non-local crates.
2017     _file_metadata: &'ll DIFile,
2018     _definition_span: Span,
2019 ) -> &'ll DICompositeType {
2020     // Create the (empty) struct metadata node ...
2021     let composite_type_metadata = create_struct_stub(cx,
2022                                                      composite_type,
2023                                                      composite_type_name,
2024                                                      composite_type_unique_id,
2025                                                      containing_scope);
2026     // ... and immediately create and add the member descriptions.
2027     set_members_of_composite_type(cx,
2028                                   composite_type,
2029                                   composite_type_metadata,
2030                                   member_descriptions);
2031
2032     composite_type_metadata
2033 }
2034
2035 fn set_members_of_composite_type(cx: &CodegenCx<'ll, 'tcx>,
2036                                  composite_type: Ty<'tcx>,
2037                                  composite_type_metadata: &'ll DICompositeType,
2038                                  member_descriptions: Vec<MemberDescription<'ll>>) {
2039     // In some rare cases LLVM metadata uniquing would lead to an existing type
2040     // description being used instead of a new one created in
2041     // create_struct_stub. This would cause a hard to trace assertion in
2042     // DICompositeType::SetTypeArray(). The following check makes sure that we
2043     // get a better error message if this should happen again due to some
2044     // regression.
2045     {
2046         let mut composite_types_completed =
2047             debug_context(cx).composite_types_completed.borrow_mut();
2048         if composite_types_completed.contains(&composite_type_metadata) {
2049             bug!("debuginfo::set_members_of_composite_type() - \
2050                   Already completed forward declaration re-encountered.");
2051         } else {
2052             composite_types_completed.insert(composite_type_metadata);
2053         }
2054     }
2055
2056     let member_metadata: Vec<_> = member_descriptions
2057         .into_iter()
2058         .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2059         .collect();
2060
2061     let type_params = compute_type_parameters(cx, composite_type);
2062     unsafe {
2063         let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
2064         llvm::LLVMRustDICompositeTypeReplaceArrays(
2065             DIB(cx), composite_type_metadata, Some(type_array), type_params);
2066     }
2067 }
2068
2069 // Compute the type parameters for a type, if any, for the given
2070 // metadata.
2071 fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> Option<&'ll DIArray> {
2072     if let ty::Adt(def, substs) = ty.sty {
2073         if !substs.types().next().is_none() {
2074             let generics = cx.tcx.generics_of(def.did);
2075             let names = get_parameter_names(cx, generics);
2076             let template_params: Vec<_> = substs.iter().zip(names).filter_map(|(kind, name)| {
2077                 if let UnpackedKind::Type(ty) = kind.unpack() {
2078                     let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2079                     let actual_type_metadata =
2080                         type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
2081                     let name = SmallCStr::new(&name.as_str());
2082                     Some(unsafe {
2083
2084                         Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2085                             DIB(cx),
2086                             None,
2087                             name.as_ptr(),
2088                             actual_type_metadata,
2089                             unknown_file_metadata(cx),
2090                             0,
2091                             0,
2092                         ))
2093                     })
2094                 } else {
2095                     None
2096                 }
2097             }).collect();
2098
2099             return Some(create_DIArray(DIB(cx), &template_params[..]));
2100         }
2101     }
2102     return Some(create_DIArray(DIB(cx), &[]));
2103
2104     fn get_parameter_names(cx: &CodegenCx<'_, '_>,
2105                            generics: &ty::Generics)
2106                            -> Vec<InternedString> {
2107         let mut names = generics.parent.map_or(vec![], |def_id| {
2108             get_parameter_names(cx, cx.tcx.generics_of(def_id))
2109         });
2110         names.extend(generics.params.iter().map(|param| param.name));
2111         names
2112     }
2113 }
2114
2115 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
2116 // any caching, does not add any fields to the struct. This can be done later
2117 // with set_members_of_composite_type().
2118 fn create_struct_stub(
2119     cx: &CodegenCx<'ll, 'tcx>,
2120     struct_type: Ty<'tcx>,
2121     struct_type_name: &str,
2122     unique_type_id: UniqueTypeId,
2123     containing_scope: Option<&'ll DIScope>,
2124 ) -> &'ll DICompositeType {
2125     let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2126
2127     let name = SmallCStr::new(struct_type_name);
2128     let unique_type_id = SmallCStr::new(
2129         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
2130     );
2131     let metadata_stub = unsafe {
2132         // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
2133         // pointer will lead to hard to trace and debug LLVM assertions
2134         // later on in llvm/lib/IR/Value.cpp.
2135         let empty_array = create_DIArray(DIB(cx), &[]);
2136
2137         llvm::LLVMRustDIBuilderCreateStructType(
2138             DIB(cx),
2139             containing_scope,
2140             name.as_ptr(),
2141             unknown_file_metadata(cx),
2142             UNKNOWN_LINE_NUMBER,
2143             struct_size.bits(),
2144             struct_align.bits() as u32,
2145             DIFlags::FlagZero,
2146             None,
2147             empty_array,
2148             0,
2149             None,
2150             unique_type_id.as_ptr())
2151     };
2152
2153     metadata_stub
2154 }
2155
2156 fn create_union_stub(
2157     cx: &CodegenCx<'ll, 'tcx>,
2158     union_type: Ty<'tcx>,
2159     union_type_name: &str,
2160     unique_type_id: UniqueTypeId,
2161     containing_scope: &'ll DIScope,
2162 ) -> &'ll DICompositeType {
2163     let (union_size, union_align) = cx.size_and_align_of(union_type);
2164
2165     let name = SmallCStr::new(union_type_name);
2166     let unique_type_id = SmallCStr::new(
2167         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
2168     );
2169     let metadata_stub = unsafe {
2170         // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
2171         // pointer will lead to hard to trace and debug LLVM assertions
2172         // later on in llvm/lib/IR/Value.cpp.
2173         let empty_array = create_DIArray(DIB(cx), &[]);
2174
2175         llvm::LLVMRustDIBuilderCreateUnionType(
2176             DIB(cx),
2177             containing_scope,
2178             name.as_ptr(),
2179             unknown_file_metadata(cx),
2180             UNKNOWN_LINE_NUMBER,
2181             union_size.bits(),
2182             union_align.bits() as u32,
2183             DIFlags::FlagZero,
2184             Some(empty_array),
2185             0, // RuntimeLang
2186             unique_type_id.as_ptr())
2187     };
2188
2189     metadata_stub
2190 }
2191
2192 /// Creates debug information for the given global variable.
2193 ///
2194 /// Adds the created metadata nodes directly to the crate's IR.
2195 pub fn create_global_var_metadata(
2196     cx: &CodegenCx<'ll, '_>,
2197     def_id: DefId,
2198     global: &'ll Value,
2199 ) {
2200     if cx.dbg_cx.is_none() {
2201         return;
2202     }
2203
2204     let tcx = cx.tcx;
2205     let attrs = tcx.codegen_fn_attrs(def_id);
2206
2207     if attrs.flags.contains(CodegenFnAttrFlags::NO_DEBUG) {
2208         return;
2209     }
2210
2211     let no_mangle = attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE);
2212     // We may want to remove the namespace scope if we're in an extern block, see:
2213     // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952
2214     let var_scope = get_namespace_for_item(cx, def_id);
2215     let span = tcx.def_span(def_id);
2216
2217     let (file_metadata, line_number) = if !span.is_dummy() {
2218         let loc = span_start(cx, span);
2219         (file_metadata(cx, &loc.file.name, LOCAL_CRATE), loc.line as c_uint)
2220     } else {
2221         (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2222     };
2223
2224     let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2225     let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx);
2226     let type_metadata = type_metadata(cx, variable_type, span);
2227     let var_name = SmallCStr::new(&tcx.item_name(def_id).as_str());
2228     let linkage_name = if no_mangle {
2229         None
2230     } else {
2231         let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id));
2232         Some(SmallCStr::new(&linkage_name.as_str()))
2233     };
2234
2235     let global_align = cx.align_of(variable_type);
2236
2237     unsafe {
2238         llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
2239                                                     Some(var_scope),
2240                                                     var_name.as_ptr(),
2241                                                     // If null, linkage_name field is omitted,
2242                                                     // which is what we want for no_mangle statics
2243                                                     linkage_name.as_ref()
2244                                                      .map_or(ptr::null(), |name| name.as_ptr()),
2245                                                     file_metadata,
2246                                                     line_number,
2247                                                     type_metadata,
2248                                                     is_local_to_unit,
2249                                                     global,
2250                                                     None,
2251                                                     global_align.bytes() as u32,
2252         );
2253     }
2254 }
2255
2256 /// Creates debug information for the given vtable, which is for the
2257 /// given type.
2258 ///
2259 /// Adds the created metadata nodes directly to the crate's IR.
2260 pub fn create_vtable_metadata(
2261     cx: &CodegenCx<'ll, 'tcx>,
2262     ty: ty::Ty<'tcx>,
2263     vtable: &'ll Value,
2264 ) {
2265     if cx.dbg_cx.is_none() {
2266         return;
2267     }
2268
2269     let type_metadata = type_metadata(cx, ty, syntax_pos::DUMMY_SP);
2270
2271     unsafe {
2272         // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
2273         // pointer will lead to hard to trace and debug LLVM assertions
2274         // later on in llvm/lib/IR/Value.cpp.
2275         let empty_array = create_DIArray(DIB(cx), &[]);
2276
2277         let name = const_cstr!("vtable");
2278
2279         // Create a new one each time.  We don't want metadata caching
2280         // here, because each vtable will refer to a unique containing
2281         // type.
2282         let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
2283             DIB(cx),
2284             NO_SCOPE_METADATA,
2285             name.as_ptr(),
2286             unknown_file_metadata(cx),
2287             UNKNOWN_LINE_NUMBER,
2288             Size::ZERO.bits(),
2289             cx.tcx.data_layout.pointer_align.abi.bits() as u32,
2290             DIFlags::FlagArtificial,
2291             None,
2292             empty_array,
2293             0,
2294             Some(type_metadata),
2295             name.as_ptr()
2296         );
2297
2298         llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
2299                                                     NO_SCOPE_METADATA,
2300                                                     name.as_ptr(),
2301                                                     ptr::null(),
2302                                                     unknown_file_metadata(cx),
2303                                                     UNKNOWN_LINE_NUMBER,
2304                                                     vtable_type,
2305                                                     true,
2306                                                     vtable,
2307                                                     None,
2308                                                     0);
2309     }
2310 }
2311
2312 // Creates an "extension" of an existing DIScope into another file.
2313 pub fn extend_scope_to_file(
2314     cx: &CodegenCx<'ll, '_>,
2315     scope_metadata: &'ll DIScope,
2316     file: &syntax_pos::SourceFile,
2317     defining_crate: CrateNum,
2318 ) -> &'ll DILexicalBlock {
2319     let file_metadata = file_metadata(cx, &file.name, defining_crate);
2320     unsafe {
2321         llvm::LLVMRustDIBuilderCreateLexicalBlockFile(
2322             DIB(cx),
2323             scope_metadata,
2324             file_metadata)
2325     }
2326 }