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