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