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