1 use self::RecursiveTypeDescription::*;
2 use self::MemberDescriptionFactory::*;
3 use self::EnumDiscriminantInfo::*;
5 use super::utils::{debug_context, DIB, span_start,
6 get_namespace_for_item, create_DIArray, is_node_local_to_unit};
7 use super::namespace::mangled_name_of_instance;
8 use super::type_names::compute_debuginfo_type_name;
9 use super::{CrateDebugContext};
11 use crate::value::Value;
12 use rustc_codegen_ssa::traits::*;
15 use crate::llvm::debuginfo::{DIArray, DIType, DIFile, DIScope, DIDescriptor,
16 DICompositeType, DILexicalBlock, DIFlags, DebugEmissionKind};
19 use crate::common::CodegenCx;
20 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
21 use rustc::hir::CodegenFnAttrFlags;
22 use rustc::hir::def::CtorKind;
23 use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
24 use rustc::ich::NodeIdHashingMode;
25 use rustc::mir::Field;
26 use rustc::mir::interpret::truncate;
27 use rustc_data_structures::fingerprint::Fingerprint;
28 use rustc::ty::Instance;
29 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
30 use rustc::ty::layout::{self, Align, Integer, IntegerExt, LayoutOf,
31 PrimitiveExt, Size, TyLayout};
32 use rustc::ty::subst::UnpackedKind;
33 use rustc::session::config;
34 use rustc::util::nodemap::FxHashMap;
35 use rustc_fs_util::path_to_c_string;
36 use rustc_data_structures::small_c_str::SmallCStr;
37 use rustc_target::abi::HasDataLayout;
39 use libc::{c_uint, c_longlong};
40 use std::ffi::CString;
41 use std::fmt::{self, Write};
42 use std::hash::{Hash, Hasher};
45 use std::path::{Path, PathBuf};
47 use syntax::symbol::{Interner, InternedString, Symbol};
48 use syntax_pos::{self, Span, FileName};
50 impl PartialEq for llvm::Metadata {
51 fn eq(&self, other: &Self) -> bool {
56 impl Eq for llvm::Metadata {}
58 impl Hash for llvm::Metadata {
59 fn hash<H: Hasher>(&self, hasher: &mut H) {
60 (self as *const Self).hash(hasher);
64 impl fmt::Debug for llvm::Metadata {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 (self as *const Self).fmt(f)
71 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
72 const DW_LANG_RUST: c_uint = 0x1c;
73 #[allow(non_upper_case_globals)]
74 const DW_ATE_boolean: c_uint = 0x02;
75 #[allow(non_upper_case_globals)]
76 const DW_ATE_float: c_uint = 0x04;
77 #[allow(non_upper_case_globals)]
78 const DW_ATE_signed: c_uint = 0x05;
79 #[allow(non_upper_case_globals)]
80 const DW_ATE_unsigned: c_uint = 0x07;
81 #[allow(non_upper_case_globals)]
82 const DW_ATE_unsigned_char: c_uint = 0x08;
84 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
85 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
87 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
89 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
90 pub struct UniqueTypeId(ast::Name);
92 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
93 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
94 // faster lookup, also by Ty. The TypeMap is responsible for creating
97 pub struct TypeMap<'ll, 'tcx> {
98 // The UniqueTypeIds created so far
99 unique_id_interner: Interner,
100 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
101 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
102 // A map from types to debuginfo metadata. This is a N:1 mapping.
103 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
104 // A map from types to UniqueTypeId. This is a N:1 mapping.
105 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>
108 impl TypeMap<'ll, 'tcx> {
109 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
110 // the mapping already exists.
111 fn register_type_with_metadata(
114 metadata: &'ll DIType,
116 if self.type_to_metadata.insert(type_, metadata).is_some() {
117 bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
121 // Removes a Ty to metadata mapping
122 // This is useful when computing the metadata for a potentially
123 // recursive type (e.g. a function ptr of the form:
125 // fn foo() -> impl Copy { foo }
127 // This kind of type cannot be properly represented
128 // via LLVM debuginfo. As a workaround,
129 // we register a temporary Ty to metadata mapping
130 // for the function before we compute its actual metadata.
131 // If the metadata computation ends up recursing back to the
132 // original function, it will use the temporary mapping
133 // for the inner self-reference, preventing us from
134 // recursing forever.
136 // This function is used to remove the temporary metadata
137 // mapping after we've computed the actual metadata
142 if self.type_to_metadata.remove(type_).is_none() {
143 bug!("Type metadata Ty '{}' is not in the TypeMap!", type_);
147 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
148 // fail if the mapping already exists.
149 fn register_unique_id_with_metadata(
151 unique_type_id: UniqueTypeId,
152 metadata: &'ll DIType,
154 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
155 bug!("Type metadata for unique id '{}' is already in the TypeMap!",
156 self.get_unique_type_id_as_string(unique_type_id));
160 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
161 self.type_to_metadata.get(&type_).cloned()
164 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
165 self.unique_id_to_metadata.get(&unique_type_id).cloned()
168 // Get the string representation of a UniqueTypeId. This method will fail if
169 // the id is unknown.
170 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
171 let UniqueTypeId(interner_key) = unique_type_id;
172 self.unique_id_interner.get(interner_key)
175 // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
176 // type has been requested before, this is just a table lookup. Otherwise an
177 // ID will be generated and stored for later lookup.
178 fn get_unique_type_id_of_type<'a>(&mut self, cx: &CodegenCx<'a, 'tcx>,
179 type_: Ty<'tcx>) -> UniqueTypeId {
180 // Let's see if we already have something in the cache
181 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
182 return unique_type_id;
184 // if not, generate one
186 // The hasher we are using to generate the UniqueTypeId. We want
187 // something that provides more than the 64 bits of the DefaultHasher.
188 let mut hasher = StableHasher::<Fingerprint>::new();
189 let mut hcx = cx.tcx.create_stable_hashing_context();
190 let type_ = cx.tcx.erase_regions(&type_);
191 hcx.while_hashing_spans(false, |hcx| {
192 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
193 type_.hash_stable(hcx, &mut hasher);
196 let unique_type_id = hasher.finish().to_hex();
198 let key = self.unique_id_interner.intern(&unique_type_id);
199 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
201 return UniqueTypeId(key);
204 // Get the UniqueTypeId for an enum variant. Enum variants are not really
205 // types of their own, so they need special handling. We still need a
206 // UniqueTypeId for them, since to debuginfo they *are* real types.
207 fn get_unique_type_id_of_enum_variant<'a>(&mut self,
208 cx: &CodegenCx<'a, 'tcx>,
212 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
213 let enum_variant_type_id = format!("{}::{}",
214 self.get_unique_type_id_as_string(enum_type_id),
216 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
217 UniqueTypeId(interner_key)
220 // Get the unique type id string for an enum variant part.
221 // Variant parts are not types and shouldn't really have their own id,
222 // but it makes set_members_of_composite_type() simpler.
223 fn get_unique_type_id_str_of_enum_variant_part<'a>(&mut self,
224 enum_type_id: UniqueTypeId) -> &str {
225 let variant_part_type_id = format!("{}_variant_part",
226 self.get_unique_type_id_as_string(enum_type_id));
227 let interner_key = self.unique_id_interner.intern(&variant_part_type_id);
228 self.unique_id_interner.get(interner_key)
232 // A description of some recursive type. It can either be already finished (as
233 // with FinalMetadata) or it is not yet finished, but contains all information
234 // needed to generate the missing parts of the description. See the
235 // documentation section on Recursive Types at the top of this file for more
237 enum RecursiveTypeDescription<'ll, 'tcx> {
239 unfinished_type: Ty<'tcx>,
240 unique_type_id: UniqueTypeId,
241 metadata_stub: &'ll DICompositeType,
242 member_holding_stub: &'ll DICompositeType,
243 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
245 FinalMetadata(&'ll DICompositeType)
248 fn create_and_register_recursive_type_forward_declaration(
249 cx: &CodegenCx<'ll, 'tcx>,
250 unfinished_type: Ty<'tcx>,
251 unique_type_id: UniqueTypeId,
252 metadata_stub: &'ll DICompositeType,
253 member_holding_stub: &'ll DICompositeType,
254 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
255 ) -> RecursiveTypeDescription<'ll, 'tcx> {
257 // Insert the stub into the TypeMap in order to allow for recursive references
258 let mut type_map = debug_context(cx).type_map.borrow_mut();
259 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
260 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
267 member_description_factory,
271 impl RecursiveTypeDescription<'ll, 'tcx> {
272 // Finishes up the description of the type in question (mostly by providing
273 // descriptions of the fields of the given type) and returns the final type
275 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
277 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
283 ref member_description_factory,
285 // Make sure that we have a forward declaration of the type in
286 // the TypeMap so that recursive references are possible. This
287 // will always be the case if the RecursiveTypeDescription has
288 // been properly created through the
289 // create_and_register_recursive_type_forward_declaration()
292 let type_map = debug_context(cx).type_map.borrow();
293 if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
294 type_map.find_metadata_for_type(unfinished_type).is_none() {
295 bug!("Forward declaration of potentially recursive type \
296 '{:?}' was not found in TypeMap!",
301 // ... then create the member descriptions ...
302 let member_descriptions =
303 member_description_factory.create_member_descriptions(cx);
305 // ... and attach them to the stub to complete it.
306 set_members_of_composite_type(cx,
309 member_descriptions);
310 return MetadataCreationResult::new(metadata_stub, true);
316 // Returns from the enclosing function if the type metadata with the given
317 // unique id can be found in the type map
318 macro_rules! return_if_metadata_created_in_meantime {
319 ($cx: expr, $unique_type_id: expr) => (
320 if let Some(metadata) = debug_context($cx).type_map
322 .find_metadata_for_unique_id($unique_type_id)
324 return MetadataCreationResult::new(metadata, true);
329 fn fixed_vec_metadata(
330 cx: &CodegenCx<'ll, 'tcx>,
331 unique_type_id: UniqueTypeId,
332 array_or_slice_type: Ty<'tcx>,
333 element_type: Ty<'tcx>,
335 ) -> MetadataCreationResult<'ll> {
336 let element_type_metadata = type_metadata(cx, element_type, span);
338 return_if_metadata_created_in_meantime!(cx, unique_type_id);
340 let (size, align) = cx.size_and_align_of(array_or_slice_type);
342 let upper_bound = match array_or_slice_type.sty {
343 ty::Array(_, len) => {
344 len.unwrap_usize(cx.tcx) as c_longlong
349 let subrange = unsafe {
350 Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound))
353 let subscripts = create_DIArray(DIB(cx), &[subrange]);
354 let metadata = unsafe {
355 llvm::LLVMRustDIBuilderCreateArrayType(
359 element_type_metadata,
363 return MetadataCreationResult::new(metadata, false);
366 fn vec_slice_metadata(
367 cx: &CodegenCx<'ll, 'tcx>,
368 slice_ptr_type: Ty<'tcx>,
369 element_type: Ty<'tcx>,
370 unique_type_id: UniqueTypeId,
372 ) -> MetadataCreationResult<'ll> {
373 let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
375 let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
377 return_if_metadata_created_in_meantime!(cx, unique_type_id);
379 let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
381 let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
382 let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
384 let member_descriptions = vec![
386 name: "data_ptr".to_owned(),
387 type_metadata: data_ptr_metadata,
390 align: pointer_align,
391 flags: DIFlags::FlagZero,
395 name: "length".to_owned(),
396 type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
397 offset: pointer_size,
400 flags: DIFlags::FlagZero,
405 let file_metadata = unknown_file_metadata(cx);
407 let metadata = composite_type_metadata(cx,
409 &slice_type_name[..],
415 MetadataCreationResult::new(metadata, false)
418 fn subroutine_type_metadata(
419 cx: &CodegenCx<'ll, 'tcx>,
420 unique_type_id: UniqueTypeId,
421 signature: ty::PolyFnSig<'tcx>,
423 ) -> MetadataCreationResult<'ll> {
424 let signature = cx.tcx.normalize_erasing_late_bound_regions(
425 ty::ParamEnv::reveal_all(),
429 let signature_metadata: Vec<_> = iter::once(
431 match signature.output().sty {
432 ty::Tuple(ref tys) if tys.is_empty() => None,
433 _ => Some(type_metadata(cx, signature.output(), span))
437 signature.inputs().iter().map(|argument_type| {
438 Some(type_metadata(cx, argument_type, span))
442 return_if_metadata_created_in_meantime!(cx, unique_type_id);
444 return MetadataCreationResult::new(
446 llvm::LLVMRustDIBuilderCreateSubroutineType(
448 unknown_file_metadata(cx),
449 create_DIArray(DIB(cx), &signature_metadata[..]))
454 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
455 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
456 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
457 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
458 // of a DST struct, there is no trait_object_type and the results of this
459 // function will be a little bit weird.
460 fn trait_pointer_metadata(
461 cx: &CodegenCx<'ll, 'tcx>,
462 trait_type: Ty<'tcx>,
463 trait_object_type: Option<Ty<'tcx>>,
464 unique_type_id: UniqueTypeId,
466 // The implementation provided here is a stub. It makes sure that the trait
467 // type is assigned the correct name, size, namespace, and source location.
468 // But it does not describe the trait's methods.
470 let containing_scope = match trait_type.sty {
471 ty::Dynamic(ref data, ..) =>
472 data.principal_def_id().map(|did| get_namespace_for_item(cx, did)),
474 bug!("debuginfo: Unexpected trait-object type in \
475 trait_pointer_metadata(): {:?}",
480 let trait_object_type = trait_object_type.unwrap_or(trait_type);
481 let trait_type_name =
482 compute_debuginfo_type_name(cx.tcx, trait_object_type, false);
484 let file_metadata = unknown_file_metadata(cx);
486 let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
488 assert_eq!(abi::FAT_PTR_ADDR, 0);
489 assert_eq!(abi::FAT_PTR_EXTRA, 1);
491 let data_ptr_field = layout.field(cx, 0);
492 let vtable_field = layout.field(cx, 1);
493 let member_descriptions = vec![
495 name: "pointer".to_owned(),
496 type_metadata: type_metadata(cx,
497 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
498 syntax_pos::DUMMY_SP),
499 offset: layout.fields.offset(0),
500 size: data_ptr_field.size,
501 align: data_ptr_field.align.abi,
502 flags: DIFlags::FlagArtificial,
506 name: "vtable".to_owned(),
507 type_metadata: type_metadata(cx, vtable_field.ty, syntax_pos::DUMMY_SP),
508 offset: layout.fields.offset(1),
509 size: vtable_field.size,
510 align: vtable_field.align.abi,
511 flags: DIFlags::FlagArtificial,
516 composite_type_metadata(cx,
518 &trait_type_name[..],
523 syntax_pos::DUMMY_SP)
526 pub fn type_metadata(
527 cx: &CodegenCx<'ll, 'tcx>,
529 usage_site_span: Span,
531 // Get the unique type id of this type.
532 let unique_type_id = {
533 let mut type_map = debug_context(cx).type_map.borrow_mut();
534 // First, try to find the type in TypeMap. If we have seen it before, we
535 // can exit early here.
536 match type_map.find_metadata_for_type(t) {
541 // The Ty is not in the TypeMap but maybe we have already seen
542 // an equivalent type (e.g., only differing in region arguments).
543 // In order to find out, generate the unique type id and look
545 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
546 match type_map.find_metadata_for_unique_id(unique_type_id) {
548 // There is already an equivalent type in the TypeMap.
549 // Register this Ty as an alias in the cache and
550 // return the cached metadata.
551 type_map.register_type_with_metadata(t, metadata);
555 // There really is no type metadata for this type, so
556 // proceed by creating it.
564 debug!("type_metadata: {:?}", t);
566 let ptr_metadata = |ty: Ty<'tcx>| {
569 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
572 Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span))
575 Ok(MetadataCreationResult::new(
576 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
580 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
582 if let Some(metadata) = debug_context(cx).type_map
584 .find_metadata_for_unique_id(unique_type_id)
586 return Err(metadata);
589 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
595 let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.sty {
602 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
604 ty::Tuple(ref elements) if elements.is_empty() => {
605 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
609 fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
612 fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span)
615 MetadataCreationResult::new(
616 trait_pointer_metadata(cx, t, None, unique_type_id),
620 MetadataCreationResult::new(
621 foreign_type_metadata(cx, t, unique_type_id),
624 ty::RawPtr(ty::TypeAndMut{ty, ..}) |
625 ty::Ref(_, ty, _) => {
626 match ptr_metadata(ty) {
628 Err(metadata) => return metadata,
631 ty::Adt(def, _) if def.is_box() => {
632 match ptr_metadata(t.boxed_ty()) {
634 Err(metadata) => return metadata,
637 ty::FnDef(..) | ty::FnPtr(_) => {
639 if let Some(metadata) = debug_context(cx).type_map
641 .find_metadata_for_unique_id(unique_type_id)
646 // It's possible to create a self-referential
647 // type in Rust by using 'impl trait':
649 // fn foo() -> impl Copy { foo }
651 // See TypeMap::remove_type for more detals
652 // about the workaround
656 // The choice of type here is pretty arbitrary -
657 // anything reading the debuginfo for a recursive
658 // type is going to see *somthing* weird - the only
659 // question is what exactly it will see
660 let (size, align) = cx.size_and_align_of(t);
661 llvm::LLVMRustDIBuilderCreateBasicType(
663 SmallCStr::new("<recur_type>").as_ptr(),
670 let type_map = &debug_context(cx).type_map;
671 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
673 let fn_metadata = subroutine_type_metadata(cx,
676 usage_site_span).metadata;
678 type_map.borrow_mut().remove_type(t);
681 // This is actually a function pointer, so wrap it in pointer DI
682 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
685 ty::Closure(def_id, substs) => {
686 let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx).collect();
687 prepare_tuple_metadata(cx,
691 usage_site_span).finalize(cx)
693 ty::Generator(def_id, substs, _) => {
694 let upvar_tys : Vec<_> = substs.field_tys(def_id, cx.tcx).map(|t| {
695 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)
697 prepare_tuple_metadata(cx,
701 usage_site_span).finalize(cx)
703 ty::Adt(def, ..) => match def.adt_kind() {
705 prepare_struct_metadata(cx,
708 usage_site_span).finalize(cx)
711 prepare_union_metadata(cx,
714 usage_site_span).finalize(cx)
717 prepare_enum_metadata(cx,
721 usage_site_span).finalize(cx)
724 ty::Tuple(ref elements) => {
725 let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
726 prepare_tuple_metadata(cx,
730 usage_site_span).finalize(cx)
733 bug!("debuginfo: unexpected type in type_metadata: {:?}", t)
738 let mut type_map = debug_context(cx).type_map.borrow_mut();
740 if already_stored_in_typemap {
741 // Also make sure that we already have a TypeMap entry for the unique type id.
742 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
743 Some(metadata) => metadata,
745 span_bug!(usage_site_span,
746 "Expected type metadata for unique \
747 type id '{}' to already be in \
748 the debuginfo::TypeMap but it \
750 type_map.get_unique_type_id_as_string(unique_type_id),
755 match type_map.find_metadata_for_type(t) {
757 if metadata != metadata_for_uid {
758 span_bug!(usage_site_span,
759 "Mismatch between Ty and \
760 UniqueTypeId maps in \
761 debuginfo::TypeMap. \
762 UniqueTypeId={}, Ty={}",
763 type_map.get_unique_type_id_as_string(unique_type_id),
768 type_map.register_type_with_metadata(t, metadata);
772 type_map.register_type_with_metadata(t, metadata);
773 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
780 pub fn file_metadata(cx: &CodegenCx<'ll, '_>,
781 file_name: &FileName,
782 defining_crate: CrateNum) -> &'ll DIFile {
783 debug!("file_metadata: file_name: {}, defining_crate: {}",
787 let file_name = &file_name.to_string();
788 let file_name_symbol = Symbol::intern(file_name);
789 if defining_crate == LOCAL_CRATE {
790 let directory = &cx.sess().working_dir.0.to_string_lossy();
791 file_metadata_raw(cx, file_name, Some(file_name_symbol),
792 directory, Some(Symbol::intern(directory)))
794 // If the path comes from an upstream crate we assume it has been made
795 // independent of the compiler's working directory one way or another.
796 file_metadata_raw(cx, file_name, Some(file_name_symbol), "", None)
800 pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
801 file_metadata_raw(cx, "<unknown>", None, "", None)
804 fn file_metadata_raw(cx: &CodegenCx<'ll, '_>,
806 file_name_symbol: Option<Symbol>,
808 directory_symbol: Option<Symbol>)
810 let key = (file_name_symbol, directory_symbol);
812 if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(&key) {
813 return *file_metadata;
816 debug!("file_metadata: file_name: {}, directory: {}", file_name, directory);
818 let file_name = SmallCStr::new(file_name);
819 let directory = SmallCStr::new(directory);
821 let file_metadata = unsafe {
822 llvm::LLVMRustDIBuilderCreateFile(DIB(cx),
827 let mut created_files = debug_context(cx).created_files.borrow_mut();
828 created_files.insert(key, file_metadata);
832 fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
833 debug!("basic_type_metadata: {:?}", t);
835 let (name, encoding) = match t.sty {
836 ty::Never => ("!", DW_ATE_unsigned),
837 ty::Tuple(ref elements) if elements.is_empty() =>
838 ("()", DW_ATE_unsigned),
839 ty::Bool => ("bool", DW_ATE_boolean),
840 ty::Char => ("char", DW_ATE_unsigned_char),
842 (int_ty.ty_to_string(), DW_ATE_signed)
844 ty::Uint(uint_ty) => {
845 (uint_ty.ty_to_string(), DW_ATE_unsigned)
847 ty::Float(float_ty) => {
848 (float_ty.ty_to_string(), DW_ATE_float)
850 _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
853 let (size, align) = cx.size_and_align_of(t);
854 let name = SmallCStr::new(name);
855 let ty_metadata = unsafe {
856 llvm::LLVMRustDIBuilderCreateBasicType(
867 fn foreign_type_metadata(
868 cx: &CodegenCx<'ll, 'tcx>,
870 unique_type_id: UniqueTypeId,
872 debug!("foreign_type_metadata: {:?}", t);
874 let name = compute_debuginfo_type_name(cx.tcx, t, false);
875 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA)
878 fn pointer_type_metadata(
879 cx: &CodegenCx<'ll, 'tcx>,
880 pointer_type: Ty<'tcx>,
881 pointee_type_metadata: &'ll DIType,
883 let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
884 let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
885 let name = SmallCStr::new(&name);
887 llvm::LLVMRustDIBuilderCreatePointerType(
889 pointee_type_metadata,
891 pointer_align.bits() as u32,
896 pub fn compile_unit_metadata(tcx: TyCtxt<'_, '_, '_>,
897 codegen_unit_name: &str,
898 debug_context: &CrateDebugContext<'ll, '_>)
899 -> &'ll DIDescriptor {
900 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
901 Some(ref path) => path.clone(),
902 None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
905 // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
906 // if multiple object files with the same DW_AT_name are linked together.
907 // As a workaround we generate unique names for each object file. Those do
908 // not correspond to an actual source file but that should be harmless.
909 if tcx.sess.target.target.options.is_like_osx {
910 name_in_debuginfo.push("@");
911 name_in_debuginfo.push(codegen_unit_name);
914 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
915 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
916 let producer = format!("clang LLVM (rustc version {})",
917 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
919 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
920 let name_in_debuginfo = SmallCStr::new(&name_in_debuginfo);
921 let work_dir = SmallCStr::new(&tcx.sess.working_dir.0.to_string_lossy());
922 let producer = CString::new(producer).unwrap();
924 let split_name = "\0";
925 let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
928 let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
929 debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr());
931 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
932 debug_context.builder,
936 tcx.sess.opts.optimize != config::OptLevel::No,
937 flags.as_ptr() as *const _,
939 split_name.as_ptr() as *const _,
942 if tcx.sess.opts.debugging_opts.profile {
943 let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext,
947 path_to_mdstring(debug_context.llcontext,
948 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno")),
949 path_to_mdstring(debug_context.llcontext,
950 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda")),
953 let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext,
954 gcov_cu_info.as_ptr(),
955 gcov_cu_info.len() as c_uint);
957 let llvm_gcov_ident = const_cstr!("llvm.gcov");
958 llvm::LLVMAddNamedMetadataOperand(debug_context.llmod,
959 llvm_gcov_ident.as_ptr(),
963 return unit_metadata;
966 fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
967 let path_str = path_to_c_string(path);
969 llvm::LLVMMDStringInContext(llcx,
971 path_str.as_bytes().len() as c_uint)
976 struct MetadataCreationResult<'ll> {
977 metadata: &'ll DIType,
978 already_stored_in_typemap: bool
981 impl MetadataCreationResult<'ll> {
982 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
983 MetadataCreationResult {
985 already_stored_in_typemap,
990 // Description of a type member, which can either be a regular field (as in
991 // structs or tuples) or an enum variant.
993 struct MemberDescription<'ll> {
995 type_metadata: &'ll DIType,
1000 discriminant: Option<u64>,
1003 // A factory for MemberDescriptions. It produces a list of member descriptions
1004 // for some record-like type. MemberDescriptionFactories are used to defer the
1005 // creation of type member descriptions in order to break cycles arising from
1006 // recursive type definitions.
1007 enum MemberDescriptionFactory<'ll, 'tcx> {
1008 StructMDF(StructMemberDescriptionFactory<'tcx>),
1009 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1010 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1011 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1012 VariantMDF(VariantMemberDescriptionFactory<'ll, 'tcx>)
1015 impl MemberDescriptionFactory<'ll, 'tcx> {
1016 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1017 -> Vec<MemberDescription<'ll>> {
1019 StructMDF(ref this) => {
1020 this.create_member_descriptions(cx)
1022 TupleMDF(ref this) => {
1023 this.create_member_descriptions(cx)
1025 EnumMDF(ref this) => {
1026 this.create_member_descriptions(cx)
1028 UnionMDF(ref this) => {
1029 this.create_member_descriptions(cx)
1031 VariantMDF(ref this) => {
1032 this.create_member_descriptions(cx)
1038 //=-----------------------------------------------------------------------------
1040 //=-----------------------------------------------------------------------------
1042 // Creates MemberDescriptions for the fields of a struct
1043 struct StructMemberDescriptionFactory<'tcx> {
1045 variant: &'tcx ty::VariantDef,
1049 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1050 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1051 -> Vec<MemberDescription<'ll>> {
1052 let layout = cx.layout_of(self.ty);
1053 self.variant.fields.iter().enumerate().map(|(i, f)| {
1054 let name = if self.variant.ctor_kind == CtorKind::Fn {
1059 let field = layout.field(cx, i);
1062 type_metadata: type_metadata(cx, field.ty, self.span),
1063 offset: layout.fields.offset(i),
1065 align: field.align.abi,
1066 flags: DIFlags::FlagZero,
1074 fn prepare_struct_metadata(
1075 cx: &CodegenCx<'ll, 'tcx>,
1076 struct_type: Ty<'tcx>,
1077 unique_type_id: UniqueTypeId,
1079 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1080 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1082 let (struct_def_id, variant) = match struct_type.sty {
1083 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1084 _ => bug!("prepare_struct_metadata on a non-ADT")
1087 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1089 let struct_metadata_stub = create_struct_stub(cx,
1093 Some(containing_scope));
1095 create_and_register_recursive_type_forward_declaration(
1099 struct_metadata_stub,
1100 struct_metadata_stub,
1101 StructMDF(StructMemberDescriptionFactory {
1109 //=-----------------------------------------------------------------------------
1111 //=-----------------------------------------------------------------------------
1113 // Creates MemberDescriptions for the fields of a tuple
1114 struct TupleMemberDescriptionFactory<'tcx> {
1116 component_types: Vec<Ty<'tcx>>,
1120 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1121 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1122 -> Vec<MemberDescription<'ll>> {
1123 let layout = cx.layout_of(self.ty);
1124 self.component_types.iter().enumerate().map(|(i, &component_type)| {
1125 let (size, align) = cx.size_and_align_of(component_type);
1127 name: format!("__{}", i),
1128 type_metadata: type_metadata(cx, component_type, self.span),
1129 offset: layout.fields.offset(i),
1132 flags: DIFlags::FlagZero,
1139 fn prepare_tuple_metadata(
1140 cx: &CodegenCx<'ll, 'tcx>,
1141 tuple_type: Ty<'tcx>,
1142 component_types: &[Ty<'tcx>],
1143 unique_type_id: UniqueTypeId,
1145 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1146 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1148 let struct_stub = create_struct_stub(cx,
1154 create_and_register_recursive_type_forward_declaration(
1160 TupleMDF(TupleMemberDescriptionFactory {
1162 component_types: component_types.to_vec(),
1168 //=-----------------------------------------------------------------------------
1170 //=-----------------------------------------------------------------------------
1172 struct UnionMemberDescriptionFactory<'tcx> {
1173 layout: TyLayout<'tcx>,
1174 variant: &'tcx ty::VariantDef,
1178 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1179 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1180 -> Vec<MemberDescription<'ll>> {
1181 self.variant.fields.iter().enumerate().map(|(i, f)| {
1182 let field = self.layout.field(cx, i);
1184 name: f.ident.to_string(),
1185 type_metadata: type_metadata(cx, field.ty, self.span),
1188 align: field.align.abi,
1189 flags: DIFlags::FlagZero,
1196 fn prepare_union_metadata(
1197 cx: &CodegenCx<'ll, 'tcx>,
1198 union_type: Ty<'tcx>,
1199 unique_type_id: UniqueTypeId,
1201 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1202 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1204 let (union_def_id, variant) = match union_type.sty {
1205 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1206 _ => bug!("prepare_union_metadata on a non-ADT")
1209 let containing_scope = get_namespace_for_item(cx, union_def_id);
1211 let union_metadata_stub = create_union_stub(cx,
1217 create_and_register_recursive_type_forward_declaration(
1221 union_metadata_stub,
1222 union_metadata_stub,
1223 UnionMDF(UnionMemberDescriptionFactory {
1224 layout: cx.layout_of(union_type),
1231 //=-----------------------------------------------------------------------------
1233 //=-----------------------------------------------------------------------------
1235 // DWARF variant support is only available starting in LLVM 8.
1236 // Although the earlier enum debug info output did not work properly
1237 // in all situations, it is better for the time being to continue to
1238 // sometimes emit the old style rather than emit something completely
1239 // useless when rust is compiled against LLVM 6 or older. LLVM 7
1240 // contains an early version of the DWARF variant support, and will
1241 // crash when handling the new debug info format. This function
1242 // decides which representation will be emitted.
1243 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1244 // On MSVC we have to use the fallback mode, because LLVM doesn't
1245 // lower variant parts to PDB.
1246 return cx.sess().target.target.options.is_like_msvc
1247 // LLVM version 7 did not release with an important bug fix;
1248 // but the required patch is in the LLVM 8. Rust LLVM reports
1250 || llvm_util::get_major_version() < 8;
1253 // Describes the members of an enum value: An enum is described as a union of
1254 // structs in DWARF. This MemberDescriptionFactory provides the description for
1255 // the members of this union; so for every variant of the given enum, this
1256 // factory will produce one MemberDescription (all with no name and a fixed
1257 // offset of zero bytes).
1258 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1259 enum_type: Ty<'tcx>,
1260 layout: TyLayout<'tcx>,
1261 discriminant_type_metadata: Option<&'ll DIType>,
1262 containing_scope: &'ll DIScope,
1266 impl EnumMemberDescriptionFactory<'ll, 'tcx> {
1267 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1268 -> Vec<MemberDescription<'ll>> {
1269 let adt = &self.enum_type.ty_adt_def().unwrap();
1271 // This will always find the metadata in the type map.
1272 let fallback = use_enum_fallback(cx);
1273 let self_metadata = if fallback {
1274 self.containing_scope
1276 type_metadata(cx, self.enum_type, self.span)
1279 match self.layout.variants {
1280 layout::Variants::Single { .. } if adt.variants.is_empty() => vec![],
1281 layout::Variants::Single { index } => {
1282 let (variant_type_metadata, member_description_factory) =
1283 describe_enum_variant(cx,
1285 &adt.variants[index],
1290 let member_descriptions =
1291 member_description_factory.create_member_descriptions(cx);
1293 set_members_of_composite_type(cx,
1295 variant_type_metadata,
1296 member_descriptions);
1302 adt.variants[index].ident.as_str().to_string()
1304 type_metadata: variant_type_metadata,
1306 size: self.layout.size,
1307 align: self.layout.align.abi,
1308 flags: DIFlags::FlagZero,
1313 layout::Variants::Multiple {
1314 discr_kind: layout::DiscriminantKind::Tag,
1319 let discriminant_info = if fallback {
1320 RegularDiscriminant {
1321 discr_field: Field::from(discr_index),
1322 discr_type_metadata: self.discriminant_type_metadata.unwrap()
1325 // This doesn't matter in this case.
1328 variants.iter_enumerated().map(|(i, _)| {
1329 let variant = self.layout.for_variant(cx, i);
1330 let (variant_type_metadata, member_desc_factory) =
1331 describe_enum_variant(cx,
1338 let member_descriptions = member_desc_factory
1339 .create_member_descriptions(cx);
1341 set_members_of_composite_type(cx,
1343 variant_type_metadata,
1344 member_descriptions);
1349 adt.variants[i].ident.as_str().to_string()
1351 type_metadata: variant_type_metadata,
1353 size: self.layout.size,
1354 align: self.layout.align.abi,
1355 flags: DIFlags::FlagZero,
1356 discriminant: Some(self.layout.ty.ty_adt_def().unwrap()
1357 .discriminant_for_variant(cx.tcx, i)
1362 layout::Variants::Multiple {
1363 discr_kind: layout::DiscriminantKind::Niche {
1373 let variant = self.layout.for_variant(cx, dataful_variant);
1374 // Create a description of the non-null variant
1375 let (variant_type_metadata, member_description_factory) =
1376 describe_enum_variant(cx,
1378 &adt.variants[dataful_variant],
1379 OptimizedDiscriminant,
1380 self.containing_scope,
1383 let variant_member_descriptions =
1384 member_description_factory.create_member_descriptions(cx);
1386 set_members_of_composite_type(cx,
1388 variant_type_metadata,
1389 variant_member_descriptions);
1391 // Encode the information about the null variant in the union
1393 let mut name = String::from("RUST$ENCODED$ENUM$");
1394 // Right now it's not even going to work for `niche_start > 0`,
1395 // and for multiple niche variants it only supports the first.
1396 fn compute_field_path<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1398 layout: TyLayout<'tcx>,
1401 for i in 0..layout.fields.count() {
1402 let field_offset = layout.fields.offset(i);
1403 if field_offset > offset {
1406 let inner_offset = offset - field_offset;
1407 let field = layout.field(cx, i);
1408 if inner_offset + size <= field.size {
1409 write!(name, "{}$", i).unwrap();
1410 compute_field_path(cx, name, field, inner_offset, size);
1414 compute_field_path(cx, &mut name,
1416 self.layout.fields.offset(discr_index),
1417 self.layout.field(cx, discr_index).size);
1418 name.push_str(&adt.variants[*niche_variants.start()].ident.as_str());
1420 // Create the (singleton) list of descriptions of union members.
1424 type_metadata: variant_type_metadata,
1427 align: variant.align.abi,
1428 flags: DIFlags::FlagZero,
1433 variants.iter_enumerated().map(|(i, _)| {
1434 let variant = self.layout.for_variant(cx, i);
1435 let (variant_type_metadata, member_desc_factory) =
1436 describe_enum_variant(cx,
1439 OptimizedDiscriminant,
1443 let member_descriptions = member_desc_factory
1444 .create_member_descriptions(cx);
1446 set_members_of_composite_type(cx,
1448 variant_type_metadata,
1449 member_descriptions);
1451 let niche_value = if i == dataful_variant {
1454 let value = (i.as_u32() as u128)
1455 .wrapping_sub(niche_variants.start().as_u32() as u128)
1456 .wrapping_add(niche_start);
1457 let value = truncate(value, discr.value.size(cx));
1458 // NOTE(eddyb) do *NOT* remove this assert, until
1459 // we pass the full 128-bit value to LLVM, otherwise
1460 // truncation will be silent and remain undetected.
1461 assert_eq!(value as u64 as u128, value);
1466 name: adt.variants[i].ident.as_str().to_string(),
1467 type_metadata: variant_type_metadata,
1469 size: self.layout.size,
1470 align: self.layout.align.abi,
1471 flags: DIFlags::FlagZero,
1472 discriminant: niche_value,
1481 // Creates MemberDescriptions for the fields of a single enum variant.
1482 struct VariantMemberDescriptionFactory<'ll, 'tcx> {
1483 // Cloned from the layout::Struct describing the variant.
1484 offsets: Vec<layout::Size>,
1485 args: Vec<(String, Ty<'tcx>)>,
1486 discriminant_type_metadata: Option<&'ll DIType>,
1490 impl VariantMemberDescriptionFactory<'ll, 'tcx> {
1491 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1492 -> Vec<MemberDescription<'ll>> {
1493 self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1494 let (size, align) = cx.size_and_align_of(ty);
1496 name: name.to_string(),
1497 type_metadata: if use_enum_fallback(cx) {
1498 match self.discriminant_type_metadata {
1499 // Discriminant is always the first field of our variant
1500 // when using the enum fallback.
1501 Some(metadata) if i == 0 => metadata,
1502 _ => type_metadata(cx, ty, self.span)
1505 type_metadata(cx, ty, self.span)
1507 offset: self.offsets[i],
1510 flags: DIFlags::FlagZero,
1517 #[derive(Copy, Clone)]
1518 enum EnumDiscriminantInfo<'ll> {
1519 RegularDiscriminant{ discr_field: Field, discr_type_metadata: &'ll DIType },
1520 OptimizedDiscriminant,
1524 // Returns a tuple of (1) type_metadata_stub of the variant, (2) a
1525 // MemberDescriptionFactory for producing the descriptions of the
1526 // fields of the variant. This is a rudimentary version of a full
1527 // RecursiveTypeDescription.
1528 fn describe_enum_variant(
1529 cx: &CodegenCx<'ll, 'tcx>,
1530 layout: layout::TyLayout<'tcx>,
1531 variant: &'tcx ty::VariantDef,
1532 discriminant_info: EnumDiscriminantInfo<'ll>,
1533 containing_scope: &'ll DIScope,
1535 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1536 let variant_name = variant.ident.as_str();
1537 let unique_type_id = debug_context(cx).type_map
1539 .get_unique_type_id_of_enum_variant(
1544 let metadata_stub = create_struct_stub(cx,
1548 Some(containing_scope));
1550 let arg_name = |i: usize| {
1551 if variant.ctor_kind == CtorKind::Fn {
1554 variant.fields[i].ident.to_string()
1558 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1559 let (offsets, args) = if use_enum_fallback(cx) {
1560 // If this is not a univariant enum, there is also the discriminant field.
1561 let (discr_offset, discr_arg) = match discriminant_info {
1562 RegularDiscriminant { discr_field, .. } => {
1563 // We have the layout of an enum variant, we need the layout of the outer enum
1564 let enum_layout = cx.layout_of(layout.ty);
1565 let offset = enum_layout.fields.offset(discr_field.as_usize());
1567 "RUST$ENUM$DISR".to_owned(),
1568 enum_layout.field(cx, discr_field.as_usize()).ty);
1569 (Some(offset), Some(args))
1574 discr_offset.into_iter().chain((0..layout.fields.count()).map(|i| {
1575 layout.fields.offset(i)
1577 discr_arg.into_iter().chain((0..layout.fields.count()).map(|i| {
1578 (arg_name(i), layout.field(cx, i).ty)
1583 (0..layout.fields.count()).map(|i| {
1584 layout.fields.offset(i)
1586 (0..layout.fields.count()).map(|i| {
1587 (arg_name(i), layout.field(cx, i).ty)
1592 let member_description_factory =
1593 VariantMDF(VariantMemberDescriptionFactory {
1596 discriminant_type_metadata: match discriminant_info {
1597 RegularDiscriminant { discr_type_metadata, .. } => {
1598 Some(discr_type_metadata)
1605 (metadata_stub, member_description_factory)
1608 fn prepare_enum_metadata(
1609 cx: &CodegenCx<'ll, 'tcx>,
1610 enum_type: Ty<'tcx>,
1612 unique_type_id: UniqueTypeId,
1614 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1615 let enum_name = compute_debuginfo_type_name(cx.tcx, enum_type, false);
1617 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1618 // FIXME: This should emit actual file metadata for the enum, but we
1619 // currently can't get the necessary information when it comes to types
1620 // imported from other crates. Formerly we violated the ODR when performing
1621 // LTO because we emitted debuginfo for the same type with varying file
1622 // metadata, so as a workaround we pretend that the type comes from
1624 let file_metadata = unknown_file_metadata(cx);
1626 let discriminant_type_metadata = |discr: layout::Primitive| {
1627 let def = enum_type.ty_adt_def().unwrap();
1628 let enumerators_metadata: Vec<_> = def.discriminants(cx.tcx)
1630 .map(|((_, discr), v)| {
1631 let name = SmallCStr::new(&v.ident.as_str());
1633 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1636 // FIXME: what if enumeration has i128 discriminant?
1642 let disr_type_key = (enum_def_id, discr);
1643 let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1645 .get(&disr_type_key).cloned();
1646 match cached_discriminant_type_metadata {
1647 Some(discriminant_type_metadata) => discriminant_type_metadata,
1649 let (discriminant_size, discriminant_align) =
1650 (discr.size(cx), discr.align(cx));
1651 let discriminant_base_type_metadata =
1652 type_metadata(cx, discr.to_ty(cx.tcx), syntax_pos::DUMMY_SP);
1653 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id).as_str();
1655 let name = SmallCStr::new(&discriminant_name);
1656 let discriminant_type_metadata = unsafe {
1657 llvm::LLVMRustDIBuilderCreateEnumerationType(
1662 UNKNOWN_LINE_NUMBER,
1663 discriminant_size.bits(),
1664 discriminant_align.abi.bits() as u32,
1665 create_DIArray(DIB(cx), &enumerators_metadata),
1666 discriminant_base_type_metadata, true)
1669 debug_context(cx).created_enum_disr_types
1671 .insert(disr_type_key, discriminant_type_metadata);
1673 discriminant_type_metadata
1678 let layout = cx.layout_of(enum_type);
1680 match (&layout.abi, &layout.variants) {
1681 (&layout::Abi::Scalar(_), &layout::Variants::Multiple {
1682 discr_kind: layout::DiscriminantKind::Tag,
1685 }) => return FinalMetadata(discriminant_type_metadata(discr.value)),
1689 let enum_name = SmallCStr::new(&enum_name);
1690 let unique_type_id_str = SmallCStr::new(
1691 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
1694 if use_enum_fallback(cx) {
1695 let discriminant_type_metadata = match layout.variants {
1696 layout::Variants::Single { .. } |
1697 layout::Variants::Multiple {
1698 discr_kind: layout::DiscriminantKind::Niche { .. },
1701 layout::Variants::Multiple {
1702 discr_kind: layout::DiscriminantKind::Tag,
1706 Some(discriminant_type_metadata(discr.value))
1710 let enum_metadata = unsafe {
1711 llvm::LLVMRustDIBuilderCreateUnionType(
1716 UNKNOWN_LINE_NUMBER,
1718 layout.align.abi.bits() as u32,
1722 unique_type_id_str.as_ptr())
1725 return create_and_register_recursive_type_forward_declaration(
1731 EnumMDF(EnumMemberDescriptionFactory {
1734 discriminant_type_metadata,
1741 let discriminator_metadata = match layout.variants {
1742 // A single-variant enum has no discriminant.
1743 layout::Variants::Single { .. } => None,
1745 layout::Variants::Multiple {
1746 discr_kind: layout::DiscriminantKind::Niche { .. },
1751 // Find the integer type of the correct size.
1752 let size = discr.value.size(cx);
1753 let align = discr.value.align(cx);
1755 let discr_type = match discr.value {
1756 layout::Int(t, _) => t,
1757 layout::Float(layout::FloatTy::F32) => Integer::I32,
1758 layout::Float(layout::FloatTy::F64) => Integer::I64,
1759 layout::Pointer => cx.data_layout().ptr_sized_integer(),
1760 }.to_ty(cx.tcx, false);
1762 let discr_metadata = basic_type_metadata(cx, discr_type);
1764 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1769 UNKNOWN_LINE_NUMBER,
1771 align.abi.bits() as u32,
1772 layout.fields.offset(discr_index).bits(),
1773 DIFlags::FlagArtificial,
1778 layout::Variants::Multiple {
1779 discr_kind: layout::DiscriminantKind::Tag,
1784 let discr_type = discr.value.to_ty(cx.tcx);
1785 let (size, align) = cx.size_and_align_of(discr_type);
1787 let discr_metadata = basic_type_metadata(cx, discr_type);
1789 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1794 UNKNOWN_LINE_NUMBER,
1796 align.bits() as u32,
1797 layout.fields.offset(discr_index).bits(),
1798 DIFlags::FlagArtificial,
1804 let variant_part_unique_type_id_str = SmallCStr::new(
1805 debug_context(cx).type_map
1807 .get_unique_type_id_str_of_enum_variant_part(unique_type_id)
1809 let empty_array = create_DIArray(DIB(cx), &[]);
1810 let variant_part = unsafe {
1811 llvm::LLVMRustDIBuilderCreateVariantPart(
1816 UNKNOWN_LINE_NUMBER,
1818 layout.align.abi.bits() as u32,
1820 discriminator_metadata,
1822 variant_part_unique_type_id_str.as_ptr())
1825 // The variant part must be wrapped in a struct according to DWARF.
1826 let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
1827 let struct_wrapper = unsafe {
1828 llvm::LLVMRustDIBuilderCreateStructType(
1830 Some(containing_scope),
1833 UNKNOWN_LINE_NUMBER,
1835 layout.align.abi.bits() as u32,
1841 unique_type_id_str.as_ptr())
1844 return create_and_register_recursive_type_forward_declaration(
1850 EnumMDF(EnumMemberDescriptionFactory {
1853 discriminant_type_metadata: None,
1859 fn get_enum_discriminant_name(cx: &CodegenCx<'_, '_>,
1862 cx.tcx.item_name(def_id)
1866 /// Creates debug information for a composite type, that is, anything that
1867 /// results in a LLVM struct.
1869 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1870 fn composite_type_metadata(
1871 cx: &CodegenCx<'ll, 'tcx>,
1872 composite_type: Ty<'tcx>,
1873 composite_type_name: &str,
1874 composite_type_unique_id: UniqueTypeId,
1875 member_descriptions: Vec<MemberDescription<'ll>>,
1876 containing_scope: Option<&'ll DIScope>,
1878 // Ignore source location information as long as it
1879 // can't be reconstructed for non-local crates.
1880 _file_metadata: &'ll DIFile,
1881 _definition_span: Span,
1882 ) -> &'ll DICompositeType {
1883 // Create the (empty) struct metadata node ...
1884 let composite_type_metadata = create_struct_stub(cx,
1886 composite_type_name,
1887 composite_type_unique_id,
1889 // ... and immediately create and add the member descriptions.
1890 set_members_of_composite_type(cx,
1892 composite_type_metadata,
1893 member_descriptions);
1895 composite_type_metadata
1898 fn set_members_of_composite_type(cx: &CodegenCx<'ll, 'tcx>,
1899 composite_type: Ty<'tcx>,
1900 composite_type_metadata: &'ll DICompositeType,
1901 member_descriptions: Vec<MemberDescription<'ll>>) {
1902 // In some rare cases LLVM metadata uniquing would lead to an existing type
1903 // description being used instead of a new one created in
1904 // create_struct_stub. This would cause a hard to trace assertion in
1905 // DICompositeType::SetTypeArray(). The following check makes sure that we
1906 // get a better error message if this should happen again due to some
1909 let mut composite_types_completed =
1910 debug_context(cx).composite_types_completed.borrow_mut();
1911 if composite_types_completed.contains(&composite_type_metadata) {
1912 bug!("debuginfo::set_members_of_composite_type() - \
1913 Already completed forward declaration re-encountered.");
1915 composite_types_completed.insert(composite_type_metadata);
1919 let member_metadata: Vec<_> = member_descriptions
1921 .map(|member_description| {
1922 let member_name = CString::new(member_description.name).unwrap();
1924 Some(llvm::LLVMRustDIBuilderCreateVariantMemberType(
1926 composite_type_metadata,
1927 member_name.as_ptr(),
1928 unknown_file_metadata(cx),
1929 UNKNOWN_LINE_NUMBER,
1930 member_description.size.bits(),
1931 member_description.align.bits() as u32,
1932 member_description.offset.bits(),
1933 match member_description.discriminant {
1935 Some(value) => Some(cx.const_u64(value)),
1937 member_description.flags,
1938 member_description.type_metadata))
1943 let type_params = compute_type_parameters(cx, composite_type);
1945 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1946 llvm::LLVMRustDICompositeTypeReplaceArrays(
1947 DIB(cx), composite_type_metadata, Some(type_array), type_params);
1951 // Compute the type parameters for a type, if any, for the given
1953 fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> Option<&'ll DIArray> {
1954 if let ty::Adt(def, substs) = ty.sty {
1955 if !substs.types().next().is_none() {
1956 let generics = cx.tcx.generics_of(def.did);
1957 let names = get_parameter_names(cx, generics);
1958 let template_params: Vec<_> = substs.iter().zip(names).filter_map(|(kind, name)| {
1959 if let UnpackedKind::Type(ty) = kind.unpack() {
1960 let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
1961 let actual_type_metadata =
1962 type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
1963 let name = SmallCStr::new(&name.as_str());
1966 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
1970 actual_type_metadata,
1971 unknown_file_metadata(cx),
1981 return Some(create_DIArray(DIB(cx), &template_params[..]));
1984 return Some(create_DIArray(DIB(cx), &[]));
1986 fn get_parameter_names(cx: &CodegenCx<'_, '_>,
1987 generics: &ty::Generics)
1988 -> Vec<InternedString> {
1989 let mut names = generics.parent.map_or(vec![], |def_id| {
1990 get_parameter_names(cx, cx.tcx.generics_of(def_id))
1992 names.extend(generics.params.iter().map(|param| param.name));
1997 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1998 // any caching, does not add any fields to the struct. This can be done later
1999 // with set_members_of_composite_type().
2000 fn create_struct_stub(
2001 cx: &CodegenCx<'ll, 'tcx>,
2002 struct_type: Ty<'tcx>,
2003 struct_type_name: &str,
2004 unique_type_id: UniqueTypeId,
2005 containing_scope: Option<&'ll DIScope>,
2006 ) -> &'ll DICompositeType {
2007 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2009 let name = SmallCStr::new(struct_type_name);
2010 let unique_type_id = SmallCStr::new(
2011 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
2013 let metadata_stub = unsafe {
2014 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
2015 // pointer will lead to hard to trace and debug LLVM assertions
2016 // later on in llvm/lib/IR/Value.cpp.
2017 let empty_array = create_DIArray(DIB(cx), &[]);
2019 llvm::LLVMRustDIBuilderCreateStructType(
2023 unknown_file_metadata(cx),
2024 UNKNOWN_LINE_NUMBER,
2026 struct_align.bits() as u32,
2032 unique_type_id.as_ptr())
2038 fn create_union_stub(
2039 cx: &CodegenCx<'ll, 'tcx>,
2040 union_type: Ty<'tcx>,
2041 union_type_name: &str,
2042 unique_type_id: UniqueTypeId,
2043 containing_scope: &'ll DIScope,
2044 ) -> &'ll DICompositeType {
2045 let (union_size, union_align) = cx.size_and_align_of(union_type);
2047 let name = SmallCStr::new(union_type_name);
2048 let unique_type_id = SmallCStr::new(
2049 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
2051 let metadata_stub = unsafe {
2052 // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
2053 // pointer will lead to hard to trace and debug LLVM assertions
2054 // later on in llvm/lib/IR/Value.cpp.
2055 let empty_array = create_DIArray(DIB(cx), &[]);
2057 llvm::LLVMRustDIBuilderCreateUnionType(
2061 unknown_file_metadata(cx),
2062 UNKNOWN_LINE_NUMBER,
2064 union_align.bits() as u32,
2068 unique_type_id.as_ptr())
2074 /// Creates debug information for the given global variable.
2076 /// Adds the created metadata nodes directly to the crate's IR.
2077 pub fn create_global_var_metadata(
2078 cx: &CodegenCx<'ll, '_>,
2082 if cx.dbg_cx.is_none() {
2087 let attrs = tcx.codegen_fn_attrs(def_id);
2089 if attrs.flags.contains(CodegenFnAttrFlags::NO_DEBUG) {
2093 let no_mangle = attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE);
2094 // We may want to remove the namespace scope if we're in an extern block, see:
2095 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952
2096 let var_scope = get_namespace_for_item(cx, def_id);
2097 let span = tcx.def_span(def_id);
2099 let (file_metadata, line_number) = if !span.is_dummy() {
2100 let loc = span_start(cx, span);
2101 (file_metadata(cx, &loc.file.name, LOCAL_CRATE), loc.line as c_uint)
2103 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2106 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2107 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx);
2108 let type_metadata = type_metadata(cx, variable_type, span);
2109 let var_name = SmallCStr::new(&tcx.item_name(def_id).as_str());
2110 let linkage_name = if no_mangle {
2113 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id));
2114 Some(SmallCStr::new(&linkage_name.as_str()))
2117 let global_align = cx.align_of(variable_type);
2120 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
2123 // If null, linkage_name field is omitted,
2124 // which is what we want for no_mangle statics
2125 linkage_name.as_ref()
2126 .map_or(ptr::null(), |name| name.as_ptr()),
2133 global_align.bytes() as u32,
2138 /// Creates debug information for the given vtable, which is for the
2141 /// Adds the created metadata nodes directly to the crate's IR.
2142 pub fn create_vtable_metadata(
2143 cx: &CodegenCx<'ll, 'tcx>,
2147 if cx.dbg_cx.is_none() {
2151 let type_metadata = type_metadata(cx, ty, syntax_pos::DUMMY_SP);
2154 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
2155 // pointer will lead to hard to trace and debug LLVM assertions
2156 // later on in llvm/lib/IR/Value.cpp.
2157 let empty_array = create_DIArray(DIB(cx), &[]);
2159 let name = const_cstr!("vtable");
2161 // Create a new one each time. We don't want metadata caching
2162 // here, because each vtable will refer to a unique containing
2164 let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
2168 unknown_file_metadata(cx),
2169 UNKNOWN_LINE_NUMBER,
2171 cx.tcx.data_layout.pointer_align.abi.bits() as u32,
2172 DIFlags::FlagArtificial,
2176 Some(type_metadata),
2180 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
2184 unknown_file_metadata(cx),
2185 UNKNOWN_LINE_NUMBER,
2194 // Creates an "extension" of an existing DIScope into another file.
2195 pub fn extend_scope_to_file(
2196 cx: &CodegenCx<'ll, '_>,
2197 scope_metadata: &'ll DIScope,
2198 file: &syntax_pos::SourceFile,
2199 defining_crate: CrateNum,
2200 ) -> &'ll DILexicalBlock {
2201 let file_metadata = file_metadata(cx, &file.name, defining_crate);
2203 llvm::LLVMRustDIBuilderCreateLexicalBlockFile(