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, DICompositeType, DILexicalBlock};
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;
33 use rustc_data_structures::blake2b;
34 use {type_of, machine, monomorphize};
35 use common::CrateContext;
37 use rustc::ty::{self, AdtKind, Ty, layout};
39 use util::nodemap::FnvHashMap;
40 use util::common::path2cstr;
42 use libc::{c_uint, c_longlong};
43 use std::ffi::CString;
48 use syntax::util::interner::Interner;
50 use syntax::parse::token;
51 use syntax_pos::{self, Span};
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;
68 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
69 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
71 // ptr::null() doesn't work :(
72 pub const NO_SCOPE_METADATA: DIScope = (0 as DIScope);
74 const FLAGS_NONE: c_uint = 0;
76 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
77 pub struct UniqueTypeId(ast::Name);
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
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>
94 impl<'tcx> TypeMap<'tcx> {
95 pub fn new() -> TypeMap<'tcx> {
97 unique_id_interner: Interner::new(),
98 type_to_metadata: FnvHashMap(),
99 unique_id_to_metadata: FnvHashMap(),
100 type_to_unique_id: FnvHashMap(),
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,
109 if self.type_to_metadata.insert(type_, metadata).is_some() {
110 bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
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,
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[..]);
126 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
127 self.type_to_metadata.get(&type_).cloned()
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()
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)
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 */}
152 let mut type_id_hasher = TypeIdHasher::new(cx.tcx(),
153 DebugInfoTypeIdHasher::new());
154 type_id_hasher.visit_ty(type_);
155 let hash = type_id_hasher.into_inner().into_hash();
157 let mut unique_type_id = String::with_capacity(TYPE_ID_HASH_LENGTH * 2);
159 for byte in hash.into_iter() {
160 write!(&mut unique_type_id, "{:x}", byte).unwrap();
163 let key = self.unique_id_interner.intern(&unique_type_id);
164 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
166 return UniqueTypeId(key);
168 // The hasher we are using to generate the UniqueTypeId. We want
169 // something that provides more than the 64 bits of the DefaultHasher.
170 const TYPE_ID_HASH_LENGTH: usize = 20;
172 struct DebugInfoTypeIdHasher {
173 state: blake2b::Blake2bCtx
176 impl ::std::hash::Hasher for DebugInfoTypeIdHasher {
177 fn finish(&self) -> u64 {
182 fn write(&mut self, bytes: &[u8]) {
183 blake2b::blake2b_update(&mut self.state, bytes);
187 impl DebugInfoTypeIdHasher {
188 fn new() -> DebugInfoTypeIdHasher {
189 DebugInfoTypeIdHasher {
190 state: blake2b::blake2b_new(TYPE_ID_HASH_LENGTH, &[])
194 fn into_hash(self) -> [u8; TYPE_ID_HASH_LENGTH] {
195 let mut hash = [0u8; TYPE_ID_HASH_LENGTH];
196 blake2b::blake2b_final(self.state, &mut hash);
202 // Get the UniqueTypeId for an enum variant. Enum variants are not really
203 // types of their own, so they need special handling. We still need a
204 // UniqueTypeId for them, since to debuginfo they *are* real types.
205 fn get_unique_type_id_of_enum_variant<'a>(&mut self,
206 cx: &CrateContext<'a, 'tcx>,
210 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
211 let enum_variant_type_id = format!("{}::{}",
212 &self.get_unique_type_id_as_string(enum_type_id),
214 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
215 UniqueTypeId(interner_key)
219 // A description of some recursive type. It can either be already finished (as
220 // with FinalMetadata) or it is not yet finished, but contains all information
221 // needed to generate the missing parts of the description. See the
222 // documentation section on Recursive Types at the top of this file for more
224 enum RecursiveTypeDescription<'tcx> {
226 unfinished_type: Ty<'tcx>,
227 unique_type_id: UniqueTypeId,
228 metadata_stub: DICompositeType,
230 member_description_factory: MemberDescriptionFactory<'tcx>,
232 FinalMetadata(DICompositeType)
235 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
236 cx: &CrateContext<'a, 'tcx>,
237 unfinished_type: Ty<'tcx>,
238 unique_type_id: UniqueTypeId,
239 metadata_stub: DICompositeType,
241 member_description_factory: MemberDescriptionFactory<'tcx>)
242 -> RecursiveTypeDescription<'tcx> {
244 // Insert the stub into the TypeMap in order to allow for recursive references
245 let mut type_map = debug_context(cx).type_map.borrow_mut();
246 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
247 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
250 unfinished_type: unfinished_type,
251 unique_type_id: unique_type_id,
252 metadata_stub: metadata_stub,
253 llvm_type: llvm_type,
254 member_description_factory: member_description_factory,
258 impl<'tcx> RecursiveTypeDescription<'tcx> {
259 // Finishes up the description of the type in question (mostly by providing
260 // descriptions of the fields of the given type) and returns the final type
262 fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
264 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
270 ref member_description_factory,
273 // Make sure that we have a forward declaration of the type in
274 // the TypeMap so that recursive references are possible. This
275 // will always be the case if the RecursiveTypeDescription has
276 // been properly created through the
277 // create_and_register_recursive_type_forward_declaration()
280 let type_map = debug_context(cx).type_map.borrow();
281 if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
282 type_map.find_metadata_for_type(unfinished_type).is_none() {
283 bug!("Forward declaration of potentially recursive type \
284 '{:?}' was not found in TypeMap!",
289 // ... then create the member descriptions ...
290 let member_descriptions =
291 member_description_factory.create_member_descriptions(cx);
293 // ... and attach them to the stub to complete it.
294 set_members_of_composite_type(cx,
297 &member_descriptions[..]);
298 return MetadataCreationResult::new(metadata_stub, true);
304 // Returns from the enclosing function if the type metadata with the given
305 // unique id can be found in the type map
306 macro_rules! return_if_metadata_created_in_meantime {
307 ($cx: expr, $unique_type_id: expr) => (
308 match debug_context($cx).type_map
310 .find_metadata_for_unique_id($unique_type_id) {
311 Some(metadata) => return MetadataCreationResult::new(metadata, true),
312 None => { /* proceed normally */ }
317 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
318 unique_type_id: UniqueTypeId,
319 element_type: Ty<'tcx>,
322 -> MetadataCreationResult {
323 let element_type_metadata = type_metadata(cx, element_type, span);
325 return_if_metadata_created_in_meantime!(cx, unique_type_id);
327 let element_llvm_type = type_of::type_of(cx, element_type);
328 let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
330 let (array_size_in_bytes, upper_bound) = match len {
331 Some(len) => (element_type_size * len, len as c_longlong),
335 let subrange = unsafe {
336 llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
339 let subscripts = create_DIArray(DIB(cx), &[subrange]);
340 let metadata = unsafe {
341 llvm::LLVMRustDIBuilderCreateArrayType(
343 bytes_to_bits(array_size_in_bytes),
344 bytes_to_bits(element_type_align),
345 element_type_metadata,
349 return MetadataCreationResult::new(metadata, false);
352 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
354 element_type: Ty<'tcx>,
355 unique_type_id: UniqueTypeId,
357 -> MetadataCreationResult {
358 let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
360 mutbl: hir::MutImmutable
363 let element_type_metadata = type_metadata(cx, data_ptr_type, span);
365 return_if_metadata_created_in_meantime!(cx, unique_type_id);
367 let slice_llvm_type = type_of::type_of(cx, vec_type);
368 let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
370 let member_llvm_types = slice_llvm_type.field_types();
371 assert!(slice_layout_is_correct(cx,
372 &member_llvm_types[..],
374 let member_descriptions = [
376 name: "data_ptr".to_string(),
377 llvm_type: member_llvm_types[0],
378 type_metadata: element_type_metadata,
379 offset: ComputedMemberOffset,
383 name: "length".to_string(),
384 llvm_type: member_llvm_types[1],
385 type_metadata: type_metadata(cx, cx.tcx().types.usize, span),
386 offset: ComputedMemberOffset,
391 assert!(member_descriptions.len() == member_llvm_types.len());
393 let loc = span_start(cx, span);
394 let file_metadata = file_metadata(cx, &loc.file.name, &loc.file.abs_path);
396 let metadata = composite_type_metadata(cx,
398 &slice_type_name[..],
400 &member_descriptions,
404 return MetadataCreationResult::new(metadata, false);
406 fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
407 member_llvm_types: &[Type],
408 element_type: Ty<'tcx>)
410 member_llvm_types.len() == 2 &&
411 member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
412 member_llvm_types[1] == cx.int_type()
416 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
417 unique_type_id: UniqueTypeId,
418 signature: &ty::PolyFnSig<'tcx>,
420 -> MetadataCreationResult
422 let signature = cx.tcx().erase_late_bound_regions(signature);
424 let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs.len() + 1);
427 signature_metadata.push(match signature.output.sty {
428 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
429 _ => type_metadata(cx, signature.output, span)
433 for &argument_type in &signature.inputs {
434 signature_metadata.push(type_metadata(cx, argument_type, span));
437 return_if_metadata_created_in_meantime!(cx, unique_type_id);
439 return MetadataCreationResult::new(
441 llvm::LLVMRustDIBuilderCreateSubroutineType(
443 unknown_file_metadata(cx),
444 create_DIArray(DIB(cx), &signature_metadata[..]))
449 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
450 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
451 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
452 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
453 // of a DST struct, there is no trait_object_type and the results of this
454 // function will be a little bit weird.
455 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
456 trait_type: Ty<'tcx>,
457 trait_object_type: Option<Ty<'tcx>>,
458 unique_type_id: UniqueTypeId)
460 // The implementation provided here is a stub. It makes sure that the trait
461 // type is assigned the correct name, size, namespace, and source location.
462 // But it does not describe the trait's methods.
464 let def_id = match trait_type.sty {
465 ty::TyTrait(ref data) => data.principal.def_id(),
467 bug!("debuginfo: Unexpected trait-object type in \
468 trait_pointer_metadata(): {:?}",
473 let trait_object_type = trait_object_type.unwrap_or(trait_type);
474 let trait_type_name =
475 compute_debuginfo_type_name(cx, trait_object_type, false);
477 let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
479 let trait_llvm_type = type_of::type_of(cx, trait_object_type);
480 let file_metadata = unknown_file_metadata(cx);
482 composite_type_metadata(cx,
484 &trait_type_name[..],
489 syntax_pos::DUMMY_SP)
492 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
494 usage_site_span: Span)
496 // Get the unique type id of this type.
497 let unique_type_id = {
498 let mut type_map = debug_context(cx).type_map.borrow_mut();
499 // First, try to find the type in TypeMap. If we have seen it before, we
500 // can exit early here.
501 match type_map.find_metadata_for_type(t) {
506 // The Ty is not in the TypeMap but maybe we have already seen
507 // an equivalent type (e.g. only differing in region arguments).
508 // In order to find out, generate the unique type id and look
510 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
511 match type_map.find_metadata_for_unique_id(unique_type_id) {
513 // There is already an equivalent type in the TypeMap.
514 // Register this Ty as an alias in the cache and
515 // return the cached metadata.
516 type_map.register_type_with_metadata(t, metadata);
520 // There really is no type metadata for this type, so
521 // proceed by creating it.
529 debug!("type_metadata: {:?}", t);
532 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
539 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
541 ty::TyTuple(ref elements) if elements.is_empty() => {
542 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
544 ty::TyArray(typ, len) => {
545 fixed_vec_metadata(cx, unique_type_id, typ, Some(len as u64), usage_site_span)
547 ty::TySlice(typ) => {
548 fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
551 fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
554 MetadataCreationResult::new(
555 trait_pointer_metadata(cx, t, None, unique_type_id),
559 ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
560 ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
562 ty::TySlice(typ) => {
563 vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
566 vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span)
569 MetadataCreationResult::new(
570 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
574 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
576 match debug_context(cx).type_map
578 .find_metadata_for_unique_id(unique_type_id) {
579 Some(metadata) => return metadata,
580 None => { /* proceed normally */ }
583 MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
588 ty::TyFnDef(.., ref barefnty) | ty::TyFnPtr(ref barefnty) => {
589 let fn_metadata = subroutine_type_metadata(cx,
592 usage_site_span).metadata;
593 match debug_context(cx).type_map
595 .find_metadata_for_unique_id(unique_type_id) {
596 Some(metadata) => return metadata,
597 None => { /* proceed normally */ }
600 // This is actually a function pointer, so wrap it in pointer DI
601 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
604 ty::TyClosure(_, ref substs) => {
605 prepare_tuple_metadata(cx,
609 usage_site_span).finalize(cx)
611 ty::TyAdt(def, ..) => match def.adt_kind() {
613 prepare_struct_metadata(cx,
616 usage_site_span).finalize(cx)
619 prepare_union_metadata(cx,
622 usage_site_span).finalize(cx)
625 prepare_enum_metadata(cx,
629 usage_site_span).finalize(cx)
632 ty::TyTuple(ref elements) => {
633 prepare_tuple_metadata(cx,
637 usage_site_span).finalize(cx)
640 bug!("debuginfo: unexpected type in type_metadata: {:?}", sty)
645 let mut type_map = debug_context(cx).type_map.borrow_mut();
647 if already_stored_in_typemap {
648 // Also make sure that we already have a TypeMap entry for the unique type id.
649 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
650 Some(metadata) => metadata,
652 let unique_type_id_str =
653 type_map.get_unique_type_id_as_string(unique_type_id);
654 span_bug!(usage_site_span,
655 "Expected type metadata for unique \
656 type id '{}' to already be in \
657 the debuginfo::TypeMap but it \
659 &unique_type_id_str[..],
664 match type_map.find_metadata_for_type(t) {
666 if metadata != metadata_for_uid {
667 let unique_type_id_str =
668 type_map.get_unique_type_id_as_string(unique_type_id);
669 span_bug!(usage_site_span,
670 "Mismatch between Ty and \
671 UniqueTypeId maps in \
672 debuginfo::TypeMap. \
673 UniqueTypeId={}, Ty={}",
674 &unique_type_id_str[..],
679 type_map.register_type_with_metadata(t, metadata);
683 type_map.register_type_with_metadata(t, metadata);
684 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
691 pub fn file_metadata(cx: &CrateContext, path: &str, full_path: &Option<String>) -> DIFile {
692 // FIXME (#9639): This needs to handle non-utf8 paths
693 let work_dir = cx.sess().working_dir.to_str().unwrap();
695 full_path.as_ref().map(|p| p.as_str()).unwrap_or_else(|| {
696 if path.starts_with(work_dir) {
697 &path[work_dir.len() + 1..path.len()]
703 file_metadata_(cx, path, file_name, &work_dir)
706 pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile {
707 // Regular filenames should not be empty, so we abuse an empty name as the
708 // key for the special unknown file metadata
709 file_metadata_(cx, "", "<unknown>", "")
713 fn file_metadata_(cx: &CrateContext, key: &str, file_name: &str, work_dir: &str) -> DIFile {
714 if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(key) {
715 return *file_metadata;
718 debug!("file_metadata: file_name: {}, work_dir: {}", file_name, work_dir);
720 let file_name = CString::new(file_name).unwrap();
721 let work_dir = CString::new(work_dir).unwrap();
722 let file_metadata = unsafe {
723 llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(),
727 let mut created_files = debug_context(cx).created_files.borrow_mut();
728 created_files.insert(key.to_string(), file_metadata);
732 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
733 t: Ty<'tcx>) -> DIType {
735 debug!("basic_type_metadata: {:?}", t);
737 let (name, encoding) = match t.sty {
738 ty::TyNever => ("!", DW_ATE_unsigned),
739 ty::TyTuple(ref elements) if elements.is_empty() =>
740 ("()", DW_ATE_unsigned),
741 ty::TyBool => ("bool", DW_ATE_boolean),
742 ty::TyChar => ("char", DW_ATE_unsigned_char),
743 ty::TyInt(int_ty) => {
744 (int_ty.ty_to_string(), DW_ATE_signed)
746 ty::TyUint(uint_ty) => {
747 (uint_ty.ty_to_string(), DW_ATE_unsigned)
749 ty::TyFloat(float_ty) => {
750 (float_ty.ty_to_string(), DW_ATE_float)
752 _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
755 let llvm_type = type_of::type_of(cx, t);
756 let (size, align) = size_and_align_of(cx, llvm_type);
757 let name = CString::new(name).unwrap();
758 let ty_metadata = unsafe {
759 llvm::LLVMRustDIBuilderCreateBasicType(
763 bytes_to_bits(align),
770 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
771 pointer_type: Ty<'tcx>,
772 pointee_type_metadata: DIType)
774 let pointer_llvm_type = type_of::type_of(cx, pointer_type);
775 let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
776 let name = compute_debuginfo_type_name(cx, pointer_type, false);
777 let name = CString::new(name).unwrap();
778 let ptr_metadata = unsafe {
779 llvm::LLVMRustDIBuilderCreatePointerType(
781 pointee_type_metadata,
782 bytes_to_bits(pointer_size),
783 bytes_to_bits(pointer_align),
789 pub fn compile_unit_metadata(scc: &SharedCrateContext,
790 debug_context: &CrateDebugContext,
793 let work_dir = &sess.working_dir;
794 let compile_unit_name = match sess.local_crate_source_file {
795 None => fallback_path(scc),
796 Some(ref abs_path) => {
797 if abs_path.is_relative() {
798 sess.warn("debuginfo: Invalid path to crate's local root source file!");
801 match abs_path.strip_prefix(work_dir) {
802 Ok(ref p) if p.is_relative() => {
803 if p.starts_with(Path::new("./")) {
806 path2cstr(&Path::new(".").join(p))
809 _ => fallback_path(scc)
815 debug!("compile_unit_metadata: {:?}", compile_unit_name);
816 let producer = format!("rustc version {}",
817 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
819 let compile_unit_name = compile_unit_name.as_ptr();
820 let work_dir = path2cstr(&work_dir);
821 let producer = CString::new(producer).unwrap();
823 let split_name = "\0";
825 llvm::LLVMRustDIBuilderCreateCompileUnit(
826 debug_context.builder,
831 sess.opts.optimize != config::OptLevel::No,
832 flags.as_ptr() as *const _,
834 split_name.as_ptr() as *const _)
837 fn fallback_path(scc: &SharedCrateContext) -> CString {
838 CString::new(scc.link_meta().crate_name.clone()).unwrap()
842 struct MetadataCreationResult {
844 already_stored_in_typemap: bool
847 impl MetadataCreationResult {
848 fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
849 MetadataCreationResult {
851 already_stored_in_typemap: already_stored_in_typemap
858 FixedMemberOffset { bytes: usize },
859 // For ComputedMemberOffset, the offset is read from the llvm type definition.
863 // Description of a type member, which can either be a regular field (as in
864 // structs or tuples) or an enum variant.
866 struct MemberDescription {
869 type_metadata: DIType,
870 offset: MemberOffset,
874 // A factory for MemberDescriptions. It produces a list of member descriptions
875 // for some record-like type. MemberDescriptionFactories are used to defer the
876 // creation of type member descriptions in order to break cycles arising from
877 // recursive type definitions.
878 enum MemberDescriptionFactory<'tcx> {
879 StructMDF(StructMemberDescriptionFactory<'tcx>),
880 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
881 EnumMDF(EnumMemberDescriptionFactory<'tcx>),
882 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
883 VariantMDF(VariantMemberDescriptionFactory<'tcx>)
886 impl<'tcx> MemberDescriptionFactory<'tcx> {
887 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
888 -> Vec<MemberDescription> {
890 StructMDF(ref this) => {
891 this.create_member_descriptions(cx)
893 TupleMDF(ref this) => {
894 this.create_member_descriptions(cx)
896 EnumMDF(ref this) => {
897 this.create_member_descriptions(cx)
899 UnionMDF(ref this) => {
900 this.create_member_descriptions(cx)
902 VariantMDF(ref this) => {
903 this.create_member_descriptions(cx)
909 //=-----------------------------------------------------------------------------
911 //=-----------------------------------------------------------------------------
913 // Creates MemberDescriptions for the fields of a struct
914 struct StructMemberDescriptionFactory<'tcx> {
915 variant: ty::VariantDef<'tcx>,
916 substs: &'tcx Substs<'tcx>,
921 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
922 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
923 -> Vec<MemberDescription> {
924 let field_size = if self.is_simd {
925 let fty = monomorphize::field_ty(cx.tcx(),
927 &self.variant.fields[0]);
928 Some(machine::llsize_of_alloc(
930 type_of::type_of(cx, fty)
936 self.variant.fields.iter().enumerate().map(|(i, f)| {
937 let name = if self.variant.ctor_kind == CtorKind::Fn {
942 let fty = monomorphize::field_ty(cx.tcx(), self.substs, f);
944 let offset = if self.is_simd {
945 FixedMemberOffset { bytes: i * field_size.unwrap() }
952 llvm_type: type_of::type_of(cx, fty),
953 type_metadata: type_metadata(cx, fty, self.span),
962 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
963 struct_type: Ty<'tcx>,
964 unique_type_id: UniqueTypeId,
966 -> RecursiveTypeDescription<'tcx> {
967 let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
968 let struct_llvm_type = type_of::in_memory_type_of(cx, struct_type);
970 let (struct_def_id, variant, substs) = match struct_type.sty {
971 ty::TyAdt(def, substs) => (def.did, def.struct_variant(), substs),
972 _ => bug!("prepare_struct_metadata on a non-ADT")
975 let (containing_scope, _) = get_namespace_and_span_for_item(cx, struct_def_id);
977 let struct_metadata_stub = create_struct_stub(cx,
983 create_and_register_recursive_type_forward_declaration(
987 struct_metadata_stub,
989 StructMDF(StructMemberDescriptionFactory {
992 is_simd: struct_type.is_simd(),
998 //=-----------------------------------------------------------------------------
1000 //=-----------------------------------------------------------------------------
1002 // Creates MemberDescriptions for the fields of a tuple
1003 struct TupleMemberDescriptionFactory<'tcx> {
1004 component_types: Vec<Ty<'tcx>>,
1008 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1009 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1010 -> Vec<MemberDescription> {
1011 self.component_types
1014 .map(|(i, &component_type)| {
1016 name: format!("__{}", i),
1017 llvm_type: type_of::type_of(cx, component_type),
1018 type_metadata: type_metadata(cx, component_type, self.span),
1019 offset: ComputedMemberOffset,
1026 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1027 tuple_type: Ty<'tcx>,
1028 component_types: &[Ty<'tcx>],
1029 unique_type_id: UniqueTypeId,
1031 -> RecursiveTypeDescription<'tcx> {
1032 let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1033 let tuple_llvm_type = type_of::type_of(cx, tuple_type);
1035 create_and_register_recursive_type_forward_declaration(
1039 create_struct_stub(cx,
1045 TupleMDF(TupleMemberDescriptionFactory {
1046 component_types: component_types.to_vec(),
1052 //=-----------------------------------------------------------------------------
1054 //=-----------------------------------------------------------------------------
1056 struct UnionMemberDescriptionFactory<'tcx> {
1057 variant: ty::VariantDef<'tcx>,
1058 substs: &'tcx Substs<'tcx>,
1062 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1063 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1064 -> Vec<MemberDescription> {
1065 self.variant.fields.iter().map(|field| {
1066 let fty = monomorphize::field_ty(cx.tcx(), self.substs, field);
1068 name: field.name.to_string(),
1069 llvm_type: type_of::type_of(cx, fty),
1070 type_metadata: type_metadata(cx, fty, self.span),
1071 offset: FixedMemberOffset { bytes: 0 },
1078 fn prepare_union_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1079 union_type: Ty<'tcx>,
1080 unique_type_id: UniqueTypeId,
1082 -> RecursiveTypeDescription<'tcx> {
1083 let union_name = compute_debuginfo_type_name(cx, union_type, false);
1084 let union_llvm_type = type_of::in_memory_type_of(cx, union_type);
1086 let (union_def_id, variant, substs) = match union_type.sty {
1087 ty::TyAdt(def, substs) => (def.did, def.struct_variant(), substs),
1088 _ => bug!("prepare_union_metadata on a non-ADT")
1091 let (containing_scope, _) = get_namespace_and_span_for_item(cx, union_def_id);
1093 let union_metadata_stub = create_union_stub(cx,
1099 create_and_register_recursive_type_forward_declaration(
1103 union_metadata_stub,
1105 UnionMDF(UnionMemberDescriptionFactory {
1113 //=-----------------------------------------------------------------------------
1115 //=-----------------------------------------------------------------------------
1117 // Describes the members of an enum value: An enum is described as a union of
1118 // structs in DWARF. This MemberDescriptionFactory provides the description for
1119 // the members of this union; so for every variant of the given enum, this
1120 // factory will produce one MemberDescription (all with no name and a fixed
1121 // offset of zero bytes).
1122 struct EnumMemberDescriptionFactory<'tcx> {
1123 enum_type: Ty<'tcx>,
1124 type_rep: &'tcx layout::Layout,
1125 discriminant_type_metadata: Option<DIType>,
1126 containing_scope: DIScope,
1127 file_metadata: DIFile,
1131 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1132 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1133 -> Vec<MemberDescription> {
1134 let adt = &self.enum_type.ty_adt_def().unwrap();
1135 let substs = match self.enum_type.sty {
1136 ty::TyAdt(def, ref s) if def.adt_kind() == AdtKind::Enum => s,
1137 _ => bug!("{} is not an enum", self.enum_type)
1139 match *self.type_rep {
1140 layout::General { ref variants, .. } => {
1141 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1146 .map(|(i, struct_def)| {
1147 let (variant_type_metadata,
1149 member_desc_factory) =
1150 describe_enum_variant(cx,
1155 self.containing_scope,
1158 let member_descriptions = member_desc_factory
1159 .create_member_descriptions(cx);
1161 set_members_of_composite_type(cx,
1162 variant_type_metadata,
1164 &member_descriptions);
1166 name: "".to_string(),
1167 llvm_type: variant_llvm_type,
1168 type_metadata: variant_type_metadata,
1169 offset: FixedMemberOffset { bytes: 0 },
1174 layout::Univariant{ ref variant, .. } => {
1175 assert!(adt.variants.len() <= 1);
1177 if adt.variants.is_empty() {
1180 let (variant_type_metadata,
1182 member_description_factory) =
1183 describe_enum_variant(cx,
1188 self.containing_scope,
1191 let member_descriptions =
1192 member_description_factory.create_member_descriptions(cx);
1194 set_members_of_composite_type(cx,
1195 variant_type_metadata,
1197 &member_descriptions[..]);
1200 name: "".to_string(),
1201 llvm_type: variant_llvm_type,
1202 type_metadata: variant_type_metadata,
1203 offset: FixedMemberOffset { bytes: 0 },
1209 layout::RawNullablePointer { nndiscr: non_null_variant_index, .. } => {
1210 // As far as debuginfo is concerned, the pointer this enum
1211 // represents is still wrapped in a struct. This is to make the
1212 // DWARF representation of enums uniform.
1214 // First create a description of the artificial wrapper struct:
1215 let non_null_variant = &adt.variants[non_null_variant_index as usize];
1216 let non_null_variant_name = non_null_variant.name.as_str();
1218 // The llvm type and metadata of the pointer
1219 let nnty = monomorphize::field_ty(cx.tcx(), &substs, &non_null_variant.fields[0] );
1220 let non_null_llvm_type = type_of::type_of(cx, nnty);
1221 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
1223 // The type of the artificial struct wrapping the pointer
1224 let artificial_struct_llvm_type = Type::struct_(cx,
1225 &[non_null_llvm_type],
1228 // For the metadata of the wrapper struct, we need to create a
1229 // MemberDescription of the struct's single field.
1230 let sole_struct_member_description = MemberDescription {
1231 name: match non_null_variant.ctor_kind {
1232 CtorKind::Fn => "__0".to_string(),
1233 CtorKind::Fictive => {
1234 non_null_variant.fields[0].name.to_string()
1236 CtorKind::Const => bug!()
1238 llvm_type: non_null_llvm_type,
1239 type_metadata: non_null_type_metadata,
1240 offset: FixedMemberOffset { bytes: 0 },
1244 let unique_type_id = debug_context(cx).type_map
1246 .get_unique_type_id_of_enum_variant(
1249 &non_null_variant_name);
1251 // Now we can create the metadata of the artificial struct
1252 let artificial_struct_metadata =
1253 composite_type_metadata(cx,
1254 artificial_struct_llvm_type,
1255 &non_null_variant_name,
1257 &[sole_struct_member_description],
1258 self.containing_scope,
1260 syntax_pos::DUMMY_SP);
1262 // Encode the information about the null variant in the union
1264 let null_variant_index = (1 - non_null_variant_index) as usize;
1265 let null_variant_name = adt.variants[null_variant_index].name;
1266 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1270 // Finally create the (singleton) list of descriptions of union
1274 name: union_member_name,
1275 llvm_type: artificial_struct_llvm_type,
1276 type_metadata: artificial_struct_metadata,
1277 offset: FixedMemberOffset { bytes: 0 },
1282 layout::StructWrappedNullablePointer { nonnull: ref struct_def,
1284 ref discrfield, ..} => {
1285 // Create a description of the non-null variant
1286 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
1287 describe_enum_variant(cx,
1290 &adt.variants[nndiscr as usize],
1291 OptimizedDiscriminant,
1292 self.containing_scope,
1295 let variant_member_descriptions =
1296 member_description_factory.create_member_descriptions(cx);
1298 set_members_of_composite_type(cx,
1299 variant_type_metadata,
1301 &variant_member_descriptions[..]);
1303 // Encode the information about the null variant in the union
1305 let null_variant_index = (1 - nndiscr) as usize;
1306 let null_variant_name = adt.variants[null_variant_index].name;
1307 let discrfield = discrfield.iter()
1309 .map(|x| x.to_string())
1310 .collect::<Vec<_>>().join("$");
1311 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1315 // Create the (singleton) list of descriptions of union members.
1318 name: union_member_name,
1319 llvm_type: variant_llvm_type,
1320 type_metadata: variant_type_metadata,
1321 offset: FixedMemberOffset { bytes: 0 },
1326 layout::CEnum { .. } => span_bug!(self.span, "This should be unreachable."),
1327 ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1332 // Creates MemberDescriptions for the fields of a single enum variant.
1333 struct VariantMemberDescriptionFactory<'tcx> {
1334 args: Vec<(String, Ty<'tcx>)>,
1335 discriminant_type_metadata: Option<DIType>,
1339 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1340 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1341 -> Vec<MemberDescription> {
1342 self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1344 name: name.to_string(),
1345 llvm_type: type_of::type_of(cx, ty),
1346 type_metadata: match self.discriminant_type_metadata {
1347 Some(metadata) if i == 0 => metadata,
1348 _ => type_metadata(cx, ty, self.span)
1350 offset: ComputedMemberOffset,
1357 #[derive(Copy, Clone)]
1358 enum EnumDiscriminantInfo {
1359 RegularDiscriminant(DIType),
1360 OptimizedDiscriminant,
1364 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1365 // of the variant, and (3) a MemberDescriptionFactory for producing the
1366 // descriptions of the fields of the variant. This is a rudimentary version of a
1367 // full RecursiveTypeDescription.
1368 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1369 enum_type: Ty<'tcx>,
1370 struct_def: &layout::Struct,
1371 variant: ty::VariantDef<'tcx>,
1372 discriminant_info: EnumDiscriminantInfo,
1373 containing_scope: DIScope,
1375 -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1376 let substs = match enum_type.sty {
1377 ty::TyAdt(def, s) if def.adt_kind() == AdtKind::Enum => s,
1378 ref t @ _ => bug!("{:#?} is not an enum", t)
1381 let maybe_discr_and_signed: Option<(layout::Integer, bool)> = match *cx.layout_of(enum_type) {
1382 layout::CEnum {discr, ..} => Some((discr, true)),
1383 layout::General{discr, ..} => Some((discr, false)),
1384 layout::Univariant { .. }
1385 | layout::RawNullablePointer { .. }
1386 | layout::StructWrappedNullablePointer { .. } => None,
1387 ref l @ _ => bug!("This should be unreachable. Type is {:#?} layout is {:#?}", enum_type, l)
1390 let mut field_tys = variant.fields.iter().map(|f: ty::FieldDef<'tcx>| {
1391 monomorphize::field_ty(cx.tcx(), &substs, f)
1392 }).collect::<Vec<_>>();
1394 if let Some((discr, signed)) = maybe_discr_and_signed {
1395 field_tys.insert(0, discr.to_ty(&cx.tcx(), signed));
1399 let variant_llvm_type =
1400 Type::struct_(cx, &field_tys
1402 .map(|t| type_of::type_of(cx, t))
1403 .collect::<Vec<_>>()
1406 // Could do some consistency checks here: size, align, field count, discr type
1408 let variant_name = variant.name.as_str();
1409 let unique_type_id = debug_context(cx).type_map
1411 .get_unique_type_id_of_enum_variant(
1416 let metadata_stub = create_struct_stub(cx,
1422 // Get the argument names from the enum variant info
1423 let mut arg_names: Vec<_> = match variant.ctor_kind {
1424 CtorKind::Const => vec![],
1429 .map(|(i, _)| format!("__{}", i))
1432 CtorKind::Fictive => {
1435 .map(|f| f.name.to_string())
1440 // If this is not a univariant enum, there is also the discriminant field.
1441 match discriminant_info {
1442 RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
1443 _ => { /* do nothing */ }
1446 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1447 let args: Vec<(String, Ty)> = arg_names.iter()
1448 .zip(field_tys.iter())
1449 .map(|(s, &t)| (s.to_string(), t))
1452 let member_description_factory =
1453 VariantMDF(VariantMemberDescriptionFactory {
1455 discriminant_type_metadata: match discriminant_info {
1456 RegularDiscriminant(discriminant_type_metadata) => {
1457 Some(discriminant_type_metadata)
1464 (metadata_stub, variant_llvm_type, member_description_factory)
1467 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1468 enum_type: Ty<'tcx>,
1470 unique_type_id: UniqueTypeId,
1472 -> RecursiveTypeDescription<'tcx> {
1473 let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1475 let (containing_scope, _) = get_namespace_and_span_for_item(cx, enum_def_id);
1476 // FIXME: This should emit actual file metadata for the enum, but we
1477 // currently can't get the necessary information when it comes to types
1478 // imported from other crates. Formerly we violated the ODR when performing
1479 // LTO because we emitted debuginfo for the same type with varying file
1480 // metadata, so as a workaround we pretend that the type comes from
1482 let file_metadata = unknown_file_metadata(cx);
1484 let variants = &enum_type.ty_adt_def().unwrap().variants;
1485 let enumerators_metadata: Vec<DIDescriptor> = variants
1488 let token = v.name.as_str();
1489 let name = CString::new(token.as_bytes()).unwrap();
1491 llvm::LLVMRustDIBuilderCreateEnumerator(
1494 v.disr_val.to_u64_unchecked())
1499 let discriminant_type_metadata = |inttype: layout::Integer, signed: bool| {
1500 let disr_type_key = (enum_def_id, inttype);
1501 let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1503 .get(&disr_type_key).cloned();
1504 match cached_discriminant_type_metadata {
1505 Some(discriminant_type_metadata) => discriminant_type_metadata,
1507 let discriminant_llvm_type = Type::from_integer(cx, inttype);
1508 let (discriminant_size, discriminant_align) =
1509 size_and_align_of(cx, discriminant_llvm_type);
1510 let discriminant_base_type_metadata =
1512 inttype.to_ty(&cx.tcx(), signed),
1513 syntax_pos::DUMMY_SP);
1514 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1516 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1517 let discriminant_type_metadata = unsafe {
1518 llvm::LLVMRustDIBuilderCreateEnumerationType(
1523 UNKNOWN_LINE_NUMBER,
1524 bytes_to_bits(discriminant_size),
1525 bytes_to_bits(discriminant_align),
1526 create_DIArray(DIB(cx), &enumerators_metadata),
1527 discriminant_base_type_metadata)
1530 debug_context(cx).created_enum_disr_types
1532 .insert(disr_type_key, discriminant_type_metadata);
1534 discriminant_type_metadata
1539 let type_rep = cx.layout_of(enum_type);
1541 let discriminant_type_metadata = match *type_rep {
1542 layout::CEnum { discr, signed, .. } => {
1543 return FinalMetadata(discriminant_type_metadata(discr, signed))
1545 layout::RawNullablePointer { .. } |
1546 layout::StructWrappedNullablePointer { .. } |
1547 layout::Univariant { .. } => None,
1548 layout::General { discr, .. } => Some(discriminant_type_metadata(discr, false)),
1549 ref l @ _ => bug!("Not an enum layout: {:#?}", l)
1552 let enum_llvm_type = type_of::type_of(cx, enum_type);
1553 let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
1555 let unique_type_id_str = debug_context(cx)
1558 .get_unique_type_id_as_string(unique_type_id);
1560 let enum_name = CString::new(enum_name).unwrap();
1561 let unique_type_id_str = CString::new(unique_type_id_str.as_bytes()).unwrap();
1562 let enum_metadata = unsafe {
1563 llvm::LLVMRustDIBuilderCreateUnionType(
1568 UNKNOWN_LINE_NUMBER,
1569 bytes_to_bits(enum_type_size),
1570 bytes_to_bits(enum_type_align),
1574 unique_type_id_str.as_ptr())
1577 return create_and_register_recursive_type_forward_declaration(
1583 EnumMDF(EnumMemberDescriptionFactory {
1584 enum_type: enum_type,
1586 discriminant_type_metadata: discriminant_type_metadata,
1587 containing_scope: containing_scope,
1588 file_metadata: file_metadata,
1593 fn get_enum_discriminant_name(cx: &CrateContext,
1595 -> token::InternedString {
1596 cx.tcx().item_name(def_id).as_str()
1600 /// Creates debug information for a composite type, that is, anything that
1601 /// results in a LLVM struct.
1603 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1604 fn composite_type_metadata(cx: &CrateContext,
1605 composite_llvm_type: Type,
1606 composite_type_name: &str,
1607 composite_type_unique_id: UniqueTypeId,
1608 member_descriptions: &[MemberDescription],
1609 containing_scope: DIScope,
1611 // Ignore source location information as long as it
1612 // can't be reconstructed for non-local crates.
1613 _file_metadata: DIFile,
1614 _definition_span: Span)
1615 -> DICompositeType {
1616 // Create the (empty) struct metadata node ...
1617 let composite_type_metadata = create_struct_stub(cx,
1618 composite_llvm_type,
1619 composite_type_name,
1620 composite_type_unique_id,
1622 // ... and immediately create and add the member descriptions.
1623 set_members_of_composite_type(cx,
1624 composite_type_metadata,
1625 composite_llvm_type,
1626 member_descriptions);
1628 return composite_type_metadata;
1631 fn set_members_of_composite_type(cx: &CrateContext,
1632 composite_type_metadata: DICompositeType,
1633 composite_llvm_type: Type,
1634 member_descriptions: &[MemberDescription]) {
1635 // In some rare cases LLVM metadata uniquing would lead to an existing type
1636 // description being used instead of a new one created in
1637 // create_struct_stub. This would cause a hard to trace assertion in
1638 // DICompositeType::SetTypeArray(). The following check makes sure that we
1639 // get a better error message if this should happen again due to some
1642 let mut composite_types_completed =
1643 debug_context(cx).composite_types_completed.borrow_mut();
1644 if composite_types_completed.contains(&composite_type_metadata) {
1645 bug!("debuginfo::set_members_of_composite_type() - \
1646 Already completed forward declaration re-encountered.");
1648 composite_types_completed.insert(composite_type_metadata);
1652 let member_metadata: Vec<DIDescriptor> = member_descriptions
1655 .map(|(i, member_description)| {
1656 let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
1657 let member_offset = match member_description.offset {
1658 FixedMemberOffset { bytes } => bytes as u64,
1659 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
1662 let member_name = member_description.name.as_bytes();
1663 let member_name = CString::new(member_name).unwrap();
1665 llvm::LLVMRustDIBuilderCreateMemberType(
1667 composite_type_metadata,
1668 member_name.as_ptr(),
1669 unknown_file_metadata(cx),
1670 UNKNOWN_LINE_NUMBER,
1671 bytes_to_bits(member_size),
1672 bytes_to_bits(member_align),
1673 bytes_to_bits(member_offset),
1674 member_description.flags,
1675 member_description.type_metadata)
1681 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1682 llvm::LLVMRustDICompositeTypeSetTypeArray(
1683 DIB(cx), composite_type_metadata, type_array);
1687 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1688 // any caching, does not add any fields to the struct. This can be done later
1689 // with set_members_of_composite_type().
1690 fn create_struct_stub(cx: &CrateContext,
1691 struct_llvm_type: Type,
1692 struct_type_name: &str,
1693 unique_type_id: UniqueTypeId,
1694 containing_scope: DIScope)
1695 -> DICompositeType {
1696 let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
1698 let unique_type_id_str = debug_context(cx).type_map
1700 .get_unique_type_id_as_string(unique_type_id);
1701 let name = CString::new(struct_type_name).unwrap();
1702 let unique_type_id = CString::new(unique_type_id_str.as_bytes()).unwrap();
1703 let metadata_stub = unsafe {
1704 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1705 // pointer will lead to hard to trace and debug LLVM assertions
1706 // later on in llvm/lib/IR/Value.cpp.
1707 let empty_array = create_DIArray(DIB(cx), &[]);
1709 llvm::LLVMRustDIBuilderCreateStructType(
1713 unknown_file_metadata(cx),
1714 UNKNOWN_LINE_NUMBER,
1715 bytes_to_bits(struct_size),
1716 bytes_to_bits(struct_align),
1722 unique_type_id.as_ptr())
1725 return metadata_stub;
1728 fn create_union_stub(cx: &CrateContext,
1729 union_llvm_type: Type,
1730 union_type_name: &str,
1731 unique_type_id: UniqueTypeId,
1732 containing_scope: DIScope)
1733 -> DICompositeType {
1734 let (union_size, union_align) = size_and_align_of(cx, union_llvm_type);
1736 let unique_type_id_str = debug_context(cx).type_map
1738 .get_unique_type_id_as_string(unique_type_id);
1739 let name = CString::new(union_type_name).unwrap();
1740 let unique_type_id = CString::new(unique_type_id_str.as_bytes()).unwrap();
1741 let metadata_stub = unsafe {
1742 // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
1743 // pointer will lead to hard to trace and debug LLVM assertions
1744 // later on in llvm/lib/IR/Value.cpp.
1745 let empty_array = create_DIArray(DIB(cx), &[]);
1747 llvm::LLVMRustDIBuilderCreateUnionType(
1751 unknown_file_metadata(cx),
1752 UNKNOWN_LINE_NUMBER,
1753 bytes_to_bits(union_size),
1754 bytes_to_bits(union_align),
1758 unique_type_id.as_ptr())
1761 return metadata_stub;
1764 /// Creates debug information for the given global variable.
1766 /// Adds the created metadata nodes directly to the crate's IR.
1767 pub fn create_global_var_metadata(cx: &CrateContext,
1768 node_id: ast::NodeId,
1770 if cx.dbg_cx().is_none() {
1776 // Don't create debuginfo for globals inlined from other crates. The other
1777 // crate should already contain debuginfo for it. More importantly, the
1778 // global might not even exist in un-inlined form anywhere which would lead
1779 // to a linker errors.
1780 if tcx.map.is_inlined_node_id(node_id) {
1784 let node_def_id = tcx.map.local_def_id(node_id);
1785 let (var_scope, span) = get_namespace_and_span_for_item(cx, node_def_id);
1787 let (file_metadata, line_number) = if span != syntax_pos::DUMMY_SP {
1788 let loc = span_start(cx, span);
1789 (file_metadata(cx, &loc.file.name, &loc.file.abs_path), loc.line as c_uint)
1791 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1794 let is_local_to_unit = is_node_local_to_unit(cx, node_id);
1795 let variable_type = tcx.erase_regions(&tcx.node_id_to_type(node_id));
1796 let type_metadata = type_metadata(cx, variable_type, span);
1797 let var_name = tcx.item_name(node_def_id).to_string();
1798 let linkage_name = mangled_name_of_item(cx, node_def_id, "");
1800 let var_name = CString::new(var_name).unwrap();
1801 let linkage_name = CString::new(linkage_name).unwrap();
1803 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1806 linkage_name.as_ptr(),
1816 // Creates an "extension" of an existing DIScope into another file.
1817 pub fn extend_scope_to_file(ccx: &CrateContext,
1818 scope_metadata: DIScope,
1819 file: &syntax_pos::FileMap)
1821 let file_metadata = file_metadata(ccx, &file.name, &file.abs_path);
1823 llvm::LLVMRustDIBuilderCreateLexicalBlockFile(