]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/debuginfo/metadata.rs
run EndRegion when unwinding otherwise-empty scopes
[rust.git] / src / librustc_trans / debuginfo / metadata.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use self::RecursiveTypeDescription::*;
12 use self::MemberOffset::*;
13 use self::MemberDescriptionFactory::*;
14 use self::EnumDiscriminantInfo::*;
15
16 use super::utils::{debug_context, DIB, span_start, bytes_to_bits, size_and_align_of,
17                    get_namespace_for_item, create_DIArray, is_node_local_to_unit};
18 use super::namespace::mangled_name_of_item;
19 use super::type_names::compute_debuginfo_type_name;
20 use super::{CrateDebugContext};
21 use context::SharedCrateContext;
22
23 use llvm::{self, ValueRef};
24 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor,
25                       DICompositeType, DILexicalBlock, DIFlags};
26
27 use rustc::hir::def::CtorKind;
28 use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
29 use rustc::ty::fold::TypeVisitor;
30 use rustc::ty::subst::Substs;
31 use rustc::ty::util::TypeIdHasher;
32 use rustc::hir;
33 use rustc_data_structures::ToHex;
34 use {type_of, machine, monomorphize};
35 use common::{self, CrateContext};
36 use type_::Type;
37 use rustc::ty::{self, AdtKind, Ty};
38 use rustc::ty::layout::{self, LayoutTyper};
39 use rustc::session::{Session, config};
40 use rustc::util::nodemap::FxHashMap;
41 use rustc::util::common::path2cstr;
42
43 use libc::{c_uint, c_longlong};
44 use std::ffi::CString;
45 use std::ptr;
46 use std::path::Path;
47 use syntax::ast;
48 use syntax::symbol::{Interner, InternedString, Symbol};
49 use syntax_pos::{self, Span};
50
51
52 // From DWARF 5.
53 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
54 const DW_LANG_RUST: c_uint = 0x1c;
55 #[allow(non_upper_case_globals)]
56 const DW_ATE_boolean: c_uint = 0x02;
57 #[allow(non_upper_case_globals)]
58 const DW_ATE_float: c_uint = 0x04;
59 #[allow(non_upper_case_globals)]
60 const DW_ATE_signed: c_uint = 0x05;
61 #[allow(non_upper_case_globals)]
62 const DW_ATE_unsigned: c_uint = 0x07;
63 #[allow(non_upper_case_globals)]
64 const DW_ATE_unsigned_char: c_uint = 0x08;
65
66 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
67 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
68
69 // ptr::null() doesn't work :(
70 pub const NO_SCOPE_METADATA: DIScope = (0 as DIScope);
71
72 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
73 pub struct UniqueTypeId(ast::Name);
74
75 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
76 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
77 // faster lookup, also by Ty. The TypeMap is responsible for creating
78 // UniqueTypeIds.
79 pub struct TypeMap<'tcx> {
80     // The UniqueTypeIds created so far
81     unique_id_interner: Interner,
82     // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
83     unique_id_to_metadata: FxHashMap<UniqueTypeId, DIType>,
84     // A map from types to debuginfo metadata. This is a N:1 mapping.
85     type_to_metadata: FxHashMap<Ty<'tcx>, DIType>,
86     // A map from types to UniqueTypeId. This is a N:1 mapping.
87     type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>
88 }
89
90 impl<'tcx> TypeMap<'tcx> {
91     pub fn new() -> TypeMap<'tcx> {
92         TypeMap {
93             unique_id_interner: Interner::new(),
94             type_to_metadata: FxHashMap(),
95             unique_id_to_metadata: FxHashMap(),
96             type_to_unique_id: FxHashMap(),
97         }
98     }
99
100     // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
101     // the mapping already exists.
102     fn register_type_with_metadata<'a>(&mut self,
103                                        type_: Ty<'tcx>,
104                                        metadata: DIType) {
105         if self.type_to_metadata.insert(type_, metadata).is_some() {
106             bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
107         }
108     }
109
110     // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
111     // fail if the mapping already exists.
112     fn register_unique_id_with_metadata(&mut self,
113                                         unique_type_id: UniqueTypeId,
114                                         metadata: DIType) {
115         if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
116             bug!("Type metadata for unique id '{}' is already in the TypeMap!",
117                  self.get_unique_type_id_as_string(unique_type_id));
118         }
119     }
120
121     fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
122         self.type_to_metadata.get(&type_).cloned()
123     }
124
125     fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<DIType> {
126         self.unique_id_to_metadata.get(&unique_type_id).cloned()
127     }
128
129     // Get the string representation of a UniqueTypeId. This method will fail if
130     // the id is unknown.
131     fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
132         let UniqueTypeId(interner_key) = unique_type_id;
133         self.unique_id_interner.get(interner_key)
134     }
135
136     // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
137     // type has been requested before, this is just a table lookup. Otherwise an
138     // ID will be generated and stored for later lookup.
139     fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
140                                       type_: Ty<'tcx>) -> UniqueTypeId {
141         // Let's see if we already have something in the cache
142         match self.type_to_unique_id.get(&type_).cloned() {
143             Some(unique_type_id) => return unique_type_id,
144             None => { /* generate one */}
145         };
146
147         // The hasher we are using to generate the UniqueTypeId. We want
148         // something that provides more than the 64 bits of the DefaultHasher.
149
150         let mut type_id_hasher = TypeIdHasher::<[u8; 20]>::new(cx.tcx());
151         type_id_hasher.visit_ty(type_);
152
153         let unique_type_id = type_id_hasher.finish().to_hex();
154         let key = self.unique_id_interner.intern(&unique_type_id);
155         self.type_to_unique_id.insert(type_, UniqueTypeId(key));
156
157         return UniqueTypeId(key);
158     }
159
160     // Get the UniqueTypeId for an enum variant. Enum variants are not really
161     // types of their own, so they need special handling. We still need a
162     // UniqueTypeId for them, since to debuginfo they *are* real types.
163     fn get_unique_type_id_of_enum_variant<'a>(&mut self,
164                                               cx: &CrateContext<'a, 'tcx>,
165                                               enum_type: Ty<'tcx>,
166                                               variant_name: &str)
167                                               -> UniqueTypeId {
168         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
169         let enum_variant_type_id = format!("{}::{}",
170                                            self.get_unique_type_id_as_string(enum_type_id),
171                                            variant_name);
172         let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
173         UniqueTypeId(interner_key)
174     }
175 }
176
177 // A description of some recursive type. It can either be already finished (as
178 // with FinalMetadata) or it is not yet finished, but contains all information
179 // needed to generate the missing parts of the description. See the
180 // documentation section on Recursive Types at the top of this file for more
181 // information.
182 enum RecursiveTypeDescription<'tcx> {
183     UnfinishedMetadata {
184         unfinished_type: Ty<'tcx>,
185         unique_type_id: UniqueTypeId,
186         metadata_stub: DICompositeType,
187         llvm_type: Type,
188         member_description_factory: MemberDescriptionFactory<'tcx>,
189     },
190     FinalMetadata(DICompositeType)
191 }
192
193 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
194     cx: &CrateContext<'a, 'tcx>,
195     unfinished_type: Ty<'tcx>,
196     unique_type_id: UniqueTypeId,
197     metadata_stub: DICompositeType,
198     llvm_type: Type,
199     member_description_factory: MemberDescriptionFactory<'tcx>)
200  -> RecursiveTypeDescription<'tcx> {
201
202     // Insert the stub into the TypeMap in order to allow for recursive references
203     let mut type_map = debug_context(cx).type_map.borrow_mut();
204     type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
205     type_map.register_type_with_metadata(unfinished_type, metadata_stub);
206
207     UnfinishedMetadata {
208         unfinished_type,
209         unique_type_id,
210         metadata_stub,
211         llvm_type,
212         member_description_factory,
213     }
214 }
215
216 impl<'tcx> RecursiveTypeDescription<'tcx> {
217     // Finishes up the description of the type in question (mostly by providing
218     // descriptions of the fields of the given type) and returns the final type
219     // metadata.
220     fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
221         match *self {
222             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
223             UnfinishedMetadata {
224                 unfinished_type,
225                 unique_type_id,
226                 metadata_stub,
227                 llvm_type,
228                 ref member_description_factory,
229                 ..
230             } => {
231                 // Make sure that we have a forward declaration of the type in
232                 // the TypeMap so that recursive references are possible. This
233                 // will always be the case if the RecursiveTypeDescription has
234                 // been properly created through the
235                 // create_and_register_recursive_type_forward_declaration()
236                 // function.
237                 {
238                     let type_map = debug_context(cx).type_map.borrow();
239                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
240                        type_map.find_metadata_for_type(unfinished_type).is_none() {
241                         bug!("Forward declaration of potentially recursive type \
242                               '{:?}' was not found in TypeMap!",
243                              unfinished_type);
244                     }
245                 }
246
247                 // ... then create the member descriptions ...
248                 let member_descriptions =
249                     member_description_factory.create_member_descriptions(cx);
250
251                 // ... and attach them to the stub to complete it.
252                 set_members_of_composite_type(cx,
253                                               metadata_stub,
254                                               llvm_type,
255                                               &member_descriptions[..]);
256                 return MetadataCreationResult::new(metadata_stub, true);
257             }
258         }
259     }
260 }
261
262 // Returns from the enclosing function if the type metadata with the given
263 // unique id can be found in the type map
264 macro_rules! return_if_metadata_created_in_meantime {
265     ($cx: expr, $unique_type_id: expr) => (
266         match debug_context($cx).type_map
267                                 .borrow()
268                                 .find_metadata_for_unique_id($unique_type_id) {
269             Some(metadata) => return MetadataCreationResult::new(metadata, true),
270             None => { /* proceed normally */ }
271         }
272     )
273 }
274
275 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
276                                 unique_type_id: UniqueTypeId,
277                                 element_type: Ty<'tcx>,
278                                 len: Option<u64>,
279                                 span: Span)
280                                 -> MetadataCreationResult {
281     let element_type_metadata = type_metadata(cx, element_type, span);
282
283     return_if_metadata_created_in_meantime!(cx, unique_type_id);
284
285     let element_llvm_type = type_of::type_of(cx, element_type);
286     let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
287
288     let (array_size_in_bytes, upper_bound) = match len {
289         Some(len) => (element_type_size * len, len as c_longlong),
290         None => (0, -1)
291     };
292
293     let subrange = unsafe {
294         llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
295     };
296
297     let subscripts = create_DIArray(DIB(cx), &[subrange]);
298     let metadata = unsafe {
299         llvm::LLVMRustDIBuilderCreateArrayType(
300             DIB(cx),
301             bytes_to_bits(array_size_in_bytes),
302             bytes_to_bits(element_type_align),
303             element_type_metadata,
304             subscripts)
305     };
306
307     return MetadataCreationResult::new(metadata, false);
308 }
309
310 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
311                                 vec_type: Ty<'tcx>,
312                                 element_type: Ty<'tcx>,
313                                 unique_type_id: UniqueTypeId,
314                                 span: Span)
315                                 -> MetadataCreationResult {
316     let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
317         ty: element_type,
318         mutbl: hir::MutImmutable
319     });
320
321     let element_type_metadata = type_metadata(cx, data_ptr_type, span);
322
323     return_if_metadata_created_in_meantime!(cx, unique_type_id);
324
325     let slice_llvm_type = type_of::type_of(cx, vec_type);
326     let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
327
328     let member_llvm_types = slice_llvm_type.field_types();
329     assert!(slice_layout_is_correct(cx,
330                                     &member_llvm_types[..],
331                                     element_type));
332     let member_descriptions = [
333         MemberDescription {
334             name: "data_ptr".to_string(),
335             llvm_type: member_llvm_types[0],
336             type_metadata: element_type_metadata,
337             offset: ComputedMemberOffset,
338             flags: DIFlags::FlagZero,
339         },
340         MemberDescription {
341             name: "length".to_string(),
342             llvm_type: member_llvm_types[1],
343             type_metadata: type_metadata(cx, cx.tcx().types.usize, span),
344             offset: ComputedMemberOffset,
345             flags: DIFlags::FlagZero,
346         },
347     ];
348
349     assert!(member_descriptions.len() == member_llvm_types.len());
350
351     let file_metadata = unknown_file_metadata(cx);
352
353     let metadata = composite_type_metadata(cx,
354                                            slice_llvm_type,
355                                            &slice_type_name[..],
356                                            unique_type_id,
357                                            &member_descriptions,
358                                            NO_SCOPE_METADATA,
359                                            file_metadata,
360                                            span);
361     return MetadataCreationResult::new(metadata, false);
362
363     fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
364                                          member_llvm_types: &[Type],
365                                          element_type: Ty<'tcx>)
366                                          -> bool {
367         member_llvm_types.len() == 2 &&
368         member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
369         member_llvm_types[1] == cx.isize_ty()
370     }
371 }
372
373 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
374                                       unique_type_id: UniqueTypeId,
375                                       signature: ty::PolyFnSig<'tcx>,
376                                       span: Span)
377                                       -> MetadataCreationResult
378 {
379     let signature = cx.tcx().erase_late_bound_regions_and_normalize(&signature);
380
381     let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs().len() + 1);
382
383     // return type
384     signature_metadata.push(match signature.output().sty {
385         ty::TyTuple(ref tys, _) if tys.is_empty() => ptr::null_mut(),
386         _ => type_metadata(cx, signature.output(), span)
387     });
388
389     // regular arguments
390     for &argument_type in signature.inputs() {
391         signature_metadata.push(type_metadata(cx, argument_type, span));
392     }
393
394     return_if_metadata_created_in_meantime!(cx, unique_type_id);
395
396     return MetadataCreationResult::new(
397         unsafe {
398             llvm::LLVMRustDIBuilderCreateSubroutineType(
399                 DIB(cx),
400                 unknown_file_metadata(cx),
401                 create_DIArray(DIB(cx), &signature_metadata[..]))
402         },
403         false);
404 }
405
406 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
407 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
408 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
409 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
410 // of a DST struct, there is no trait_object_type and the results of this
411 // function will be a little bit weird.
412 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
413                                     trait_type: Ty<'tcx>,
414                                     trait_object_type: Option<Ty<'tcx>>,
415                                     unique_type_id: UniqueTypeId)
416                                     -> DIType {
417     // The implementation provided here is a stub. It makes sure that the trait
418     // type is assigned the correct name, size, namespace, and source location.
419     // But it does not describe the trait's methods.
420
421     let containing_scope = match trait_type.sty {
422         ty::TyDynamic(ref data, ..) => if let Some(principal) = data.principal() {
423             let def_id = principal.def_id();
424             get_namespace_for_item(cx, def_id)
425         } else {
426             NO_SCOPE_METADATA
427         },
428         _ => {
429             bug!("debuginfo: Unexpected trait-object type in \
430                   trait_pointer_metadata(): {:?}",
431                  trait_type);
432         }
433     };
434
435     let trait_object_type = trait_object_type.unwrap_or(trait_type);
436     let trait_type_name =
437         compute_debuginfo_type_name(cx, trait_object_type, false);
438
439     let trait_llvm_type = type_of::type_of(cx, trait_object_type);
440     let file_metadata = unknown_file_metadata(cx);
441
442     composite_type_metadata(cx,
443                             trait_llvm_type,
444                             &trait_type_name[..],
445                             unique_type_id,
446                             &[],
447                             containing_scope,
448                             file_metadata,
449                             syntax_pos::DUMMY_SP)
450 }
451
452 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
453                                t: Ty<'tcx>,
454                                usage_site_span: Span)
455                                -> DIType {
456     // Get the unique type id of this type.
457     let unique_type_id = {
458         let mut type_map = debug_context(cx).type_map.borrow_mut();
459         // First, try to find the type in TypeMap. If we have seen it before, we
460         // can exit early here.
461         match type_map.find_metadata_for_type(t) {
462             Some(metadata) => {
463                 return metadata;
464             },
465             None => {
466                 // The Ty is not in the TypeMap but maybe we have already seen
467                 // an equivalent type (e.g. only differing in region arguments).
468                 // In order to find out, generate the unique type id and look
469                 // that up.
470                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
471                 match type_map.find_metadata_for_unique_id(unique_type_id) {
472                     Some(metadata) => {
473                         // There is already an equivalent type in the TypeMap.
474                         // Register this Ty as an alias in the cache and
475                         // return the cached metadata.
476                         type_map.register_type_with_metadata(t, metadata);
477                         return metadata;
478                     },
479                     None => {
480                         // There really is no type metadata for this type, so
481                         // proceed by creating it.
482                         unique_type_id
483                     }
484                 }
485             }
486         }
487     };
488
489     debug!("type_metadata: {:?}", t);
490
491     let ptr_metadata = |ty: Ty<'tcx>| {
492         match ty.sty {
493             ty::TySlice(typ) => {
494                 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
495             }
496             ty::TyStr => {
497                 Ok(vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span))
498             }
499             ty::TyDynamic(..) => {
500                 Ok(MetadataCreationResult::new(
501                     trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
502                     false))
503             }
504             _ => {
505                 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
506
507                 match debug_context(cx).type_map
508                                         .borrow()
509                                         .find_metadata_for_unique_id(unique_type_id) {
510                     Some(metadata) => return Err(metadata),
511                     None => { /* proceed normally */ }
512                 };
513
514                 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
515                    false))
516             }
517         }
518     };
519
520     let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.sty {
521         ty::TyNever    |
522         ty::TyBool     |
523         ty::TyChar     |
524         ty::TyInt(_)   |
525         ty::TyUint(_)  |
526         ty::TyFloat(_) => {
527             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
528         }
529         ty::TyTuple(ref elements, _) if elements.is_empty() => {
530             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
531         }
532         ty::TyArray(typ, len) => {
533             let len = len.val.to_const_int().unwrap().to_u64().unwrap();
534             fixed_vec_metadata(cx, unique_type_id, typ, Some(len), usage_site_span)
535         }
536         ty::TySlice(typ) => {
537             fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
538         }
539         ty::TyStr => {
540             fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
541         }
542         ty::TyDynamic(..) => {
543             MetadataCreationResult::new(
544                         trait_pointer_metadata(cx, t, None, unique_type_id),
545             false)
546         }
547         ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
548         ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
549             match ptr_metadata(ty) {
550                 Ok(res) => res,
551                 Err(metadata) => return metadata,
552             }
553         }
554         ty::TyAdt(def, _) if def.is_box() => {
555             match ptr_metadata(t.boxed_ty()) {
556                 Ok(res) => res,
557                 Err(metadata) => return metadata,
558             }
559         }
560         ty::TyFnDef(..) | ty::TyFnPtr(_) => {
561             let fn_metadata = subroutine_type_metadata(cx,
562                                                        unique_type_id,
563                                                        t.fn_sig(cx.tcx()),
564                                                        usage_site_span).metadata;
565             match debug_context(cx).type_map
566                                    .borrow()
567                                    .find_metadata_for_unique_id(unique_type_id) {
568                 Some(metadata) => return metadata,
569                 None => { /* proceed normally */ }
570             };
571
572             // This is actually a function pointer, so wrap it in pointer DI
573             MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
574
575         }
576         ty::TyClosure(def_id, substs) => {
577             let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx()).collect();
578             prepare_tuple_metadata(cx,
579                                    t,
580                                    &upvar_tys,
581                                    unique_type_id,
582                                    usage_site_span).finalize(cx)
583         }
584         ty::TyGenerator(def_id, substs, _) => {
585             let upvar_tys : Vec<_> = substs.field_tys(def_id, cx.tcx()).map(|t| {
586                 cx.tcx().normalize_associated_type(&t)
587             }).collect();
588             prepare_tuple_metadata(cx,
589                                    t,
590                                    &upvar_tys,
591                                    unique_type_id,
592                                    usage_site_span).finalize(cx)
593         }
594         ty::TyAdt(def, ..) => match def.adt_kind() {
595             AdtKind::Struct => {
596                 prepare_struct_metadata(cx,
597                                         t,
598                                         unique_type_id,
599                                         usage_site_span).finalize(cx)
600             }
601             AdtKind::Union => {
602                 prepare_union_metadata(cx,
603                                     t,
604                                     unique_type_id,
605                                     usage_site_span).finalize(cx)
606             }
607             AdtKind::Enum => {
608                 prepare_enum_metadata(cx,
609                                     t,
610                                     def.did,
611                                     unique_type_id,
612                                     usage_site_span).finalize(cx)
613             }
614         },
615         ty::TyTuple(ref elements, _) => {
616             prepare_tuple_metadata(cx,
617                                    t,
618                                    &elements[..],
619                                    unique_type_id,
620                                    usage_site_span).finalize(cx)
621         }
622         _ => {
623             bug!("debuginfo: unexpected type in type_metadata: {:?}", t)
624         }
625     };
626
627     {
628         let mut type_map = debug_context(cx).type_map.borrow_mut();
629
630         if already_stored_in_typemap {
631             // Also make sure that we already have a TypeMap entry for the unique type id.
632             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
633                 Some(metadata) => metadata,
634                 None => {
635                     span_bug!(usage_site_span,
636                               "Expected type metadata for unique \
637                                type id '{}' to already be in \
638                                the debuginfo::TypeMap but it \
639                                was not. (Ty = {})",
640                               type_map.get_unique_type_id_as_string(unique_type_id),
641                               t);
642                 }
643             };
644
645             match type_map.find_metadata_for_type(t) {
646                 Some(metadata) => {
647                     if metadata != metadata_for_uid {
648                         span_bug!(usage_site_span,
649                                   "Mismatch between Ty and \
650                                    UniqueTypeId maps in \
651                                    debuginfo::TypeMap. \
652                                    UniqueTypeId={}, Ty={}",
653                                   type_map.get_unique_type_id_as_string(unique_type_id),
654                                   t);
655                     }
656                 }
657                 None => {
658                     type_map.register_type_with_metadata(t, metadata);
659                 }
660             }
661         } else {
662             type_map.register_type_with_metadata(t, metadata);
663             type_map.register_unique_id_with_metadata(unique_type_id, metadata);
664         }
665     }
666
667     metadata
668 }
669
670 pub fn file_metadata(cx: &CrateContext,
671                      file_name: &str,
672                      defining_crate: CrateNum) -> DIFile {
673     debug!("file_metadata: file_name: {}, defining_crate: {}",
674            file_name,
675            defining_crate);
676
677     let directory = if defining_crate == LOCAL_CRATE {
678         &cx.sess().working_dir.0[..]
679     } else {
680         // If the path comes from an upstream crate we assume it has been made
681         // independent of the compiler's working directory one way or another.
682         ""
683     };
684
685     file_metadata_raw(cx, file_name, directory)
686 }
687
688 pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile {
689     file_metadata_raw(cx, "<unknown>", "")
690 }
691
692 fn file_metadata_raw(cx: &CrateContext,
693                      file_name: &str,
694                      directory: &str)
695                      -> DIFile {
696     let key = (Symbol::intern(file_name), Symbol::intern(directory));
697
698     if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(&key) {
699         return *file_metadata;
700     }
701
702     debug!("file_metadata: file_name: {}, directory: {}", file_name, directory);
703
704     let file_name = CString::new(file_name).unwrap();
705     let directory = CString::new(directory).unwrap();
706
707     let file_metadata = unsafe {
708         llvm::LLVMRustDIBuilderCreateFile(DIB(cx),
709                                           file_name.as_ptr(),
710                                           directory.as_ptr())
711     };
712
713     let mut created_files = debug_context(cx).created_files.borrow_mut();
714     created_files.insert(key, file_metadata);
715     file_metadata
716 }
717
718 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
719                                  t: Ty<'tcx>) -> DIType {
720
721     debug!("basic_type_metadata: {:?}", t);
722
723     let (name, encoding) = match t.sty {
724         ty::TyNever => ("!", DW_ATE_unsigned),
725         ty::TyTuple(ref elements, _) if elements.is_empty() =>
726             ("()", DW_ATE_unsigned),
727         ty::TyBool => ("bool", DW_ATE_boolean),
728         ty::TyChar => ("char", DW_ATE_unsigned_char),
729         ty::TyInt(int_ty) => {
730             (int_ty.ty_to_string(), DW_ATE_signed)
731         },
732         ty::TyUint(uint_ty) => {
733             (uint_ty.ty_to_string(), DW_ATE_unsigned)
734         },
735         ty::TyFloat(float_ty) => {
736             (float_ty.ty_to_string(), DW_ATE_float)
737         },
738         _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
739     };
740
741     let llvm_type = type_of::type_of(cx, t);
742     let (size, align) = size_and_align_of(cx, llvm_type);
743     let name = CString::new(name).unwrap();
744     let ty_metadata = unsafe {
745         llvm::LLVMRustDIBuilderCreateBasicType(
746             DIB(cx),
747             name.as_ptr(),
748             bytes_to_bits(size),
749             bytes_to_bits(align),
750             encoding)
751     };
752
753     return ty_metadata;
754 }
755
756 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
757                                    pointer_type: Ty<'tcx>,
758                                    pointee_type_metadata: DIType)
759                                    -> DIType {
760     let pointer_llvm_type = type_of::type_of(cx, pointer_type);
761     let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
762     let name = compute_debuginfo_type_name(cx, pointer_type, false);
763     let name = CString::new(name).unwrap();
764     let ptr_metadata = unsafe {
765         llvm::LLVMRustDIBuilderCreatePointerType(
766             DIB(cx),
767             pointee_type_metadata,
768             bytes_to_bits(pointer_size),
769             bytes_to_bits(pointer_align),
770             name.as_ptr())
771     };
772     return ptr_metadata;
773 }
774
775 pub fn compile_unit_metadata(scc: &SharedCrateContext,
776                              codegen_unit_name: &str,
777                              debug_context: &CrateDebugContext,
778                              sess: &Session)
779                              -> DIDescriptor {
780     let mut name_in_debuginfo = match sess.local_crate_source_file {
781         Some(ref path) => path.clone(),
782         None => scc.tcx().crate_name(LOCAL_CRATE).to_string(),
783     };
784
785     // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
786     // if multiple object files with the same DW_AT_name are linked together.
787     // As a workaround we generate unique names for each object file. Those do
788     // not correspond to an actual source file but that should be harmless.
789     if scc.sess().target.target.options.is_like_osx {
790         name_in_debuginfo.push_str("@");
791         name_in_debuginfo.push_str(codegen_unit_name);
792     }
793
794     debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
795     // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
796     let producer = format!("clang LLVM (rustc version {})",
797                            (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
798
799     let name_in_debuginfo = CString::new(name_in_debuginfo).unwrap();
800     let work_dir = CString::new(&sess.working_dir.0[..]).unwrap();
801     let producer = CString::new(producer).unwrap();
802     let flags = "\0";
803     let split_name = "\0";
804
805     unsafe {
806         let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
807             debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr());
808
809         let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
810             debug_context.builder,
811             DW_LANG_RUST,
812             file_metadata,
813             producer.as_ptr(),
814             sess.opts.optimize != config::OptLevel::No,
815             flags.as_ptr() as *const _,
816             0,
817             split_name.as_ptr() as *const _);
818
819         if sess.opts.debugging_opts.profile {
820             let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext,
821                                                                  unit_metadata);
822
823             let gcov_cu_info = [
824                 path_to_mdstring(debug_context.llcontext,
825                                  &scc.tcx().output_filenames(LOCAL_CRATE).with_extension("gcno")),
826                 path_to_mdstring(debug_context.llcontext,
827                                  &scc.tcx().output_filenames(LOCAL_CRATE).with_extension("gcda")),
828                 cu_desc_metadata,
829             ];
830             let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext,
831                                                           gcov_cu_info.as_ptr(),
832                                                           gcov_cu_info.len() as c_uint);
833
834             let llvm_gcov_ident = CString::new("llvm.gcov").unwrap();
835             llvm::LLVMAddNamedMetadataOperand(debug_context.llmod,
836                                               llvm_gcov_ident.as_ptr(),
837                                               gcov_metadata);
838         }
839
840         return unit_metadata;
841     };
842
843     fn path_to_mdstring(llcx: llvm::ContextRef, path: &Path) -> llvm::ValueRef {
844         let path_str = path2cstr(path);
845         unsafe {
846             llvm::LLVMMDStringInContext(llcx,
847                                         path_str.as_ptr(),
848                                         path_str.as_bytes().len() as c_uint)
849         }
850     }
851 }
852
853 struct MetadataCreationResult {
854     metadata: DIType,
855     already_stored_in_typemap: bool
856 }
857
858 impl MetadataCreationResult {
859     fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
860         MetadataCreationResult {
861             metadata,
862             already_stored_in_typemap,
863         }
864     }
865 }
866
867 #[derive(Debug)]
868 enum MemberOffset {
869     FixedMemberOffset { bytes: usize },
870     // For ComputedMemberOffset, the offset is read from the llvm type definition.
871     ComputedMemberOffset
872 }
873
874 // Description of a type member, which can either be a regular field (as in
875 // structs or tuples) or an enum variant.
876 #[derive(Debug)]
877 struct MemberDescription {
878     name: String,
879     llvm_type: Type,
880     type_metadata: DIType,
881     offset: MemberOffset,
882     flags: DIFlags,
883 }
884
885 // A factory for MemberDescriptions. It produces a list of member descriptions
886 // for some record-like type. MemberDescriptionFactories are used to defer the
887 // creation of type member descriptions in order to break cycles arising from
888 // recursive type definitions.
889 enum MemberDescriptionFactory<'tcx> {
890     StructMDF(StructMemberDescriptionFactory<'tcx>),
891     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
892     EnumMDF(EnumMemberDescriptionFactory<'tcx>),
893     UnionMDF(UnionMemberDescriptionFactory<'tcx>),
894     VariantMDF(VariantMemberDescriptionFactory<'tcx>)
895 }
896
897 impl<'tcx> MemberDescriptionFactory<'tcx> {
898     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
899                                       -> Vec<MemberDescription> {
900         match *self {
901             StructMDF(ref this) => {
902                 this.create_member_descriptions(cx)
903             }
904             TupleMDF(ref this) => {
905                 this.create_member_descriptions(cx)
906             }
907             EnumMDF(ref this) => {
908                 this.create_member_descriptions(cx)
909             }
910             UnionMDF(ref this) => {
911                 this.create_member_descriptions(cx)
912             }
913             VariantMDF(ref this) => {
914                 this.create_member_descriptions(cx)
915             }
916         }
917     }
918 }
919
920 //=-----------------------------------------------------------------------------
921 // Structs
922 //=-----------------------------------------------------------------------------
923
924 // Creates MemberDescriptions for the fields of a struct
925 struct StructMemberDescriptionFactory<'tcx> {
926     ty: Ty<'tcx>,
927     variant: &'tcx ty::VariantDef,
928     substs: &'tcx Substs<'tcx>,
929     span: Span,
930 }
931
932 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
933     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
934                                       -> Vec<MemberDescription> {
935         let layout = cx.layout_of(self.ty);
936
937         let tmp;
938         let offsets = match *layout {
939             layout::Univariant { ref variant, .. } => &variant.offsets,
940             layout::Vector { element, count } => {
941                 let element_size = element.size(cx).bytes();
942                 tmp = (0..count).
943                   map(|i| layout::Size::from_bytes(i*element_size))
944                   .collect::<Vec<layout::Size>>();
945                 &tmp
946             }
947             _ => bug!("{} is not a struct", self.ty)
948         };
949
950         self.variant.fields.iter().enumerate().map(|(i, f)| {
951             let name = if self.variant.ctor_kind == CtorKind::Fn {
952                 format!("__{}", i)
953             } else {
954                 f.name.to_string()
955             };
956             let fty = monomorphize::field_ty(cx.tcx(), self.substs, f);
957
958             let offset = FixedMemberOffset { bytes: offsets[i].bytes() as usize};
959
960             MemberDescription {
961                 name,
962                 llvm_type: type_of::in_memory_type_of(cx, fty),
963                 type_metadata: type_metadata(cx, fty, self.span),
964                 offset,
965                 flags: DIFlags::FlagZero,
966             }
967         }).collect()
968     }
969 }
970
971
972 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
973                                      struct_type: Ty<'tcx>,
974                                      unique_type_id: UniqueTypeId,
975                                      span: Span)
976                                      -> RecursiveTypeDescription<'tcx> {
977     let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
978     let struct_llvm_type = type_of::in_memory_type_of(cx, struct_type);
979
980     let (struct_def_id, variant, substs) = match struct_type.sty {
981         ty::TyAdt(def, substs) => (def.did, def.struct_variant(), substs),
982         _ => bug!("prepare_struct_metadata on a non-ADT")
983     };
984
985     let containing_scope = get_namespace_for_item(cx, struct_def_id);
986
987     let struct_metadata_stub = create_struct_stub(cx,
988                                                   struct_llvm_type,
989                                                   &struct_name,
990                                                   unique_type_id,
991                                                   containing_scope);
992
993     create_and_register_recursive_type_forward_declaration(
994         cx,
995         struct_type,
996         unique_type_id,
997         struct_metadata_stub,
998         struct_llvm_type,
999         StructMDF(StructMemberDescriptionFactory {
1000             ty: struct_type,
1001             variant,
1002             substs,
1003             span,
1004         })
1005     )
1006 }
1007
1008 //=-----------------------------------------------------------------------------
1009 // Tuples
1010 //=-----------------------------------------------------------------------------
1011
1012 // Creates MemberDescriptions for the fields of a tuple
1013 struct TupleMemberDescriptionFactory<'tcx> {
1014     ty: Ty<'tcx>,
1015     component_types: Vec<Ty<'tcx>>,
1016     span: Span,
1017 }
1018
1019 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1020     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1021                                       -> Vec<MemberDescription> {
1022         let layout = cx.layout_of(self.ty);
1023         let offsets = if let layout::Univariant { ref variant, .. } = *layout {
1024             &variant.offsets
1025         } else {
1026             bug!("{} is not a tuple", self.ty);
1027         };
1028
1029         self.component_types
1030             .iter()
1031             .enumerate()
1032             .map(|(i, &component_type)| {
1033             MemberDescription {
1034                 name: format!("__{}", i),
1035                 llvm_type: type_of::type_of(cx, component_type),
1036                 type_metadata: type_metadata(cx, component_type, self.span),
1037                 offset: FixedMemberOffset { bytes: offsets[i].bytes() as usize },
1038                 flags: DIFlags::FlagZero,
1039             }
1040         }).collect()
1041     }
1042 }
1043
1044 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1045                                     tuple_type: Ty<'tcx>,
1046                                     component_types: &[Ty<'tcx>],
1047                                     unique_type_id: UniqueTypeId,
1048                                     span: Span)
1049                                     -> RecursiveTypeDescription<'tcx> {
1050     let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1051     let tuple_llvm_type = type_of::type_of(cx, tuple_type);
1052
1053     create_and_register_recursive_type_forward_declaration(
1054         cx,
1055         tuple_type,
1056         unique_type_id,
1057         create_struct_stub(cx,
1058                            tuple_llvm_type,
1059                            &tuple_name[..],
1060                            unique_type_id,
1061                            NO_SCOPE_METADATA),
1062         tuple_llvm_type,
1063         TupleMDF(TupleMemberDescriptionFactory {
1064             ty: tuple_type,
1065             component_types: component_types.to_vec(),
1066             span,
1067         })
1068     )
1069 }
1070
1071 //=-----------------------------------------------------------------------------
1072 // Unions
1073 //=-----------------------------------------------------------------------------
1074
1075 struct UnionMemberDescriptionFactory<'tcx> {
1076     variant: &'tcx ty::VariantDef,
1077     substs: &'tcx Substs<'tcx>,
1078     span: Span,
1079 }
1080
1081 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1082     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1083                                       -> Vec<MemberDescription> {
1084         self.variant.fields.iter().map(|field| {
1085             let fty = monomorphize::field_ty(cx.tcx(), self.substs, field);
1086             MemberDescription {
1087                 name: field.name.to_string(),
1088                 llvm_type: type_of::type_of(cx, fty),
1089                 type_metadata: type_metadata(cx, fty, self.span),
1090                 offset: FixedMemberOffset { bytes: 0 },
1091                 flags: DIFlags::FlagZero,
1092             }
1093         }).collect()
1094     }
1095 }
1096
1097 fn prepare_union_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1098                                     union_type: Ty<'tcx>,
1099                                     unique_type_id: UniqueTypeId,
1100                                     span: Span)
1101                                     -> RecursiveTypeDescription<'tcx> {
1102     let union_name = compute_debuginfo_type_name(cx, union_type, false);
1103     let union_llvm_type = type_of::in_memory_type_of(cx, union_type);
1104
1105     let (union_def_id, variant, substs) = match union_type.sty {
1106         ty::TyAdt(def, substs) => (def.did, def.struct_variant(), substs),
1107         _ => bug!("prepare_union_metadata on a non-ADT")
1108     };
1109
1110     let containing_scope = get_namespace_for_item(cx, union_def_id);
1111
1112     let union_metadata_stub = create_union_stub(cx,
1113                                                 union_llvm_type,
1114                                                 &union_name,
1115                                                 unique_type_id,
1116                                                 containing_scope);
1117
1118     create_and_register_recursive_type_forward_declaration(
1119         cx,
1120         union_type,
1121         unique_type_id,
1122         union_metadata_stub,
1123         union_llvm_type,
1124         UnionMDF(UnionMemberDescriptionFactory {
1125             variant,
1126             substs,
1127             span,
1128         })
1129     )
1130 }
1131
1132 //=-----------------------------------------------------------------------------
1133 // Enums
1134 //=-----------------------------------------------------------------------------
1135
1136 // Describes the members of an enum value: An enum is described as a union of
1137 // structs in DWARF. This MemberDescriptionFactory provides the description for
1138 // the members of this union; so for every variant of the given enum, this
1139 // factory will produce one MemberDescription (all with no name and a fixed
1140 // offset of zero bytes).
1141 struct EnumMemberDescriptionFactory<'tcx> {
1142     enum_type: Ty<'tcx>,
1143     type_rep: &'tcx layout::Layout,
1144     discriminant_type_metadata: Option<DIType>,
1145     containing_scope: DIScope,
1146     file_metadata: DIFile,
1147     span: Span,
1148 }
1149
1150 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1151     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1152                                       -> Vec<MemberDescription> {
1153         let adt = &self.enum_type.ty_adt_def().unwrap();
1154         let substs = match self.enum_type.sty {
1155             ty::TyAdt(def, ref s) if def.adt_kind() == AdtKind::Enum => s,
1156             _ => bug!("{} is not an enum", self.enum_type)
1157         };
1158         match *self.type_rep {
1159             layout::General { ref variants, .. } => {
1160                 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1161                     .expect(""));
1162                 variants
1163                     .iter()
1164                     .enumerate()
1165                     .map(|(i, struct_def)| {
1166                         let (variant_type_metadata,
1167                              variant_llvm_type,
1168                              member_desc_factory) =
1169                             describe_enum_variant(cx,
1170                                                   self.enum_type,
1171                                                   struct_def,
1172                                                   &adt.variants[i],
1173                                                   discriminant_info,
1174                                                   self.containing_scope,
1175                                                   self.span);
1176
1177                         let member_descriptions = member_desc_factory
1178                             .create_member_descriptions(cx);
1179
1180                         set_members_of_composite_type(cx,
1181                                                       variant_type_metadata,
1182                                                       variant_llvm_type,
1183                                                       &member_descriptions);
1184                         MemberDescription {
1185                             name: "".to_string(),
1186                             llvm_type: variant_llvm_type,
1187                             type_metadata: variant_type_metadata,
1188                             offset: FixedMemberOffset { bytes: 0 },
1189                             flags: DIFlags::FlagZero
1190                         }
1191                     }).collect()
1192             },
1193             layout::Univariant{ ref variant, .. } => {
1194                 assert!(adt.variants.len() <= 1);
1195
1196                 if adt.variants.is_empty() {
1197                     vec![]
1198                 } else {
1199                     let (variant_type_metadata,
1200                          variant_llvm_type,
1201                          member_description_factory) =
1202                         describe_enum_variant(cx,
1203                                               self.enum_type,
1204                                               variant,
1205                                               &adt.variants[0],
1206                                               NoDiscriminant,
1207                                               self.containing_scope,
1208                                               self.span);
1209
1210                     let member_descriptions =
1211                         member_description_factory.create_member_descriptions(cx);
1212
1213                     set_members_of_composite_type(cx,
1214                                                   variant_type_metadata,
1215                                                   variant_llvm_type,
1216                                                   &member_descriptions[..]);
1217                     vec![
1218                         MemberDescription {
1219                             name: "".to_string(),
1220                             llvm_type: variant_llvm_type,
1221                             type_metadata: variant_type_metadata,
1222                             offset: FixedMemberOffset { bytes: 0 },
1223                             flags: DIFlags::FlagZero
1224                         }
1225                     ]
1226                 }
1227             }
1228             layout::RawNullablePointer { nndiscr: non_null_variant_index, .. } => {
1229                 // As far as debuginfo is concerned, the pointer this enum
1230                 // represents is still wrapped in a struct. This is to make the
1231                 // DWARF representation of enums uniform.
1232
1233                 // First create a description of the artificial wrapper struct:
1234                 let non_null_variant = &adt.variants[non_null_variant_index as usize];
1235                 let non_null_variant_name = non_null_variant.name.as_str();
1236
1237                 // The llvm type and metadata of the pointer
1238                 let nnty = monomorphize::field_ty(cx.tcx(), &substs, &non_null_variant.fields[0] );
1239                 let non_null_llvm_type = type_of::type_of(cx, nnty);
1240                 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
1241
1242                 // The type of the artificial struct wrapping the pointer
1243                 let artificial_struct_llvm_type = Type::struct_(cx,
1244                                                                 &[non_null_llvm_type],
1245                                                                 false);
1246
1247                 // For the metadata of the wrapper struct, we need to create a
1248                 // MemberDescription of the struct's single field.
1249                 let sole_struct_member_description = MemberDescription {
1250                     name: match non_null_variant.ctor_kind {
1251                         CtorKind::Fn => "__0".to_string(),
1252                         CtorKind::Fictive => {
1253                             non_null_variant.fields[0].name.to_string()
1254                         }
1255                         CtorKind::Const => bug!()
1256                     },
1257                     llvm_type: non_null_llvm_type,
1258                     type_metadata: non_null_type_metadata,
1259                     offset: FixedMemberOffset { bytes: 0 },
1260                     flags: DIFlags::FlagZero
1261                 };
1262
1263                 let unique_type_id = debug_context(cx).type_map
1264                                                       .borrow_mut()
1265                                                       .get_unique_type_id_of_enum_variant(
1266                                                           cx,
1267                                                           self.enum_type,
1268                                                           &non_null_variant_name);
1269
1270                 // Now we can create the metadata of the artificial struct
1271                 let artificial_struct_metadata =
1272                     composite_type_metadata(cx,
1273                                             artificial_struct_llvm_type,
1274                                             &non_null_variant_name,
1275                                             unique_type_id,
1276                                             &[sole_struct_member_description],
1277                                             self.containing_scope,
1278                                             self.file_metadata,
1279                                             syntax_pos::DUMMY_SP);
1280
1281                 // Encode the information about the null variant in the union
1282                 // member's name.
1283                 let null_variant_index = (1 - non_null_variant_index) as usize;
1284                 let null_variant_name = adt.variants[null_variant_index].name;
1285                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1286                                                 0,
1287                                                 null_variant_name);
1288
1289                 // Finally create the (singleton) list of descriptions of union
1290                 // members.
1291                 vec![
1292                     MemberDescription {
1293                         name: union_member_name,
1294                         llvm_type: artificial_struct_llvm_type,
1295                         type_metadata: artificial_struct_metadata,
1296                         offset: FixedMemberOffset { bytes: 0 },
1297                         flags: DIFlags::FlagZero
1298                     }
1299                 ]
1300             },
1301             layout::StructWrappedNullablePointer { nonnull: ref struct_def,
1302                                                 nndiscr,
1303                                                 ref discrfield_source, ..} => {
1304                 // Create a description of the non-null variant
1305                 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
1306                     describe_enum_variant(cx,
1307                                           self.enum_type,
1308                                           struct_def,
1309                                           &adt.variants[nndiscr as usize],
1310                                           OptimizedDiscriminant,
1311                                           self.containing_scope,
1312                                           self.span);
1313
1314                 let variant_member_descriptions =
1315                     member_description_factory.create_member_descriptions(cx);
1316
1317                 set_members_of_composite_type(cx,
1318                                               variant_type_metadata,
1319                                               variant_llvm_type,
1320                                               &variant_member_descriptions[..]);
1321
1322                 // Encode the information about the null variant in the union
1323                 // member's name.
1324                 let null_variant_index = (1 - nndiscr) as usize;
1325                 let null_variant_name = adt.variants[null_variant_index].name;
1326                 let discrfield_source = discrfield_source.iter()
1327                                            .skip(1)
1328                                            .map(|x| x.to_string())
1329                                            .collect::<Vec<_>>().join("$");
1330                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1331                                                 discrfield_source,
1332                                                 null_variant_name);
1333
1334                 // Create the (singleton) list of descriptions of union members.
1335                 vec![
1336                     MemberDescription {
1337                         name: union_member_name,
1338                         llvm_type: variant_llvm_type,
1339                         type_metadata: variant_type_metadata,
1340                         offset: FixedMemberOffset { bytes: 0 },
1341                         flags: DIFlags::FlagZero
1342                     }
1343                 ]
1344             },
1345             layout::CEnum { .. } => span_bug!(self.span, "This should be unreachable."),
1346             ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1347         }
1348     }
1349 }
1350
1351 // Creates MemberDescriptions for the fields of a single enum variant.
1352 struct VariantMemberDescriptionFactory<'tcx> {
1353     // Cloned from the layout::Struct describing the variant.
1354     offsets: &'tcx [layout::Size],
1355     args: Vec<(String, Ty<'tcx>)>,
1356     discriminant_type_metadata: Option<DIType>,
1357     span: Span,
1358 }
1359
1360 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1361     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1362                                       -> Vec<MemberDescription> {
1363         self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1364             MemberDescription {
1365                 name: name.to_string(),
1366                 llvm_type: type_of::type_of(cx, ty),
1367                 type_metadata: match self.discriminant_type_metadata {
1368                     Some(metadata) if i == 0 => metadata,
1369                     _ => type_metadata(cx, ty, self.span)
1370                 },
1371                 offset: FixedMemberOffset { bytes: self.offsets[i].bytes() as usize },
1372                 flags: DIFlags::FlagZero
1373             }
1374         }).collect()
1375     }
1376 }
1377
1378 #[derive(Copy, Clone)]
1379 enum EnumDiscriminantInfo {
1380     RegularDiscriminant(DIType),
1381     OptimizedDiscriminant,
1382     NoDiscriminant
1383 }
1384
1385 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1386 // of the variant, and (3) a MemberDescriptionFactory for producing the
1387 // descriptions of the fields of the variant. This is a rudimentary version of a
1388 // full RecursiveTypeDescription.
1389 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1390                                    enum_type: Ty<'tcx>,
1391                                    struct_def: &'tcx layout::Struct,
1392                                    variant: &'tcx ty::VariantDef,
1393                                    discriminant_info: EnumDiscriminantInfo,
1394                                    containing_scope: DIScope,
1395                                    span: Span)
1396                                    -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1397     let substs = match enum_type.sty {
1398         ty::TyAdt(def, s) if def.adt_kind() == AdtKind::Enum => s,
1399         ref t @ _ => bug!("{:#?} is not an enum", t)
1400     };
1401
1402     let maybe_discr_and_signed: Option<(layout::Integer, bool)> = match *cx.layout_of(enum_type) {
1403         layout::CEnum {discr, ..} => Some((discr, true)),
1404         layout::General{discr, ..} => Some((discr, false)),
1405         layout::Univariant { .. }
1406         | layout::RawNullablePointer { .. }
1407         | layout::StructWrappedNullablePointer { .. } => None,
1408         ref l @ _ => bug!("This should be unreachable. Type is {:#?} layout is {:#?}", enum_type, l)
1409     };
1410
1411     let mut field_tys = variant.fields.iter().map(|f| {
1412         monomorphize::field_ty(cx.tcx(), &substs, f)
1413     }).collect::<Vec<_>>();
1414
1415     if let Some((discr, signed)) = maybe_discr_and_signed {
1416         field_tys.insert(0, discr.to_ty(&cx.tcx(), signed));
1417     }
1418
1419
1420     let variant_llvm_type =
1421         Type::struct_(cx, &field_tys
1422                                     .iter()
1423                                     .map(|t| type_of::type_of(cx, t))
1424                                     .collect::<Vec<_>>()
1425                                     ,
1426                       struct_def.packed);
1427     // Could do some consistency checks here: size, align, field count, discr type
1428
1429     let variant_name = variant.name.as_str();
1430     let unique_type_id = debug_context(cx).type_map
1431                                           .borrow_mut()
1432                                           .get_unique_type_id_of_enum_variant(
1433                                               cx,
1434                                               enum_type,
1435                                               &variant_name);
1436
1437     let metadata_stub = create_struct_stub(cx,
1438                                            variant_llvm_type,
1439                                            &variant_name,
1440                                            unique_type_id,
1441                                            containing_scope);
1442
1443     // Get the argument names from the enum variant info
1444     let mut arg_names: Vec<_> = match variant.ctor_kind {
1445         CtorKind::Const => vec![],
1446         CtorKind::Fn => {
1447             variant.fields
1448                    .iter()
1449                    .enumerate()
1450                    .map(|(i, _)| format!("__{}", i))
1451                    .collect()
1452         }
1453         CtorKind::Fictive => {
1454             variant.fields
1455                    .iter()
1456                    .map(|f| f.name.to_string())
1457                    .collect()
1458         }
1459     };
1460
1461     // If this is not a univariant enum, there is also the discriminant field.
1462     match discriminant_info {
1463         RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
1464         _ => { /* do nothing */ }
1465     };
1466
1467     // Build an array of (field name, field type) pairs to be captured in the factory closure.
1468     let args: Vec<(String, Ty)> = arg_names.iter()
1469         .zip(field_tys.iter())
1470         .map(|(s, &t)| (s.to_string(), t))
1471         .collect();
1472
1473     let member_description_factory =
1474         VariantMDF(VariantMemberDescriptionFactory {
1475             offsets: &struct_def.offsets[..],
1476             args,
1477             discriminant_type_metadata: match discriminant_info {
1478                 RegularDiscriminant(discriminant_type_metadata) => {
1479                     Some(discriminant_type_metadata)
1480                 }
1481                 _ => None
1482             },
1483             span,
1484         });
1485
1486     (metadata_stub, variant_llvm_type, member_description_factory)
1487 }
1488
1489 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1490                                    enum_type: Ty<'tcx>,
1491                                    enum_def_id: DefId,
1492                                    unique_type_id: UniqueTypeId,
1493                                    span: Span)
1494                                    -> RecursiveTypeDescription<'tcx> {
1495     let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1496
1497     let containing_scope = get_namespace_for_item(cx, enum_def_id);
1498     // FIXME: This should emit actual file metadata for the enum, but we
1499     // currently can't get the necessary information when it comes to types
1500     // imported from other crates. Formerly we violated the ODR when performing
1501     // LTO because we emitted debuginfo for the same type with varying file
1502     // metadata, so as a workaround we pretend that the type comes from
1503     // <unknown>
1504     let file_metadata = unknown_file_metadata(cx);
1505
1506     let def = enum_type.ty_adt_def().unwrap();
1507     let enumerators_metadata: Vec<DIDescriptor> = def.discriminants(cx.tcx())
1508         .zip(&def.variants)
1509         .map(|(discr, v)| {
1510             let token = v.name.as_str();
1511             let name = CString::new(token.as_bytes()).unwrap();
1512             unsafe {
1513                 llvm::LLVMRustDIBuilderCreateEnumerator(
1514                     DIB(cx),
1515                     name.as_ptr(),
1516                     // FIXME: what if enumeration has i128 discriminant?
1517                     discr.to_u128_unchecked() as u64)
1518             }
1519         })
1520         .collect();
1521
1522     let discriminant_type_metadata = |inttype: layout::Integer, signed: bool| {
1523         let disr_type_key = (enum_def_id, inttype);
1524         let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1525                                                                  .borrow()
1526                                                                  .get(&disr_type_key).cloned();
1527         match cached_discriminant_type_metadata {
1528             Some(discriminant_type_metadata) => discriminant_type_metadata,
1529             None => {
1530                 let discriminant_llvm_type = Type::from_integer(cx, inttype);
1531                 let (discriminant_size, discriminant_align) =
1532                     size_and_align_of(cx, discriminant_llvm_type);
1533                 let discriminant_base_type_metadata =
1534                     type_metadata(cx,
1535                                   inttype.to_ty(&cx.tcx(), signed),
1536                                   syntax_pos::DUMMY_SP);
1537                 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1538
1539                 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1540                 let discriminant_type_metadata = unsafe {
1541                     llvm::LLVMRustDIBuilderCreateEnumerationType(
1542                         DIB(cx),
1543                         containing_scope,
1544                         name.as_ptr(),
1545                         file_metadata,
1546                         UNKNOWN_LINE_NUMBER,
1547                         bytes_to_bits(discriminant_size),
1548                         bytes_to_bits(discriminant_align),
1549                         create_DIArray(DIB(cx), &enumerators_metadata),
1550                         discriminant_base_type_metadata)
1551                 };
1552
1553                 debug_context(cx).created_enum_disr_types
1554                                  .borrow_mut()
1555                                  .insert(disr_type_key, discriminant_type_metadata);
1556
1557                 discriminant_type_metadata
1558             }
1559         }
1560     };
1561
1562     let type_rep = cx.layout_of(enum_type);
1563
1564     let discriminant_type_metadata = match *type_rep {
1565         layout::CEnum { discr, signed, .. } => {
1566             return FinalMetadata(discriminant_type_metadata(discr, signed))
1567         },
1568         layout::RawNullablePointer { .. }           |
1569         layout::StructWrappedNullablePointer { .. } |
1570         layout::Univariant { .. }                      => None,
1571         layout::General { discr, .. } => Some(discriminant_type_metadata(discr, false)),
1572         ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1573     };
1574
1575     let enum_llvm_type = type_of::type_of(cx, enum_type);
1576     let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
1577
1578     let enum_name = CString::new(enum_name).unwrap();
1579     let unique_type_id_str = CString::new(
1580         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1581     ).unwrap();
1582     let enum_metadata = unsafe {
1583         llvm::LLVMRustDIBuilderCreateUnionType(
1584         DIB(cx),
1585         containing_scope,
1586         enum_name.as_ptr(),
1587         file_metadata,
1588         UNKNOWN_LINE_NUMBER,
1589         bytes_to_bits(enum_type_size),
1590         bytes_to_bits(enum_type_align),
1591         DIFlags::FlagZero,
1592         ptr::null_mut(),
1593         0, // RuntimeLang
1594         unique_type_id_str.as_ptr())
1595     };
1596
1597     return create_and_register_recursive_type_forward_declaration(
1598         cx,
1599         enum_type,
1600         unique_type_id,
1601         enum_metadata,
1602         enum_llvm_type,
1603         EnumMDF(EnumMemberDescriptionFactory {
1604             enum_type,
1605             type_rep: type_rep.layout,
1606             discriminant_type_metadata,
1607             containing_scope,
1608             file_metadata,
1609             span,
1610         }),
1611     );
1612
1613     fn get_enum_discriminant_name(cx: &CrateContext,
1614                                   def_id: DefId)
1615                                   -> InternedString {
1616         cx.tcx().item_name(def_id)
1617     }
1618 }
1619
1620 /// Creates debug information for a composite type, that is, anything that
1621 /// results in a LLVM struct.
1622 ///
1623 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1624 fn composite_type_metadata(cx: &CrateContext,
1625                            composite_llvm_type: Type,
1626                            composite_type_name: &str,
1627                            composite_type_unique_id: UniqueTypeId,
1628                            member_descriptions: &[MemberDescription],
1629                            containing_scope: DIScope,
1630
1631                            // Ignore source location information as long as it
1632                            // can't be reconstructed for non-local crates.
1633                            _file_metadata: DIFile,
1634                            _definition_span: Span)
1635                            -> DICompositeType {
1636     // Create the (empty) struct metadata node ...
1637     let composite_type_metadata = create_struct_stub(cx,
1638                                                      composite_llvm_type,
1639                                                      composite_type_name,
1640                                                      composite_type_unique_id,
1641                                                      containing_scope);
1642     // ... and immediately create and add the member descriptions.
1643     set_members_of_composite_type(cx,
1644                                   composite_type_metadata,
1645                                   composite_llvm_type,
1646                                   member_descriptions);
1647
1648     return composite_type_metadata;
1649 }
1650
1651 fn set_members_of_composite_type(cx: &CrateContext,
1652                                  composite_type_metadata: DICompositeType,
1653                                  composite_llvm_type: Type,
1654                                  member_descriptions: &[MemberDescription]) {
1655     // In some rare cases LLVM metadata uniquing would lead to an existing type
1656     // description being used instead of a new one created in
1657     // create_struct_stub. This would cause a hard to trace assertion in
1658     // DICompositeType::SetTypeArray(). The following check makes sure that we
1659     // get a better error message if this should happen again due to some
1660     // regression.
1661     {
1662         let mut composite_types_completed =
1663             debug_context(cx).composite_types_completed.borrow_mut();
1664         if composite_types_completed.contains(&composite_type_metadata) {
1665             bug!("debuginfo::set_members_of_composite_type() - \
1666                   Already completed forward declaration re-encountered.");
1667         } else {
1668             composite_types_completed.insert(composite_type_metadata);
1669         }
1670     }
1671
1672     let member_metadata: Vec<DIDescriptor> = member_descriptions
1673         .iter()
1674         .enumerate()
1675         .map(|(i, member_description)| {
1676             let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
1677             let member_offset = match member_description.offset {
1678                 FixedMemberOffset { bytes } => bytes as u64,
1679                 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
1680             };
1681
1682             let member_name = member_description.name.as_bytes();
1683             let member_name = CString::new(member_name).unwrap();
1684             unsafe {
1685                 llvm::LLVMRustDIBuilderCreateMemberType(
1686                     DIB(cx),
1687                     composite_type_metadata,
1688                     member_name.as_ptr(),
1689                     unknown_file_metadata(cx),
1690                     UNKNOWN_LINE_NUMBER,
1691                     bytes_to_bits(member_size),
1692                     bytes_to_bits(member_align),
1693                     bytes_to_bits(member_offset),
1694                     member_description.flags,
1695                     member_description.type_metadata)
1696             }
1697         })
1698         .collect();
1699
1700     unsafe {
1701         let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1702         llvm::LLVMRustDICompositeTypeSetTypeArray(
1703             DIB(cx), composite_type_metadata, type_array);
1704     }
1705 }
1706
1707 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1708 // any caching, does not add any fields to the struct. This can be done later
1709 // with set_members_of_composite_type().
1710 fn create_struct_stub(cx: &CrateContext,
1711                       struct_llvm_type: Type,
1712                       struct_type_name: &str,
1713                       unique_type_id: UniqueTypeId,
1714                       containing_scope: DIScope)
1715                    -> DICompositeType {
1716     let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
1717
1718     let name = CString::new(struct_type_name).unwrap();
1719     let unique_type_id = CString::new(
1720         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1721     ).unwrap();
1722     let metadata_stub = unsafe {
1723         // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1724         // pointer will lead to hard to trace and debug LLVM assertions
1725         // later on in llvm/lib/IR/Value.cpp.
1726         let empty_array = create_DIArray(DIB(cx), &[]);
1727
1728         llvm::LLVMRustDIBuilderCreateStructType(
1729             DIB(cx),
1730             containing_scope,
1731             name.as_ptr(),
1732             unknown_file_metadata(cx),
1733             UNKNOWN_LINE_NUMBER,
1734             bytes_to_bits(struct_size),
1735             bytes_to_bits(struct_align),
1736             DIFlags::FlagZero,
1737             ptr::null_mut(),
1738             empty_array,
1739             0,
1740             ptr::null_mut(),
1741             unique_type_id.as_ptr())
1742     };
1743
1744     return metadata_stub;
1745 }
1746
1747 fn create_union_stub(cx: &CrateContext,
1748                      union_llvm_type: Type,
1749                      union_type_name: &str,
1750                      unique_type_id: UniqueTypeId,
1751                      containing_scope: DIScope)
1752                    -> DICompositeType {
1753     let (union_size, union_align) = size_and_align_of(cx, union_llvm_type);
1754
1755     let name = CString::new(union_type_name).unwrap();
1756     let unique_type_id = CString::new(
1757         debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1758     ).unwrap();
1759     let metadata_stub = unsafe {
1760         // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
1761         // pointer will lead to hard to trace and debug LLVM assertions
1762         // later on in llvm/lib/IR/Value.cpp.
1763         let empty_array = create_DIArray(DIB(cx), &[]);
1764
1765         llvm::LLVMRustDIBuilderCreateUnionType(
1766             DIB(cx),
1767             containing_scope,
1768             name.as_ptr(),
1769             unknown_file_metadata(cx),
1770             UNKNOWN_LINE_NUMBER,
1771             bytes_to_bits(union_size),
1772             bytes_to_bits(union_align),
1773             DIFlags::FlagZero,
1774             empty_array,
1775             0, // RuntimeLang
1776             unique_type_id.as_ptr())
1777     };
1778
1779     return metadata_stub;
1780 }
1781
1782 /// Creates debug information for the given global variable.
1783 ///
1784 /// Adds the created metadata nodes directly to the crate's IR.
1785 pub fn create_global_var_metadata(cx: &CrateContext,
1786                                   node_id: ast::NodeId,
1787                                   global: ValueRef) {
1788     if cx.dbg_cx().is_none() {
1789         return;
1790     }
1791
1792     let tcx = cx.tcx();
1793
1794     let node_def_id = tcx.hir.local_def_id(node_id);
1795     let var_scope = get_namespace_for_item(cx, node_def_id);
1796     let span = cx.tcx().def_span(node_def_id);
1797
1798     let (file_metadata, line_number) = if span != syntax_pos::DUMMY_SP {
1799         let loc = span_start(cx, span);
1800         (file_metadata(cx, &loc.file.name, LOCAL_CRATE), loc.line as c_uint)
1801     } else {
1802         (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1803     };
1804
1805     let is_local_to_unit = is_node_local_to_unit(cx, node_id);
1806     let variable_type = common::def_ty(cx.tcx(), node_def_id, Substs::empty());
1807     let type_metadata = type_metadata(cx, variable_type, span);
1808     let var_name = tcx.item_name(node_def_id).to_string();
1809     let linkage_name = mangled_name_of_item(cx, node_def_id, "");
1810
1811     let var_name = CString::new(var_name).unwrap();
1812     let linkage_name = CString::new(linkage_name).unwrap();
1813
1814     let global_align = cx.align_of(variable_type);
1815
1816     unsafe {
1817         llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1818                                                     var_scope,
1819                                                     var_name.as_ptr(),
1820                                                     linkage_name.as_ptr(),
1821                                                     file_metadata,
1822                                                     line_number,
1823                                                     type_metadata,
1824                                                     is_local_to_unit,
1825                                                     global,
1826                                                     ptr::null_mut(),
1827                                                     global_align,
1828         );
1829     }
1830 }
1831
1832 // Creates an "extension" of an existing DIScope into another file.
1833 pub fn extend_scope_to_file(ccx: &CrateContext,
1834                             scope_metadata: DIScope,
1835                             file: &syntax_pos::FileMap,
1836                             defining_crate: CrateNum)
1837                             -> DILexicalBlock {
1838     let file_metadata = file_metadata(ccx, &file.name, defining_crate);
1839     unsafe {
1840         llvm::LLVMRustDIBuilderCreateLexicalBlockFile(
1841             DIB(ccx),
1842             scope_metadata,
1843             file_metadata)
1844     }
1845 }