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.
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.
11 use self::RecursiveTypeDescription::*;
12 use self::MemberOffset::*;
13 use self::MemberDescriptionFactory::*;
14 use self::EnumDiscriminantInfo::*;
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;
24 use llvm::{self, ValueRef};
25 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor,
26 DICompositeType, DILexicalBlock, DIFlags};
28 use rustc::hir::def::CtorKind;
29 use rustc::hir::def_id::DefId;
30 use rustc::ty::fold::TypeVisitor;
31 use rustc::ty::subst::Substs;
32 use rustc::ty::util::TypeIdHasher;
34 use rustc_data_structures::ToHex;
35 use {type_of, machine, monomorphize};
36 use common::{self, CrateContext};
38 use rustc::ty::{self, AdtKind, Ty};
39 use rustc::ty::layout::{self, LayoutTyper};
41 use util::nodemap::FxHashMap;
42 use util::common::path2cstr;
44 use libc::{c_uint, c_longlong};
45 use std::ffi::CString;
49 use syntax::symbol::{Interner, InternedString};
50 use syntax_pos::{self, Span};
54 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
55 const DW_LANG_RUST: c_uint = 0x1c;
56 #[allow(non_upper_case_globals)]
57 const DW_ATE_boolean: c_uint = 0x02;
58 #[allow(non_upper_case_globals)]
59 const DW_ATE_float: c_uint = 0x04;
60 #[allow(non_upper_case_globals)]
61 const DW_ATE_signed: c_uint = 0x05;
62 #[allow(non_upper_case_globals)]
63 const DW_ATE_unsigned: c_uint = 0x07;
64 #[allow(non_upper_case_globals)]
65 const DW_ATE_unsigned_char: c_uint = 0x08;
67 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
68 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
70 // ptr::null() doesn't work :(
71 pub const NO_SCOPE_METADATA: DIScope = (0 as DIScope);
73 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
74 pub struct UniqueTypeId(ast::Name);
76 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
77 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
78 // faster lookup, also by Ty. The TypeMap is responsible for creating
80 pub struct TypeMap<'tcx> {
81 // The UniqueTypeIds created so far
82 unique_id_interner: Interner,
83 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
84 unique_id_to_metadata: FxHashMap<UniqueTypeId, DIType>,
85 // A map from types to debuginfo metadata. This is a N:1 mapping.
86 type_to_metadata: FxHashMap<Ty<'tcx>, DIType>,
87 // A map from types to UniqueTypeId. This is a N:1 mapping.
88 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>
91 impl<'tcx> TypeMap<'tcx> {
92 pub fn new() -> TypeMap<'tcx> {
94 unique_id_interner: Interner::new(),
95 type_to_metadata: FxHashMap(),
96 unique_id_to_metadata: FxHashMap(),
97 type_to_unique_id: FxHashMap(),
101 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
102 // the mapping already exists.
103 fn register_type_with_metadata<'a>(&mut self,
106 if self.type_to_metadata.insert(type_, metadata).is_some() {
107 bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
111 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
112 // fail if the mapping already exists.
113 fn register_unique_id_with_metadata(&mut self,
114 unique_type_id: UniqueTypeId,
116 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
117 bug!("Type metadata for unique id '{}' is already in the TypeMap!",
118 self.get_unique_type_id_as_string(unique_type_id));
122 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
123 self.type_to_metadata.get(&type_).cloned()
126 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<DIType> {
127 self.unique_id_to_metadata.get(&unique_type_id).cloned()
130 // Get the string representation of a UniqueTypeId. This method will fail if
131 // the id is unknown.
132 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
133 let UniqueTypeId(interner_key) = unique_type_id;
134 self.unique_id_interner.get(interner_key)
137 // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
138 // type has been requested before, this is just a table lookup. Otherwise an
139 // ID will be generated and stored for later lookup.
140 fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
141 type_: Ty<'tcx>) -> UniqueTypeId {
142 // Let's see if we already have something in the cache
143 match self.type_to_unique_id.get(&type_).cloned() {
144 Some(unique_type_id) => return unique_type_id,
145 None => { /* generate one */}
148 // The hasher we are using to generate the UniqueTypeId. We want
149 // something that provides more than the 64 bits of the DefaultHasher.
151 let mut type_id_hasher = TypeIdHasher::<[u8; 20]>::new(cx.tcx());
152 type_id_hasher.visit_ty(type_);
154 let unique_type_id = type_id_hasher.finish().to_hex();
155 let key = self.unique_id_interner.intern(&unique_type_id);
156 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
158 return UniqueTypeId(key);
161 // Get the UniqueTypeId for an enum variant. Enum variants are not really
162 // types of their own, so they need special handling. We still need a
163 // UniqueTypeId for them, since to debuginfo they *are* real types.
164 fn get_unique_type_id_of_enum_variant<'a>(&mut self,
165 cx: &CrateContext<'a, 'tcx>,
169 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
170 let enum_variant_type_id = format!("{}::{}",
171 self.get_unique_type_id_as_string(enum_type_id),
173 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
174 UniqueTypeId(interner_key)
178 // A description of some recursive type. It can either be already finished (as
179 // with FinalMetadata) or it is not yet finished, but contains all information
180 // needed to generate the missing parts of the description. See the
181 // documentation section on Recursive Types at the top of this file for more
183 enum RecursiveTypeDescription<'tcx> {
185 unfinished_type: Ty<'tcx>,
186 unique_type_id: UniqueTypeId,
187 metadata_stub: DICompositeType,
189 member_description_factory: MemberDescriptionFactory<'tcx>,
191 FinalMetadata(DICompositeType)
194 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
195 cx: &CrateContext<'a, 'tcx>,
196 unfinished_type: Ty<'tcx>,
197 unique_type_id: UniqueTypeId,
198 metadata_stub: DICompositeType,
200 member_description_factory: MemberDescriptionFactory<'tcx>)
201 -> RecursiveTypeDescription<'tcx> {
203 // Insert the stub into the TypeMap in order to allow for recursive references
204 let mut type_map = debug_context(cx).type_map.borrow_mut();
205 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
206 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
209 unfinished_type: unfinished_type,
210 unique_type_id: unique_type_id,
211 metadata_stub: metadata_stub,
212 llvm_type: llvm_type,
213 member_description_factory: member_description_factory,
217 impl<'tcx> RecursiveTypeDescription<'tcx> {
218 // Finishes up the description of the type in question (mostly by providing
219 // descriptions of the fields of the given type) and returns the final type
221 fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
223 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
229 ref member_description_factory,
232 // Make sure that we have a forward declaration of the type in
233 // the TypeMap so that recursive references are possible. This
234 // will always be the case if the RecursiveTypeDescription has
235 // been properly created through the
236 // create_and_register_recursive_type_forward_declaration()
239 let type_map = debug_context(cx).type_map.borrow();
240 if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
241 type_map.find_metadata_for_type(unfinished_type).is_none() {
242 bug!("Forward declaration of potentially recursive type \
243 '{:?}' was not found in TypeMap!",
248 // ... then create the member descriptions ...
249 let member_descriptions =
250 member_description_factory.create_member_descriptions(cx);
252 // ... and attach them to the stub to complete it.
253 set_members_of_composite_type(cx,
256 &member_descriptions[..]);
257 return MetadataCreationResult::new(metadata_stub, true);
263 // Returns from the enclosing function if the type metadata with the given
264 // unique id can be found in the type map
265 macro_rules! return_if_metadata_created_in_meantime {
266 ($cx: expr, $unique_type_id: expr) => (
267 match debug_context($cx).type_map
269 .find_metadata_for_unique_id($unique_type_id) {
270 Some(metadata) => return MetadataCreationResult::new(metadata, true),
271 None => { /* proceed normally */ }
276 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
277 unique_type_id: UniqueTypeId,
278 element_type: Ty<'tcx>,
281 -> MetadataCreationResult {
282 let element_type_metadata = type_metadata(cx, element_type, span);
284 return_if_metadata_created_in_meantime!(cx, unique_type_id);
286 let element_llvm_type = type_of::type_of(cx, element_type);
287 let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
289 let (array_size_in_bytes, upper_bound) = match len {
290 Some(len) => (element_type_size * len, len as c_longlong),
294 let subrange = unsafe {
295 llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
298 let subscripts = create_DIArray(DIB(cx), &[subrange]);
299 let metadata = unsafe {
300 llvm::LLVMRustDIBuilderCreateArrayType(
302 bytes_to_bits(array_size_in_bytes),
303 bytes_to_bits(element_type_align),
304 element_type_metadata,
308 return MetadataCreationResult::new(metadata, false);
311 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
313 element_type: Ty<'tcx>,
314 unique_type_id: UniqueTypeId,
316 -> MetadataCreationResult {
317 let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
319 mutbl: hir::MutImmutable
322 let element_type_metadata = type_metadata(cx, data_ptr_type, span);
324 return_if_metadata_created_in_meantime!(cx, unique_type_id);
326 let slice_llvm_type = type_of::type_of(cx, vec_type);
327 let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
329 let member_llvm_types = slice_llvm_type.field_types();
330 assert!(slice_layout_is_correct(cx,
331 &member_llvm_types[..],
333 let member_descriptions = [
335 name: "data_ptr".to_string(),
336 llvm_type: member_llvm_types[0],
337 type_metadata: element_type_metadata,
338 offset: ComputedMemberOffset,
339 flags: DIFlags::FlagZero,
342 name: "length".to_string(),
343 llvm_type: member_llvm_types[1],
344 type_metadata: type_metadata(cx, cx.tcx().types.usize, span),
345 offset: ComputedMemberOffset,
346 flags: DIFlags::FlagZero,
350 assert!(member_descriptions.len() == member_llvm_types.len());
352 let loc = span_start(cx, span);
353 let file_metadata = file_metadata(cx, &loc.file.name, &loc.file.abs_path);
355 let metadata = composite_type_metadata(cx,
357 &slice_type_name[..],
359 &member_descriptions,
363 return MetadataCreationResult::new(metadata, false);
365 fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
366 member_llvm_types: &[Type],
367 element_type: Ty<'tcx>)
369 member_llvm_types.len() == 2 &&
370 member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
371 member_llvm_types[1] == cx.int_type()
375 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
376 unique_type_id: UniqueTypeId,
377 signature: ty::PolyFnSig<'tcx>,
379 -> MetadataCreationResult
381 let signature = cx.tcx().erase_late_bound_regions_and_normalize(&signature);
383 let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs().len() + 1);
386 signature_metadata.push(match signature.output().sty {
387 ty::TyTuple(ref tys, _) if tys.is_empty() => ptr::null_mut(),
388 _ => type_metadata(cx, signature.output(), span)
392 for &argument_type in signature.inputs() {
393 signature_metadata.push(type_metadata(cx, argument_type, span));
396 return_if_metadata_created_in_meantime!(cx, unique_type_id);
398 return MetadataCreationResult::new(
400 llvm::LLVMRustDIBuilderCreateSubroutineType(
402 unknown_file_metadata(cx),
403 create_DIArray(DIB(cx), &signature_metadata[..]))
408 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
409 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
410 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
411 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
412 // of a DST struct, there is no trait_object_type and the results of this
413 // function will be a little bit weird.
414 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
415 trait_type: Ty<'tcx>,
416 trait_object_type: Option<Ty<'tcx>>,
417 unique_type_id: UniqueTypeId)
419 // The implementation provided here is a stub. It makes sure that the trait
420 // type is assigned the correct name, size, namespace, and source location.
421 // But it does not describe the trait's methods.
423 let containing_scope = match trait_type.sty {
424 ty::TyDynamic(ref data, ..) => if let Some(principal) = data.principal() {
425 let def_id = principal.def_id();
426 get_namespace_and_span_for_item(cx, def_id).0
431 bug!("debuginfo: Unexpected trait-object type in \
432 trait_pointer_metadata(): {:?}",
437 let trait_object_type = trait_object_type.unwrap_or(trait_type);
438 let trait_type_name =
439 compute_debuginfo_type_name(cx, trait_object_type, false);
441 let trait_llvm_type = type_of::type_of(cx, trait_object_type);
442 let file_metadata = unknown_file_metadata(cx);
444 composite_type_metadata(cx,
446 &trait_type_name[..],
451 syntax_pos::DUMMY_SP)
454 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
456 usage_site_span: Span)
458 // Get the unique type id of this type.
459 let unique_type_id = {
460 let mut type_map = debug_context(cx).type_map.borrow_mut();
461 // First, try to find the type in TypeMap. If we have seen it before, we
462 // can exit early here.
463 match type_map.find_metadata_for_type(t) {
468 // The Ty is not in the TypeMap but maybe we have already seen
469 // an equivalent type (e.g. only differing in region arguments).
470 // In order to find out, generate the unique type id and look
472 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
473 match type_map.find_metadata_for_unique_id(unique_type_id) {
475 // There is already an equivalent type in the TypeMap.
476 // Register this Ty as an alias in the cache and
477 // return the cached metadata.
478 type_map.register_type_with_metadata(t, metadata);
482 // There really is no type metadata for this type, so
483 // proceed by creating it.
491 debug!("type_metadata: {:?}", t);
494 let ptr_metadata = |ty: Ty<'tcx>| {
496 ty::TySlice(typ) => {
497 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
500 Ok(vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span))
502 ty::TyDynamic(..) => {
503 Ok(MetadataCreationResult::new(
504 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
508 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
510 match debug_context(cx).type_map
512 .find_metadata_for_unique_id(unique_type_id) {
513 Some(metadata) => return Err(metadata),
514 None => { /* proceed normally */ }
517 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
523 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
530 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
532 ty::TyTuple(ref elements, _) if elements.is_empty() => {
533 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
535 ty::TyArray(typ, len) => {
536 fixed_vec_metadata(cx, unique_type_id, typ, Some(len as u64), usage_site_span)
538 ty::TySlice(typ) => {
539 fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
542 fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
544 ty::TyDynamic(..) => {
545 MetadataCreationResult::new(
546 trait_pointer_metadata(cx, t, None, unique_type_id),
549 ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
550 ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
551 match ptr_metadata(ty) {
553 Err(metadata) => return metadata,
556 ty::TyAdt(def, _) if def.is_box() => {
557 match ptr_metadata(t.boxed_ty()) {
559 Err(metadata) => return metadata,
562 ty::TyFnDef(.., sig) | ty::TyFnPtr(sig) => {
563 let fn_metadata = subroutine_type_metadata(cx,
566 usage_site_span).metadata;
567 match debug_context(cx).type_map
569 .find_metadata_for_unique_id(unique_type_id) {
570 Some(metadata) => return metadata,
571 None => { /* proceed normally */ }
574 // This is actually a function pointer, so wrap it in pointer DI
575 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
578 ty::TyClosure(def_id, substs) => {
579 let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx()).collect();
580 prepare_tuple_metadata(cx,
584 usage_site_span).finalize(cx)
586 ty::TyAdt(def, ..) => match def.adt_kind() {
588 prepare_struct_metadata(cx,
591 usage_site_span).finalize(cx)
594 prepare_union_metadata(cx,
597 usage_site_span).finalize(cx)
600 prepare_enum_metadata(cx,
604 usage_site_span).finalize(cx)
607 ty::TyTuple(ref elements, _) => {
608 prepare_tuple_metadata(cx,
612 usage_site_span).finalize(cx)
615 bug!("debuginfo: unexpected type in type_metadata: {:?}", sty)
620 let mut type_map = debug_context(cx).type_map.borrow_mut();
622 if already_stored_in_typemap {
623 // Also make sure that we already have a TypeMap entry for the unique type id.
624 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
625 Some(metadata) => metadata,
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 \
632 type_map.get_unique_type_id_as_string(unique_type_id),
637 match type_map.find_metadata_for_type(t) {
639 if metadata != metadata_for_uid {
640 span_bug!(usage_site_span,
641 "Mismatch between Ty and \
642 UniqueTypeId maps in \
643 debuginfo::TypeMap. \
644 UniqueTypeId={}, Ty={}",
645 type_map.get_unique_type_id_as_string(unique_type_id),
650 type_map.register_type_with_metadata(t, metadata);
654 type_map.register_type_with_metadata(t, metadata);
655 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
662 pub fn file_metadata(cx: &CrateContext, path: &str, full_path: &Option<String>) -> DIFile {
663 // FIXME (#9639): This needs to handle non-utf8 paths
664 let work_dir = cx.sess().working_dir.to_str().unwrap();
666 full_path.as_ref().map(|p| p.as_str()).unwrap_or_else(|| {
667 if path.starts_with(work_dir) {
668 &path[work_dir.len() + 1..path.len()]
674 file_metadata_(cx, path, file_name, &work_dir)
677 pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile {
678 // Regular filenames should not be empty, so we abuse an empty name as the
679 // key for the special unknown file metadata
680 file_metadata_(cx, "", "<unknown>", "")
684 fn file_metadata_(cx: &CrateContext, key: &str, file_name: &str, work_dir: &str) -> DIFile {
685 if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(key) {
686 return *file_metadata;
689 debug!("file_metadata: file_name: {}, work_dir: {}", file_name, work_dir);
691 let file_name = CString::new(file_name).unwrap();
692 let work_dir = CString::new(work_dir).unwrap();
693 let file_metadata = unsafe {
694 llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(),
698 let mut created_files = debug_context(cx).created_files.borrow_mut();
699 created_files.insert(key.to_string(), file_metadata);
703 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
704 t: Ty<'tcx>) -> DIType {
706 debug!("basic_type_metadata: {:?}", t);
708 let (name, encoding) = match t.sty {
709 ty::TyNever => ("!", DW_ATE_unsigned),
710 ty::TyTuple(ref elements, _) if elements.is_empty() =>
711 ("()", DW_ATE_unsigned),
712 ty::TyBool => ("bool", DW_ATE_boolean),
713 ty::TyChar => ("char", DW_ATE_unsigned_char),
714 ty::TyInt(int_ty) => {
715 (int_ty.ty_to_string(), DW_ATE_signed)
717 ty::TyUint(uint_ty) => {
718 (uint_ty.ty_to_string(), DW_ATE_unsigned)
720 ty::TyFloat(float_ty) => {
721 (float_ty.ty_to_string(), DW_ATE_float)
723 _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
726 let llvm_type = type_of::type_of(cx, t);
727 let (size, align) = size_and_align_of(cx, llvm_type);
728 let name = CString::new(name).unwrap();
729 let ty_metadata = unsafe {
730 llvm::LLVMRustDIBuilderCreateBasicType(
734 bytes_to_bits(align),
741 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
742 pointer_type: Ty<'tcx>,
743 pointee_type_metadata: DIType)
745 let pointer_llvm_type = type_of::type_of(cx, pointer_type);
746 let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
747 let name = compute_debuginfo_type_name(cx, pointer_type, false);
748 let name = CString::new(name).unwrap();
749 let ptr_metadata = unsafe {
750 llvm::LLVMRustDIBuilderCreatePointerType(
752 pointee_type_metadata,
753 bytes_to_bits(pointer_size),
754 bytes_to_bits(pointer_align),
760 pub fn compile_unit_metadata(scc: &SharedCrateContext,
761 debug_context: &CrateDebugContext,
764 let work_dir = &sess.working_dir;
765 let compile_unit_name = match sess.local_crate_source_file {
766 None => fallback_path(scc),
767 Some(ref abs_path) => {
768 if abs_path.is_relative() {
769 sess.warn("debuginfo: Invalid path to crate's local root source file!");
772 match abs_path.strip_prefix(work_dir) {
773 Ok(ref p) if p.is_relative() => {
774 if p.starts_with(Path::new("./")) {
777 path2cstr(&Path::new(".").join(p))
780 _ => fallback_path(scc)
786 debug!("compile_unit_metadata: {:?}", compile_unit_name);
787 let producer = format!("rustc version {}",
788 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
790 let compile_unit_name = compile_unit_name.as_ptr();
791 let work_dir = path2cstr(&work_dir);
792 let producer = CString::new(producer).unwrap();
794 let split_name = "\0";
797 let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
798 debug_context.builder, compile_unit_name, work_dir.as_ptr());
800 return llvm::LLVMRustDIBuilderCreateCompileUnit(
801 debug_context.builder,
805 sess.opts.optimize != config::OptLevel::No,
806 flags.as_ptr() as *const _,
808 split_name.as_ptr() as *const _)
811 fn fallback_path(scc: &SharedCrateContext) -> CString {
812 CString::new(scc.link_meta().crate_name.to_string()).unwrap()
816 struct MetadataCreationResult {
818 already_stored_in_typemap: bool
821 impl MetadataCreationResult {
822 fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
823 MetadataCreationResult {
825 already_stored_in_typemap: already_stored_in_typemap
832 FixedMemberOffset { bytes: usize },
833 // For ComputedMemberOffset, the offset is read from the llvm type definition.
837 // Description of a type member, which can either be a regular field (as in
838 // structs or tuples) or an enum variant.
840 struct MemberDescription {
843 type_metadata: DIType,
844 offset: MemberOffset,
848 // A factory for MemberDescriptions. It produces a list of member descriptions
849 // for some record-like type. MemberDescriptionFactories are used to defer the
850 // creation of type member descriptions in order to break cycles arising from
851 // recursive type definitions.
852 enum MemberDescriptionFactory<'tcx> {
853 StructMDF(StructMemberDescriptionFactory<'tcx>),
854 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
855 EnumMDF(EnumMemberDescriptionFactory<'tcx>),
856 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
857 VariantMDF(VariantMemberDescriptionFactory<'tcx>)
860 impl<'tcx> MemberDescriptionFactory<'tcx> {
861 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
862 -> Vec<MemberDescription> {
864 StructMDF(ref this) => {
865 this.create_member_descriptions(cx)
867 TupleMDF(ref this) => {
868 this.create_member_descriptions(cx)
870 EnumMDF(ref this) => {
871 this.create_member_descriptions(cx)
873 UnionMDF(ref this) => {
874 this.create_member_descriptions(cx)
876 VariantMDF(ref this) => {
877 this.create_member_descriptions(cx)
883 //=-----------------------------------------------------------------------------
885 //=-----------------------------------------------------------------------------
887 // Creates MemberDescriptions for the fields of a struct
888 struct StructMemberDescriptionFactory<'tcx> {
890 variant: &'tcx ty::VariantDef,
891 substs: &'tcx Substs<'tcx>,
895 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
896 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
897 -> Vec<MemberDescription> {
898 let layout = cx.layout_of(self.ty);
901 let offsets = match *layout {
902 layout::Univariant { ref variant, .. } => &variant.offsets,
903 layout::Vector { element, count } => {
904 let element_size = element.size(cx).bytes();
906 map(|i| layout::Size::from_bytes(i*element_size))
907 .collect::<Vec<layout::Size>>();
910 _ => bug!("{} is not a struct", self.ty)
913 self.variant.fields.iter().enumerate().map(|(i, f)| {
914 let name = if self.variant.ctor_kind == CtorKind::Fn {
919 let fty = monomorphize::field_ty(cx.tcx(), self.substs, f);
921 let offset = FixedMemberOffset { bytes: offsets[i].bytes() as usize};
925 llvm_type: type_of::in_memory_type_of(cx, fty),
926 type_metadata: type_metadata(cx, fty, self.span),
928 flags: DIFlags::FlagZero,
935 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
936 struct_type: Ty<'tcx>,
937 unique_type_id: UniqueTypeId,
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);
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")
948 let (containing_scope, _) = get_namespace_and_span_for_item(cx, struct_def_id);
950 let struct_metadata_stub = create_struct_stub(cx,
956 create_and_register_recursive_type_forward_declaration(
960 struct_metadata_stub,
962 StructMDF(StructMemberDescriptionFactory {
971 //=-----------------------------------------------------------------------------
973 //=-----------------------------------------------------------------------------
975 // Creates MemberDescriptions for the fields of a tuple
976 struct TupleMemberDescriptionFactory<'tcx> {
978 component_types: Vec<Ty<'tcx>>,
982 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
983 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
984 -> Vec<MemberDescription> {
985 let layout = cx.layout_of(self.ty);
986 let offsets = if let layout::Univariant { ref variant, .. } = *layout {
989 bug!("{} is not a tuple", self.ty);
995 .map(|(i, &component_type)| {
997 name: format!("__{}", i),
998 llvm_type: type_of::type_of(cx, component_type),
999 type_metadata: type_metadata(cx, component_type, self.span),
1000 offset: FixedMemberOffset { bytes: offsets[i].bytes() as usize },
1001 flags: DIFlags::FlagZero,
1007 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1008 tuple_type: Ty<'tcx>,
1009 component_types: &[Ty<'tcx>],
1010 unique_type_id: UniqueTypeId,
1012 -> RecursiveTypeDescription<'tcx> {
1013 let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1014 let tuple_llvm_type = type_of::type_of(cx, tuple_type);
1016 create_and_register_recursive_type_forward_declaration(
1020 create_struct_stub(cx,
1026 TupleMDF(TupleMemberDescriptionFactory {
1028 component_types: component_types.to_vec(),
1034 //=-----------------------------------------------------------------------------
1036 //=-----------------------------------------------------------------------------
1038 struct UnionMemberDescriptionFactory<'tcx> {
1039 variant: &'tcx ty::VariantDef,
1040 substs: &'tcx Substs<'tcx>,
1044 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1045 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1046 -> Vec<MemberDescription> {
1047 self.variant.fields.iter().map(|field| {
1048 let fty = monomorphize::field_ty(cx.tcx(), self.substs, field);
1050 name: field.name.to_string(),
1051 llvm_type: type_of::type_of(cx, fty),
1052 type_metadata: type_metadata(cx, fty, self.span),
1053 offset: FixedMemberOffset { bytes: 0 },
1054 flags: DIFlags::FlagZero,
1060 fn prepare_union_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1061 union_type: Ty<'tcx>,
1062 unique_type_id: UniqueTypeId,
1064 -> RecursiveTypeDescription<'tcx> {
1065 let union_name = compute_debuginfo_type_name(cx, union_type, false);
1066 let union_llvm_type = type_of::in_memory_type_of(cx, union_type);
1068 let (union_def_id, variant, substs) = match union_type.sty {
1069 ty::TyAdt(def, substs) => (def.did, def.struct_variant(), substs),
1070 _ => bug!("prepare_union_metadata on a non-ADT")
1073 let (containing_scope, _) = get_namespace_and_span_for_item(cx, union_def_id);
1075 let union_metadata_stub = create_union_stub(cx,
1081 create_and_register_recursive_type_forward_declaration(
1085 union_metadata_stub,
1087 UnionMDF(UnionMemberDescriptionFactory {
1095 //=-----------------------------------------------------------------------------
1097 //=-----------------------------------------------------------------------------
1099 // Describes the members of an enum value: An enum is described as a union of
1100 // structs in DWARF. This MemberDescriptionFactory provides the description for
1101 // the members of this union; so for every variant of the given enum, this
1102 // factory will produce one MemberDescription (all with no name and a fixed
1103 // offset of zero bytes).
1104 struct EnumMemberDescriptionFactory<'tcx> {
1105 enum_type: Ty<'tcx>,
1106 type_rep: &'tcx layout::Layout,
1107 discriminant_type_metadata: Option<DIType>,
1108 containing_scope: DIScope,
1109 file_metadata: DIFile,
1113 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1114 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1115 -> Vec<MemberDescription> {
1116 let adt = &self.enum_type.ty_adt_def().unwrap();
1117 let substs = match self.enum_type.sty {
1118 ty::TyAdt(def, ref s) if def.adt_kind() == AdtKind::Enum => s,
1119 _ => bug!("{} is not an enum", self.enum_type)
1121 match *self.type_rep {
1122 layout::General { ref variants, .. } => {
1123 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1128 .map(|(i, struct_def)| {
1129 let (variant_type_metadata,
1131 member_desc_factory) =
1132 describe_enum_variant(cx,
1137 self.containing_scope,
1140 let member_descriptions = member_desc_factory
1141 .create_member_descriptions(cx);
1143 set_members_of_composite_type(cx,
1144 variant_type_metadata,
1146 &member_descriptions);
1148 name: "".to_string(),
1149 llvm_type: variant_llvm_type,
1150 type_metadata: variant_type_metadata,
1151 offset: FixedMemberOffset { bytes: 0 },
1152 flags: DIFlags::FlagZero
1156 layout::Univariant{ ref variant, .. } => {
1157 assert!(adt.variants.len() <= 1);
1159 if adt.variants.is_empty() {
1162 let (variant_type_metadata,
1164 member_description_factory) =
1165 describe_enum_variant(cx,
1170 self.containing_scope,
1173 let member_descriptions =
1174 member_description_factory.create_member_descriptions(cx);
1176 set_members_of_composite_type(cx,
1177 variant_type_metadata,
1179 &member_descriptions[..]);
1182 name: "".to_string(),
1183 llvm_type: variant_llvm_type,
1184 type_metadata: variant_type_metadata,
1185 offset: FixedMemberOffset { bytes: 0 },
1186 flags: DIFlags::FlagZero
1191 layout::RawNullablePointer { nndiscr: non_null_variant_index, .. } => {
1192 // As far as debuginfo is concerned, the pointer this enum
1193 // represents is still wrapped in a struct. This is to make the
1194 // DWARF representation of enums uniform.
1196 // First create a description of the artificial wrapper struct:
1197 let non_null_variant = &adt.variants[non_null_variant_index as usize];
1198 let non_null_variant_name = non_null_variant.name.as_str();
1200 // The llvm type and metadata of the pointer
1201 let nnty = monomorphize::field_ty(cx.tcx(), &substs, &non_null_variant.fields[0] );
1202 let non_null_llvm_type = type_of::type_of(cx, nnty);
1203 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
1205 // The type of the artificial struct wrapping the pointer
1206 let artificial_struct_llvm_type = Type::struct_(cx,
1207 &[non_null_llvm_type],
1210 // For the metadata of the wrapper struct, we need to create a
1211 // MemberDescription of the struct's single field.
1212 let sole_struct_member_description = MemberDescription {
1213 name: match non_null_variant.ctor_kind {
1214 CtorKind::Fn => "__0".to_string(),
1215 CtorKind::Fictive => {
1216 non_null_variant.fields[0].name.to_string()
1218 CtorKind::Const => bug!()
1220 llvm_type: non_null_llvm_type,
1221 type_metadata: non_null_type_metadata,
1222 offset: FixedMemberOffset { bytes: 0 },
1223 flags: DIFlags::FlagZero
1226 let unique_type_id = debug_context(cx).type_map
1228 .get_unique_type_id_of_enum_variant(
1231 &non_null_variant_name);
1233 // Now we can create the metadata of the artificial struct
1234 let artificial_struct_metadata =
1235 composite_type_metadata(cx,
1236 artificial_struct_llvm_type,
1237 &non_null_variant_name,
1239 &[sole_struct_member_description],
1240 self.containing_scope,
1242 syntax_pos::DUMMY_SP);
1244 // Encode the information about the null variant in the union
1246 let null_variant_index = (1 - non_null_variant_index) as usize;
1247 let null_variant_name = adt.variants[null_variant_index].name;
1248 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1252 // Finally create the (singleton) list of descriptions of union
1256 name: union_member_name,
1257 llvm_type: artificial_struct_llvm_type,
1258 type_metadata: artificial_struct_metadata,
1259 offset: FixedMemberOffset { bytes: 0 },
1260 flags: DIFlags::FlagZero
1264 layout::StructWrappedNullablePointer { nonnull: ref struct_def,
1266 ref discrfield_source, ..} => {
1267 // Create a description of the non-null variant
1268 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
1269 describe_enum_variant(cx,
1272 &adt.variants[nndiscr as usize],
1273 OptimizedDiscriminant,
1274 self.containing_scope,
1277 let variant_member_descriptions =
1278 member_description_factory.create_member_descriptions(cx);
1280 set_members_of_composite_type(cx,
1281 variant_type_metadata,
1283 &variant_member_descriptions[..]);
1285 // Encode the information about the null variant in the union
1287 let null_variant_index = (1 - nndiscr) as usize;
1288 let null_variant_name = adt.variants[null_variant_index].name;
1289 let discrfield_source = discrfield_source.iter()
1291 .map(|x| x.to_string())
1292 .collect::<Vec<_>>().join("$");
1293 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1297 // Create the (singleton) list of descriptions of union members.
1300 name: union_member_name,
1301 llvm_type: variant_llvm_type,
1302 type_metadata: variant_type_metadata,
1303 offset: FixedMemberOffset { bytes: 0 },
1304 flags: DIFlags::FlagZero
1308 layout::CEnum { .. } => span_bug!(self.span, "This should be unreachable."),
1309 ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1314 // Creates MemberDescriptions for the fields of a single enum variant.
1315 struct VariantMemberDescriptionFactory<'tcx> {
1316 // Cloned from the layout::Struct describing the variant.
1317 offsets: &'tcx [layout::Size],
1318 args: Vec<(String, Ty<'tcx>)>,
1319 discriminant_type_metadata: Option<DIType>,
1323 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1324 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1325 -> Vec<MemberDescription> {
1326 self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1328 name: name.to_string(),
1329 llvm_type: type_of::type_of(cx, ty),
1330 type_metadata: match self.discriminant_type_metadata {
1331 Some(metadata) if i == 0 => metadata,
1332 _ => type_metadata(cx, ty, self.span)
1334 offset: FixedMemberOffset { bytes: self.offsets[i].bytes() as usize },
1335 flags: DIFlags::FlagZero
1341 #[derive(Copy, Clone)]
1342 enum EnumDiscriminantInfo {
1343 RegularDiscriminant(DIType),
1344 OptimizedDiscriminant,
1348 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1349 // of the variant, and (3) a MemberDescriptionFactory for producing the
1350 // descriptions of the fields of the variant. This is a rudimentary version of a
1351 // full RecursiveTypeDescription.
1352 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1353 enum_type: Ty<'tcx>,
1354 struct_def: &'tcx layout::Struct,
1355 variant: &'tcx ty::VariantDef,
1356 discriminant_info: EnumDiscriminantInfo,
1357 containing_scope: DIScope,
1359 -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1360 let substs = match enum_type.sty {
1361 ty::TyAdt(def, s) if def.adt_kind() == AdtKind::Enum => s,
1362 ref t @ _ => bug!("{:#?} is not an enum", t)
1365 let maybe_discr_and_signed: Option<(layout::Integer, bool)> = match *cx.layout_of(enum_type) {
1366 layout::CEnum {discr, ..} => Some((discr, true)),
1367 layout::General{discr, ..} => Some((discr, false)),
1368 layout::Univariant { .. }
1369 | layout::RawNullablePointer { .. }
1370 | layout::StructWrappedNullablePointer { .. } => None,
1371 ref l @ _ => bug!("This should be unreachable. Type is {:#?} layout is {:#?}", enum_type, l)
1374 let mut field_tys = variant.fields.iter().map(|f| {
1375 monomorphize::field_ty(cx.tcx(), &substs, f)
1376 }).collect::<Vec<_>>();
1378 if let Some((discr, signed)) = maybe_discr_and_signed {
1379 field_tys.insert(0, discr.to_ty(&cx.tcx(), signed));
1383 let variant_llvm_type =
1384 Type::struct_(cx, &field_tys
1386 .map(|t| type_of::type_of(cx, t))
1387 .collect::<Vec<_>>()
1390 // Could do some consistency checks here: size, align, field count, discr type
1392 let variant_name = variant.name.as_str();
1393 let unique_type_id = debug_context(cx).type_map
1395 .get_unique_type_id_of_enum_variant(
1400 let metadata_stub = create_struct_stub(cx,
1406 // Get the argument names from the enum variant info
1407 let mut arg_names: Vec<_> = match variant.ctor_kind {
1408 CtorKind::Const => vec![],
1413 .map(|(i, _)| format!("__{}", i))
1416 CtorKind::Fictive => {
1419 .map(|f| f.name.to_string())
1424 // If this is not a univariant enum, there is also the discriminant field.
1425 match discriminant_info {
1426 RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
1427 _ => { /* do nothing */ }
1430 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1431 let args: Vec<(String, Ty)> = arg_names.iter()
1432 .zip(field_tys.iter())
1433 .map(|(s, &t)| (s.to_string(), t))
1436 let member_description_factory =
1437 VariantMDF(VariantMemberDescriptionFactory {
1438 offsets: &struct_def.offsets[..],
1440 discriminant_type_metadata: match discriminant_info {
1441 RegularDiscriminant(discriminant_type_metadata) => {
1442 Some(discriminant_type_metadata)
1449 (metadata_stub, variant_llvm_type, member_description_factory)
1452 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1453 enum_type: Ty<'tcx>,
1455 unique_type_id: UniqueTypeId,
1457 -> RecursiveTypeDescription<'tcx> {
1458 let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1460 let (containing_scope, _) = get_namespace_and_span_for_item(cx, enum_def_id);
1461 // FIXME: This should emit actual file metadata for the enum, but we
1462 // currently can't get the necessary information when it comes to types
1463 // imported from other crates. Formerly we violated the ODR when performing
1464 // LTO because we emitted debuginfo for the same type with varying file
1465 // metadata, so as a workaround we pretend that the type comes from
1467 let file_metadata = unknown_file_metadata(cx);
1469 let def = enum_type.ty_adt_def().unwrap();
1470 let enumerators_metadata: Vec<DIDescriptor> = def.discriminants(cx.tcx())
1473 let token = v.name.as_str();
1474 let name = CString::new(token.as_bytes()).unwrap();
1476 llvm::LLVMRustDIBuilderCreateEnumerator(
1479 // FIXME: what if enumeration has i128 discriminant?
1480 discr.to_u128_unchecked() as u64)
1485 let discriminant_type_metadata = |inttype: layout::Integer, signed: bool| {
1486 let disr_type_key = (enum_def_id, inttype);
1487 let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1489 .get(&disr_type_key).cloned();
1490 match cached_discriminant_type_metadata {
1491 Some(discriminant_type_metadata) => discriminant_type_metadata,
1493 let discriminant_llvm_type = Type::from_integer(cx, inttype);
1494 let (discriminant_size, discriminant_align) =
1495 size_and_align_of(cx, discriminant_llvm_type);
1496 let discriminant_base_type_metadata =
1498 inttype.to_ty(&cx.tcx(), signed),
1499 syntax_pos::DUMMY_SP);
1500 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1502 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1503 let discriminant_type_metadata = unsafe {
1504 llvm::LLVMRustDIBuilderCreateEnumerationType(
1509 UNKNOWN_LINE_NUMBER,
1510 bytes_to_bits(discriminant_size),
1511 bytes_to_bits(discriminant_align),
1512 create_DIArray(DIB(cx), &enumerators_metadata),
1513 discriminant_base_type_metadata)
1516 debug_context(cx).created_enum_disr_types
1518 .insert(disr_type_key, discriminant_type_metadata);
1520 discriminant_type_metadata
1525 let type_rep = cx.layout_of(enum_type);
1527 let discriminant_type_metadata = match *type_rep {
1528 layout::CEnum { discr, signed, .. } => {
1529 return FinalMetadata(discriminant_type_metadata(discr, signed))
1531 layout::RawNullablePointer { .. } |
1532 layout::StructWrappedNullablePointer { .. } |
1533 layout::Univariant { .. } => None,
1534 layout::General { discr, .. } => Some(discriminant_type_metadata(discr, false)),
1535 ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1538 let enum_llvm_type = type_of::type_of(cx, enum_type);
1539 let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
1541 let enum_name = CString::new(enum_name).unwrap();
1542 let unique_type_id_str = CString::new(
1543 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1545 let enum_metadata = unsafe {
1546 llvm::LLVMRustDIBuilderCreateUnionType(
1551 UNKNOWN_LINE_NUMBER,
1552 bytes_to_bits(enum_type_size),
1553 bytes_to_bits(enum_type_align),
1557 unique_type_id_str.as_ptr())
1560 return create_and_register_recursive_type_forward_declaration(
1566 EnumMDF(EnumMemberDescriptionFactory {
1567 enum_type: enum_type,
1568 type_rep: type_rep.layout,
1569 discriminant_type_metadata: discriminant_type_metadata,
1570 containing_scope: containing_scope,
1571 file_metadata: file_metadata,
1576 fn get_enum_discriminant_name(cx: &CrateContext,
1579 cx.tcx().item_name(def_id).as_str()
1583 /// Creates debug information for a composite type, that is, anything that
1584 /// results in a LLVM struct.
1586 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1587 fn composite_type_metadata(cx: &CrateContext,
1588 composite_llvm_type: Type,
1589 composite_type_name: &str,
1590 composite_type_unique_id: UniqueTypeId,
1591 member_descriptions: &[MemberDescription],
1592 containing_scope: DIScope,
1594 // Ignore source location information as long as it
1595 // can't be reconstructed for non-local crates.
1596 _file_metadata: DIFile,
1597 _definition_span: Span)
1598 -> DICompositeType {
1599 // Create the (empty) struct metadata node ...
1600 let composite_type_metadata = create_struct_stub(cx,
1601 composite_llvm_type,
1602 composite_type_name,
1603 composite_type_unique_id,
1605 // ... and immediately create and add the member descriptions.
1606 set_members_of_composite_type(cx,
1607 composite_type_metadata,
1608 composite_llvm_type,
1609 member_descriptions);
1611 return composite_type_metadata;
1614 fn set_members_of_composite_type(cx: &CrateContext,
1615 composite_type_metadata: DICompositeType,
1616 composite_llvm_type: Type,
1617 member_descriptions: &[MemberDescription]) {
1618 // In some rare cases LLVM metadata uniquing would lead to an existing type
1619 // description being used instead of a new one created in
1620 // create_struct_stub. This would cause a hard to trace assertion in
1621 // DICompositeType::SetTypeArray(). The following check makes sure that we
1622 // get a better error message if this should happen again due to some
1625 let mut composite_types_completed =
1626 debug_context(cx).composite_types_completed.borrow_mut();
1627 if composite_types_completed.contains(&composite_type_metadata) {
1628 bug!("debuginfo::set_members_of_composite_type() - \
1629 Already completed forward declaration re-encountered.");
1631 composite_types_completed.insert(composite_type_metadata);
1635 let member_metadata: Vec<DIDescriptor> = member_descriptions
1638 .map(|(i, member_description)| {
1639 let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
1640 let member_offset = match member_description.offset {
1641 FixedMemberOffset { bytes } => bytes as u64,
1642 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
1645 let member_name = member_description.name.as_bytes();
1646 let member_name = CString::new(member_name).unwrap();
1648 llvm::LLVMRustDIBuilderCreateMemberType(
1650 composite_type_metadata,
1651 member_name.as_ptr(),
1652 unknown_file_metadata(cx),
1653 UNKNOWN_LINE_NUMBER,
1654 bytes_to_bits(member_size),
1655 bytes_to_bits(member_align),
1656 bytes_to_bits(member_offset),
1657 member_description.flags,
1658 member_description.type_metadata)
1664 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1665 llvm::LLVMRustDICompositeTypeSetTypeArray(
1666 DIB(cx), composite_type_metadata, type_array);
1670 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1671 // any caching, does not add any fields to the struct. This can be done later
1672 // with set_members_of_composite_type().
1673 fn create_struct_stub(cx: &CrateContext,
1674 struct_llvm_type: Type,
1675 struct_type_name: &str,
1676 unique_type_id: UniqueTypeId,
1677 containing_scope: DIScope)
1678 -> DICompositeType {
1679 let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
1681 let name = CString::new(struct_type_name).unwrap();
1682 let unique_type_id = CString::new(
1683 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1685 let metadata_stub = unsafe {
1686 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1687 // pointer will lead to hard to trace and debug LLVM assertions
1688 // later on in llvm/lib/IR/Value.cpp.
1689 let empty_array = create_DIArray(DIB(cx), &[]);
1691 llvm::LLVMRustDIBuilderCreateStructType(
1695 unknown_file_metadata(cx),
1696 UNKNOWN_LINE_NUMBER,
1697 bytes_to_bits(struct_size),
1698 bytes_to_bits(struct_align),
1704 unique_type_id.as_ptr())
1707 return metadata_stub;
1710 fn create_union_stub(cx: &CrateContext,
1711 union_llvm_type: Type,
1712 union_type_name: &str,
1713 unique_type_id: UniqueTypeId,
1714 containing_scope: DIScope)
1715 -> DICompositeType {
1716 let (union_size, union_align) = size_and_align_of(cx, union_llvm_type);
1718 let name = CString::new(union_type_name).unwrap();
1719 let unique_type_id = CString::new(
1720 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id).as_bytes()
1722 let metadata_stub = unsafe {
1723 // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
1724 // pointer will lead to hard to trace and debug LLVM assertions
1725 // later on in llvm/lib/IR/Value.cpp.
1726 let empty_array = create_DIArray(DIB(cx), &[]);
1728 llvm::LLVMRustDIBuilderCreateUnionType(
1732 unknown_file_metadata(cx),
1733 UNKNOWN_LINE_NUMBER,
1734 bytes_to_bits(union_size),
1735 bytes_to_bits(union_align),
1739 unique_type_id.as_ptr())
1742 return metadata_stub;
1745 /// Creates debug information for the given global variable.
1747 /// Adds the created metadata nodes directly to the crate's IR.
1748 pub fn create_global_var_metadata(cx: &CrateContext,
1749 node_id: ast::NodeId,
1751 if cx.dbg_cx().is_none() {
1757 let node_def_id = tcx.hir.local_def_id(node_id);
1758 let (var_scope, span) = get_namespace_and_span_for_item(cx, node_def_id);
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)
1764 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1767 let is_local_to_unit = is_node_local_to_unit(cx, node_id);
1768 let variable_type = common::def_ty(cx.shared(), node_def_id, Substs::empty());
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, "");
1773 let var_name = CString::new(var_name).unwrap();
1774 let linkage_name = CString::new(linkage_name).unwrap();
1776 let global_align = cx.align_of(variable_type);
1779 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1782 linkage_name.as_ptr(),
1794 // Creates an "extension" of an existing DIScope into another file.
1795 pub fn extend_scope_to_file(ccx: &CrateContext,
1796 scope_metadata: DIScope,
1797 file: &syntax_pos::FileMap)
1799 let file_metadata = file_metadata(ccx, &file.name, &file.abs_path);
1801 llvm::LLVMRustDIBuilderCreateLexicalBlockFile(