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