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