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::GeneratorLayout;
27 use rustc::mir::interpret::truncate;
28 use rustc_data_structures::fingerprint::Fingerprint;
29 use rustc::ty::Instance;
30 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
31 use rustc::ty::layout::{self, Align, Integer, IntegerExt, LayoutOf,
32 PrimitiveExt, Size, TyLayout, VariantIdx};
33 use rustc::ty::subst::UnpackedKind;
34 use rustc::session::config;
35 use rustc::util::nodemap::FxHashMap;
36 use rustc_fs_util::path_to_c_string;
37 use rustc_data_structures::small_c_str::SmallCStr;
38 use rustc_target::abi::HasDataLayout;
40 use libc::{c_uint, c_longlong};
41 use std::ffi::CString;
42 use std::fmt::{self, Write};
43 use std::hash::{Hash, Hasher};
46 use std::path::{Path, PathBuf};
48 use syntax::symbol::{Interner, InternedString, Symbol};
49 use syntax_pos::{self, Span, FileName};
51 impl PartialEq for llvm::Metadata {
52 fn eq(&self, other: &Self) -> bool {
57 impl Eq for llvm::Metadata {}
59 impl Hash for llvm::Metadata {
60 fn hash<H: Hasher>(&self, hasher: &mut H) {
61 (self as *const Self).hash(hasher);
65 impl fmt::Debug for llvm::Metadata {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 (self as *const Self).fmt(f)
72 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
73 const DW_LANG_RUST: c_uint = 0x1c;
74 #[allow(non_upper_case_globals)]
75 const DW_ATE_boolean: c_uint = 0x02;
76 #[allow(non_upper_case_globals)]
77 const DW_ATE_float: c_uint = 0x04;
78 #[allow(non_upper_case_globals)]
79 const DW_ATE_signed: c_uint = 0x05;
80 #[allow(non_upper_case_globals)]
81 const DW_ATE_unsigned: c_uint = 0x07;
82 #[allow(non_upper_case_globals)]
83 const DW_ATE_unsigned_char: c_uint = 0x08;
85 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
86 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
88 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
90 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
91 pub struct UniqueTypeId(ast::Name);
93 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
94 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
95 // faster lookup, also by Ty. The TypeMap is responsible for creating
98 pub struct TypeMap<'ll, 'tcx> {
99 // The UniqueTypeIds created so far
100 unique_id_interner: Interner,
101 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
102 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
103 // A map from types to debuginfo metadata. This is a N:1 mapping.
104 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
105 // A map from types to UniqueTypeId. This is a N:1 mapping.
106 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>
109 impl TypeMap<'ll, 'tcx> {
110 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
111 // the mapping already exists.
112 fn register_type_with_metadata(
115 metadata: &'ll DIType,
117 if self.type_to_metadata.insert(type_, metadata).is_some() {
118 bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
122 // Removes a Ty to metadata mapping
123 // This is useful when computing the metadata for a potentially
124 // recursive type (e.g. a function ptr of the form:
126 // fn foo() -> impl Copy { foo }
128 // This kind of type cannot be properly represented
129 // via LLVM debuginfo. As a workaround,
130 // we register a temporary Ty to metadata mapping
131 // for the function before we compute its actual metadata.
132 // If the metadata computation ends up recursing back to the
133 // original function, it will use the temporary mapping
134 // for the inner self-reference, preventing us from
135 // recursing forever.
137 // This function is used to remove the temporary metadata
138 // mapping after we've computed the actual metadata
143 if self.type_to_metadata.remove(type_).is_none() {
144 bug!("Type metadata Ty '{}' is not in the TypeMap!", type_);
148 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
149 // fail if the mapping already exists.
150 fn register_unique_id_with_metadata(
152 unique_type_id: UniqueTypeId,
153 metadata: &'ll DIType,
155 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
156 bug!("Type metadata for unique id '{}' is already in the TypeMap!",
157 self.get_unique_type_id_as_string(unique_type_id));
161 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
162 self.type_to_metadata.get(&type_).cloned()
165 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
166 self.unique_id_to_metadata.get(&unique_type_id).cloned()
169 // Get the string representation of a UniqueTypeId. This method will fail if
170 // the id is unknown.
171 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
172 let UniqueTypeId(interner_key) = unique_type_id;
173 self.unique_id_interner.get(interner_key)
176 // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
177 // type has been requested before, this is just a table lookup. Otherwise an
178 // ID will be generated and stored for later lookup.
179 fn get_unique_type_id_of_type<'a>(&mut self, cx: &CodegenCx<'a, 'tcx>,
180 type_: Ty<'tcx>) -> UniqueTypeId {
181 // Let's see if we already have something in the cache
182 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
183 return unique_type_id;
185 // if not, generate one
187 // The hasher we are using to generate the UniqueTypeId. We want
188 // something that provides more than the 64 bits of the DefaultHasher.
189 let mut hasher = StableHasher::<Fingerprint>::new();
190 let mut hcx = cx.tcx.create_stable_hashing_context();
191 let type_ = cx.tcx.erase_regions(&type_);
192 hcx.while_hashing_spans(false, |hcx| {
193 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
194 type_.hash_stable(hcx, &mut hasher);
197 let unique_type_id = hasher.finish().to_hex();
199 let key = self.unique_id_interner.intern(&unique_type_id);
200 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
202 return UniqueTypeId(key);
205 // Get the UniqueTypeId for an enum variant. Enum variants are not really
206 // types of their own, so they need special handling. We still need a
207 // UniqueTypeId for them, since to debuginfo they *are* real types.
208 fn get_unique_type_id_of_enum_variant<'a>(&mut self,
209 cx: &CodegenCx<'a, 'tcx>,
213 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
214 let enum_variant_type_id = format!("{}::{}",
215 self.get_unique_type_id_as_string(enum_type_id),
217 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
218 UniqueTypeId(interner_key)
221 // Get the unique type id string for an enum variant part.
222 // Variant parts are not types and shouldn't really have their own id,
223 // but it makes set_members_of_composite_type() simpler.
224 fn get_unique_type_id_str_of_enum_variant_part<'a>(&mut self,
225 enum_type_id: UniqueTypeId) -> &str {
226 let variant_part_type_id = format!("{}_variant_part",
227 self.get_unique_type_id_as_string(enum_type_id));
228 let interner_key = self.unique_id_interner.intern(&variant_part_type_id);
229 self.unique_id_interner.get(interner_key)
233 // A description of some recursive type. It can either be already finished (as
234 // with FinalMetadata) or it is not yet finished, but contains all information
235 // needed to generate the missing parts of the description. See the
236 // documentation section on Recursive Types at the top of this file for more
238 enum RecursiveTypeDescription<'ll, 'tcx> {
240 unfinished_type: Ty<'tcx>,
241 unique_type_id: UniqueTypeId,
242 metadata_stub: &'ll DICompositeType,
243 member_holding_stub: &'ll DICompositeType,
244 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
246 FinalMetadata(&'ll DICompositeType)
249 fn create_and_register_recursive_type_forward_declaration(
250 cx: &CodegenCx<'ll, 'tcx>,
251 unfinished_type: Ty<'tcx>,
252 unique_type_id: UniqueTypeId,
253 metadata_stub: &'ll DICompositeType,
254 member_holding_stub: &'ll DICompositeType,
255 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
256 ) -> RecursiveTypeDescription<'ll, 'tcx> {
258 // Insert the stub into the TypeMap in order to allow for recursive references
259 let mut type_map = debug_context(cx).type_map.borrow_mut();
260 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
261 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
268 member_description_factory,
272 impl RecursiveTypeDescription<'ll, 'tcx> {
273 // Finishes up the description of the type in question (mostly by providing
274 // descriptions of the fields of the given type) and returns the final type
276 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
278 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
284 ref member_description_factory,
286 // Make sure that we have a forward declaration of the type in
287 // the TypeMap so that recursive references are possible. This
288 // will always be the case if the RecursiveTypeDescription has
289 // been properly created through the
290 // create_and_register_recursive_type_forward_declaration()
293 let type_map = debug_context(cx).type_map.borrow();
294 if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
295 type_map.find_metadata_for_type(unfinished_type).is_none() {
296 bug!("Forward declaration of potentially recursive type \
297 '{:?}' was not found in TypeMap!",
302 // ... then create the member descriptions ...
303 let member_descriptions =
304 member_description_factory.create_member_descriptions(cx);
306 // ... and attach them to the stub to complete it.
307 set_members_of_composite_type(cx,
310 member_descriptions);
311 return MetadataCreationResult::new(metadata_stub, true);
317 // Returns from the enclosing function if the type metadata with the given
318 // unique id can be found in the type map
319 macro_rules! return_if_metadata_created_in_meantime {
320 ($cx: expr, $unique_type_id: expr) => (
321 if let Some(metadata) = debug_context($cx).type_map
323 .find_metadata_for_unique_id($unique_type_id)
325 return MetadataCreationResult::new(metadata, true);
330 fn fixed_vec_metadata(
331 cx: &CodegenCx<'ll, 'tcx>,
332 unique_type_id: UniqueTypeId,
333 array_or_slice_type: Ty<'tcx>,
334 element_type: Ty<'tcx>,
336 ) -> MetadataCreationResult<'ll> {
337 let element_type_metadata = type_metadata(cx, element_type, span);
339 return_if_metadata_created_in_meantime!(cx, unique_type_id);
341 let (size, align) = cx.size_and_align_of(array_or_slice_type);
343 let upper_bound = match array_or_slice_type.sty {
344 ty::Array(_, len) => {
345 len.unwrap_usize(cx.tcx) as c_longlong
350 let subrange = unsafe {
351 Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound))
354 let subscripts = create_DIArray(DIB(cx), &[subrange]);
355 let metadata = unsafe {
356 llvm::LLVMRustDIBuilderCreateArrayType(
360 element_type_metadata,
364 return MetadataCreationResult::new(metadata, false);
367 fn vec_slice_metadata(
368 cx: &CodegenCx<'ll, 'tcx>,
369 slice_ptr_type: Ty<'tcx>,
370 element_type: Ty<'tcx>,
371 unique_type_id: UniqueTypeId,
373 ) -> MetadataCreationResult<'ll> {
374 let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
376 let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
378 return_if_metadata_created_in_meantime!(cx, unique_type_id);
380 let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
382 let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
383 let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
385 let member_descriptions = vec![
387 name: "data_ptr".to_owned(),
388 type_metadata: data_ptr_metadata,
391 align: pointer_align,
392 flags: DIFlags::FlagZero,
396 name: "length".to_owned(),
397 type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
398 offset: pointer_size,
401 flags: DIFlags::FlagZero,
406 let file_metadata = unknown_file_metadata(cx);
408 let metadata = composite_type_metadata(cx,
410 &slice_type_name[..],
416 MetadataCreationResult::new(metadata, false)
419 fn subroutine_type_metadata(
420 cx: &CodegenCx<'ll, 'tcx>,
421 unique_type_id: UniqueTypeId,
422 signature: ty::PolyFnSig<'tcx>,
424 ) -> MetadataCreationResult<'ll> {
425 let signature = cx.tcx.normalize_erasing_late_bound_regions(
426 ty::ParamEnv::reveal_all(),
430 let signature_metadata: Vec<_> = iter::once(
432 match signature.output().sty {
433 ty::Tuple(ref tys) if tys.is_empty() => None,
434 _ => Some(type_metadata(cx, signature.output(), span))
438 signature.inputs().iter().map(|argument_type| {
439 Some(type_metadata(cx, argument_type, span))
443 return_if_metadata_created_in_meantime!(cx, unique_type_id);
445 return MetadataCreationResult::new(
447 llvm::LLVMRustDIBuilderCreateSubroutineType(
449 unknown_file_metadata(cx),
450 create_DIArray(DIB(cx), &signature_metadata[..]))
455 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
456 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
457 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
458 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
459 // of a DST struct, there is no trait_object_type and the results of this
460 // function will be a little bit weird.
461 fn trait_pointer_metadata(
462 cx: &CodegenCx<'ll, 'tcx>,
463 trait_type: Ty<'tcx>,
464 trait_object_type: Option<Ty<'tcx>>,
465 unique_type_id: UniqueTypeId,
467 // The implementation provided here is a stub. It makes sure that the trait
468 // type is assigned the correct name, size, namespace, and source location.
469 // But it does not describe the trait's methods.
471 let containing_scope = match trait_type.sty {
472 ty::Dynamic(ref data, ..) =>
473 data.principal_def_id().map(|did| get_namespace_for_item(cx, did)),
475 bug!("debuginfo: Unexpected trait-object type in \
476 trait_pointer_metadata(): {:?}",
481 let trait_object_type = trait_object_type.unwrap_or(trait_type);
482 let trait_type_name =
483 compute_debuginfo_type_name(cx.tcx, trait_object_type, false);
485 let file_metadata = unknown_file_metadata(cx);
487 let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
489 assert_eq!(abi::FAT_PTR_ADDR, 0);
490 assert_eq!(abi::FAT_PTR_EXTRA, 1);
492 let data_ptr_field = layout.field(cx, 0);
493 let vtable_field = layout.field(cx, 1);
494 let member_descriptions = vec![
496 name: "pointer".to_owned(),
497 type_metadata: type_metadata(cx,
498 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
499 syntax_pos::DUMMY_SP),
500 offset: layout.fields.offset(0),
501 size: data_ptr_field.size,
502 align: data_ptr_field.align.abi,
503 flags: DIFlags::FlagArtificial,
507 name: "vtable".to_owned(),
508 type_metadata: type_metadata(cx, vtable_field.ty, syntax_pos::DUMMY_SP),
509 offset: layout.fields.offset(1),
510 size: vtable_field.size,
511 align: vtable_field.align.abi,
512 flags: DIFlags::FlagArtificial,
517 composite_type_metadata(cx,
519 &trait_type_name[..],
524 syntax_pos::DUMMY_SP)
527 pub fn type_metadata(
528 cx: &CodegenCx<'ll, 'tcx>,
530 usage_site_span: Span,
532 // Get the unique type id of this type.
533 let unique_type_id = {
534 let mut type_map = debug_context(cx).type_map.borrow_mut();
535 // First, try to find the type in TypeMap. If we have seen it before, we
536 // can exit early here.
537 match type_map.find_metadata_for_type(t) {
542 // The Ty is not in the TypeMap but maybe we have already seen
543 // an equivalent type (e.g., only differing in region arguments).
544 // In order to find out, generate the unique type id and look
546 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
547 match type_map.find_metadata_for_unique_id(unique_type_id) {
549 // There is already an equivalent type in the TypeMap.
550 // Register this Ty as an alias in the cache and
551 // return the cached metadata.
552 type_map.register_type_with_metadata(t, metadata);
556 // There really is no type metadata for this type, so
557 // proceed by creating it.
565 debug!("type_metadata: {:?}", t);
567 let ptr_metadata = |ty: Ty<'tcx>| {
570 Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
573 Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span))
576 Ok(MetadataCreationResult::new(
577 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
581 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
583 if let Some(metadata) = debug_context(cx).type_map
585 .find_metadata_for_unique_id(unique_type_id)
587 return Err(metadata);
590 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
596 let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.sty {
603 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
605 ty::Tuple(ref elements) if elements.is_empty() => {
606 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
610 fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
613 fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span)
616 MetadataCreationResult::new(
617 trait_pointer_metadata(cx, t, None, unique_type_id),
621 MetadataCreationResult::new(
622 foreign_type_metadata(cx, t, unique_type_id),
625 ty::RawPtr(ty::TypeAndMut{ty, ..}) |
626 ty::Ref(_, ty, _) => {
627 match ptr_metadata(ty) {
629 Err(metadata) => return metadata,
632 ty::Adt(def, _) if def.is_box() => {
633 match ptr_metadata(t.boxed_ty()) {
635 Err(metadata) => return metadata,
638 ty::FnDef(..) | ty::FnPtr(_) => {
640 if let Some(metadata) = debug_context(cx).type_map
642 .find_metadata_for_unique_id(unique_type_id)
647 // It's possible to create a self-referential
648 // type in Rust by using 'impl trait':
650 // fn foo() -> impl Copy { foo }
652 // See TypeMap::remove_type for more detals
653 // about the workaround
657 // The choice of type here is pretty arbitrary -
658 // anything reading the debuginfo for a recursive
659 // type is going to see *somthing* weird - the only
660 // question is what exactly it will see
661 let (size, align) = cx.size_and_align_of(t);
662 llvm::LLVMRustDIBuilderCreateBasicType(
664 SmallCStr::new("<recur_type>").as_ptr(),
671 let type_map = &debug_context(cx).type_map;
672 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
674 let fn_metadata = subroutine_type_metadata(cx,
677 usage_site_span).metadata;
679 type_map.borrow_mut().remove_type(t);
682 // This is actually a function pointer, so wrap it in pointer DI
683 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
686 ty::Closure(def_id, substs) => {
687 let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx).collect();
688 prepare_tuple_metadata(cx,
692 usage_site_span).finalize(cx)
694 ty::Generator(def_id, substs, _) => {
695 let upvar_tys : Vec<_> = substs.prefix_tys(def_id, cx.tcx).map(|t| {
696 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)
698 prepare_enum_metadata(cx,
703 upvar_tys).finalize(cx)
705 ty::Adt(def, ..) => match def.adt_kind() {
707 prepare_struct_metadata(cx,
710 usage_site_span).finalize(cx)
713 prepare_union_metadata(cx,
716 usage_site_span).finalize(cx)
719 prepare_enum_metadata(cx,
727 ty::Tuple(ref elements) => {
728 let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
729 prepare_tuple_metadata(cx,
733 usage_site_span).finalize(cx)
736 bug!("debuginfo: unexpected type in type_metadata: {:?}", t)
741 let mut type_map = debug_context(cx).type_map.borrow_mut();
743 if already_stored_in_typemap {
744 // Also make sure that we already have a TypeMap entry for the unique type id.
745 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
746 Some(metadata) => metadata,
748 span_bug!(usage_site_span,
749 "Expected type metadata for unique \
750 type id '{}' to already be in \
751 the debuginfo::TypeMap but it \
753 type_map.get_unique_type_id_as_string(unique_type_id),
758 match type_map.find_metadata_for_type(t) {
760 if metadata != metadata_for_uid {
761 span_bug!(usage_site_span,
762 "Mismatch between Ty and \
763 UniqueTypeId maps in \
764 debuginfo::TypeMap. \
765 UniqueTypeId={}, Ty={}",
766 type_map.get_unique_type_id_as_string(unique_type_id),
771 type_map.register_type_with_metadata(t, metadata);
775 type_map.register_type_with_metadata(t, metadata);
776 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
783 pub fn file_metadata(cx: &CodegenCx<'ll, '_>,
784 file_name: &FileName,
785 defining_crate: CrateNum) -> &'ll DIFile {
786 debug!("file_metadata: file_name: {}, defining_crate: {}",
790 let file_name = &file_name.to_string();
791 let file_name_symbol = Symbol::intern(file_name);
792 if defining_crate == LOCAL_CRATE {
793 let directory = &cx.sess().working_dir.0.to_string_lossy();
794 file_metadata_raw(cx, file_name, Some(file_name_symbol),
795 directory, Some(Symbol::intern(directory)))
797 // If the path comes from an upstream crate we assume it has been made
798 // independent of the compiler's working directory one way or another.
799 file_metadata_raw(cx, file_name, Some(file_name_symbol), "", None)
803 pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
804 file_metadata_raw(cx, "<unknown>", None, "", None)
807 fn file_metadata_raw(cx: &CodegenCx<'ll, '_>,
809 file_name_symbol: Option<Symbol>,
811 directory_symbol: Option<Symbol>)
813 let key = (file_name_symbol, directory_symbol);
815 if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(&key) {
816 return *file_metadata;
819 debug!("file_metadata: file_name: {}, directory: {}", file_name, directory);
821 let file_name = SmallCStr::new(file_name);
822 let directory = SmallCStr::new(directory);
824 let file_metadata = unsafe {
825 llvm::LLVMRustDIBuilderCreateFile(DIB(cx),
830 let mut created_files = debug_context(cx).created_files.borrow_mut();
831 created_files.insert(key, file_metadata);
835 fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
836 debug!("basic_type_metadata: {:?}", t);
838 let (name, encoding) = match t.sty {
839 ty::Never => ("!", DW_ATE_unsigned),
840 ty::Tuple(ref elements) if elements.is_empty() =>
841 ("()", DW_ATE_unsigned),
842 ty::Bool => ("bool", DW_ATE_boolean),
843 ty::Char => ("char", DW_ATE_unsigned_char),
845 (int_ty.ty_to_string(), DW_ATE_signed)
847 ty::Uint(uint_ty) => {
848 (uint_ty.ty_to_string(), DW_ATE_unsigned)
850 ty::Float(float_ty) => {
851 (float_ty.ty_to_string(), DW_ATE_float)
853 _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
856 let (size, align) = cx.size_and_align_of(t);
857 let name = SmallCStr::new(name);
858 let ty_metadata = unsafe {
859 llvm::LLVMRustDIBuilderCreateBasicType(
870 fn foreign_type_metadata(
871 cx: &CodegenCx<'ll, 'tcx>,
873 unique_type_id: UniqueTypeId,
875 debug!("foreign_type_metadata: {:?}", t);
877 let name = compute_debuginfo_type_name(cx.tcx, t, false);
878 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA)
881 fn pointer_type_metadata(
882 cx: &CodegenCx<'ll, 'tcx>,
883 pointer_type: Ty<'tcx>,
884 pointee_type_metadata: &'ll DIType,
886 let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
887 let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
888 let name = SmallCStr::new(&name);
890 llvm::LLVMRustDIBuilderCreatePointerType(
892 pointee_type_metadata,
894 pointer_align.bits() as u32,
899 pub fn compile_unit_metadata(tcx: TyCtxt<'_, '_, '_>,
900 codegen_unit_name: &str,
901 debug_context: &CrateDebugContext<'ll, '_>)
902 -> &'ll DIDescriptor {
903 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
904 Some(ref path) => path.clone(),
905 None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
908 // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
909 // if multiple object files with the same DW_AT_name are linked together.
910 // As a workaround we generate unique names for each object file. Those do
911 // not correspond to an actual source file but that should be harmless.
912 if tcx.sess.target.target.options.is_like_osx {
913 name_in_debuginfo.push("@");
914 name_in_debuginfo.push(codegen_unit_name);
917 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
918 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
919 let producer = format!("clang LLVM (rustc version {})",
920 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
922 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
923 let name_in_debuginfo = SmallCStr::new(&name_in_debuginfo);
924 let work_dir = SmallCStr::new(&tcx.sess.working_dir.0.to_string_lossy());
925 let producer = CString::new(producer).unwrap();
927 let split_name = "\0";
928 let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
931 let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
932 debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr());
934 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
935 debug_context.builder,
939 tcx.sess.opts.optimize != config::OptLevel::No,
940 flags.as_ptr() as *const _,
942 split_name.as_ptr() as *const _,
945 if tcx.sess.opts.debugging_opts.profile {
946 let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext,
950 path_to_mdstring(debug_context.llcontext,
951 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno")),
952 path_to_mdstring(debug_context.llcontext,
953 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda")),
956 let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext,
957 gcov_cu_info.as_ptr(),
958 gcov_cu_info.len() as c_uint);
960 let llvm_gcov_ident = const_cstr!("llvm.gcov");
961 llvm::LLVMAddNamedMetadataOperand(debug_context.llmod,
962 llvm_gcov_ident.as_ptr(),
966 return unit_metadata;
969 fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
970 let path_str = path_to_c_string(path);
972 llvm::LLVMMDStringInContext(llcx,
974 path_str.as_bytes().len() as c_uint)
979 struct MetadataCreationResult<'ll> {
980 metadata: &'ll DIType,
981 already_stored_in_typemap: bool
984 impl MetadataCreationResult<'ll> {
985 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
986 MetadataCreationResult {
988 already_stored_in_typemap,
993 // Description of a type member, which can either be a regular field (as in
994 // structs or tuples) or an enum variant.
996 struct MemberDescription<'ll> {
998 type_metadata: &'ll DIType,
1003 discriminant: Option<u64>,
1006 impl<'ll> MemberDescription<'ll> {
1007 fn into_metadata(self,
1008 cx: &CodegenCx<'ll, '_>,
1009 composite_type_metadata: &'ll DIScope) -> &'ll DIType {
1010 let member_name = CString::new(self.name).unwrap();
1012 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1014 composite_type_metadata,
1015 member_name.as_ptr(),
1016 unknown_file_metadata(cx),
1017 UNKNOWN_LINE_NUMBER,
1019 self.align.bits() as u32,
1021 match self.discriminant {
1023 Some(value) => Some(cx.const_u64(value)),
1031 // A factory for MemberDescriptions. It produces a list of member descriptions
1032 // for some record-like type. MemberDescriptionFactories are used to defer the
1033 // creation of type member descriptions in order to break cycles arising from
1034 // recursive type definitions.
1035 enum MemberDescriptionFactory<'ll, 'tcx> {
1036 StructMDF(StructMemberDescriptionFactory<'tcx>),
1037 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1038 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1039 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1040 VariantMDF(VariantMemberDescriptionFactory<'ll, 'tcx>)
1043 impl MemberDescriptionFactory<'ll, 'tcx> {
1044 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1045 -> Vec<MemberDescription<'ll>> {
1047 StructMDF(ref this) => {
1048 this.create_member_descriptions(cx)
1050 TupleMDF(ref this) => {
1051 this.create_member_descriptions(cx)
1053 EnumMDF(ref this) => {
1054 this.create_member_descriptions(cx)
1056 UnionMDF(ref this) => {
1057 this.create_member_descriptions(cx)
1059 VariantMDF(ref this) => {
1060 this.create_member_descriptions(cx)
1066 //=-----------------------------------------------------------------------------
1068 //=-----------------------------------------------------------------------------
1070 // Creates MemberDescriptions for the fields of a struct
1071 struct StructMemberDescriptionFactory<'tcx> {
1073 variant: &'tcx ty::VariantDef,
1077 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1078 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1079 -> Vec<MemberDescription<'ll>> {
1080 let layout = cx.layout_of(self.ty);
1081 self.variant.fields.iter().enumerate().map(|(i, f)| {
1082 let name = if self.variant.ctor_kind == CtorKind::Fn {
1087 let field = layout.field(cx, i);
1090 type_metadata: type_metadata(cx, field.ty, self.span),
1091 offset: layout.fields.offset(i),
1093 align: field.align.abi,
1094 flags: DIFlags::FlagZero,
1102 fn prepare_struct_metadata(
1103 cx: &CodegenCx<'ll, 'tcx>,
1104 struct_type: Ty<'tcx>,
1105 unique_type_id: UniqueTypeId,
1107 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1108 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1110 let (struct_def_id, variant) = match struct_type.sty {
1111 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1112 _ => bug!("prepare_struct_metadata on a non-ADT")
1115 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1117 let struct_metadata_stub = create_struct_stub(cx,
1121 Some(containing_scope));
1123 create_and_register_recursive_type_forward_declaration(
1127 struct_metadata_stub,
1128 struct_metadata_stub,
1129 StructMDF(StructMemberDescriptionFactory {
1137 //=-----------------------------------------------------------------------------
1139 //=-----------------------------------------------------------------------------
1141 // Creates MemberDescriptions for the fields of a tuple
1142 struct TupleMemberDescriptionFactory<'tcx> {
1144 component_types: Vec<Ty<'tcx>>,
1148 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1149 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1150 -> Vec<MemberDescription<'ll>> {
1151 let layout = cx.layout_of(self.ty);
1152 self.component_types.iter().enumerate().map(|(i, &component_type)| {
1153 let (size, align) = cx.size_and_align_of(component_type);
1155 name: format!("__{}", i),
1156 type_metadata: type_metadata(cx, component_type, self.span),
1157 offset: layout.fields.offset(i),
1160 flags: DIFlags::FlagZero,
1167 fn prepare_tuple_metadata(
1168 cx: &CodegenCx<'ll, 'tcx>,
1169 tuple_type: Ty<'tcx>,
1170 component_types: &[Ty<'tcx>],
1171 unique_type_id: UniqueTypeId,
1173 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1174 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1176 let struct_stub = create_struct_stub(cx,
1182 create_and_register_recursive_type_forward_declaration(
1188 TupleMDF(TupleMemberDescriptionFactory {
1190 component_types: component_types.to_vec(),
1196 //=-----------------------------------------------------------------------------
1198 //=-----------------------------------------------------------------------------
1200 struct UnionMemberDescriptionFactory<'tcx> {
1201 layout: TyLayout<'tcx>,
1202 variant: &'tcx ty::VariantDef,
1206 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1207 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1208 -> Vec<MemberDescription<'ll>> {
1209 self.variant.fields.iter().enumerate().map(|(i, f)| {
1210 let field = self.layout.field(cx, i);
1212 name: f.ident.to_string(),
1213 type_metadata: type_metadata(cx, field.ty, self.span),
1216 align: field.align.abi,
1217 flags: DIFlags::FlagZero,
1224 fn prepare_union_metadata(
1225 cx: &CodegenCx<'ll, 'tcx>,
1226 union_type: Ty<'tcx>,
1227 unique_type_id: UniqueTypeId,
1229 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1230 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1232 let (union_def_id, variant) = match union_type.sty {
1233 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1234 _ => bug!("prepare_union_metadata on a non-ADT")
1237 let containing_scope = get_namespace_for_item(cx, union_def_id);
1239 let union_metadata_stub = create_union_stub(cx,
1245 create_and_register_recursive_type_forward_declaration(
1249 union_metadata_stub,
1250 union_metadata_stub,
1251 UnionMDF(UnionMemberDescriptionFactory {
1252 layout: cx.layout_of(union_type),
1259 //=-----------------------------------------------------------------------------
1261 //=-----------------------------------------------------------------------------
1263 // DWARF variant support is only available starting in LLVM 8.
1264 // Although the earlier enum debug info output did not work properly
1265 // in all situations, it is better for the time being to continue to
1266 // sometimes emit the old style rather than emit something completely
1267 // useless when rust is compiled against LLVM 6 or older. LLVM 7
1268 // contains an early version of the DWARF variant support, and will
1269 // crash when handling the new debug info format. This function
1270 // decides which representation will be emitted.
1271 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1272 // On MSVC we have to use the fallback mode, because LLVM doesn't
1273 // lower variant parts to PDB.
1274 return cx.sess().target.target.options.is_like_msvc
1275 // LLVM version 7 did not release with an important bug fix;
1276 // but the required patch is in the LLVM 8. Rust LLVM reports
1278 || llvm_util::get_major_version() < 8;
1281 // Describes the members of an enum value: An enum is described as a union of
1282 // structs in DWARF. This MemberDescriptionFactory provides the description for
1283 // the members of this union; so for every variant of the given enum, this
1284 // factory will produce one MemberDescription (all with no name and a fixed
1285 // offset of zero bytes).
1286 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1287 enum_type: Ty<'tcx>,
1288 layout: TyLayout<'tcx>,
1289 discriminant_type_metadata: Option<&'ll DIType>,
1290 containing_scope: &'ll DIScope,
1294 impl EnumMemberDescriptionFactory<'ll, 'tcx> {
1295 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1296 -> Vec<MemberDescription<'ll>> {
1297 let variant_info_for = |index: VariantIdx| {
1298 match &self.enum_type.sty {
1299 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1300 ty::Generator(def_id, substs, _) => {
1301 let generator_layout = cx.tcx.generator_layout(*def_id);
1302 VariantInfo::Generator(*substs, generator_layout, index)
1308 // This will always find the metadata in the type map.
1309 let fallback = use_enum_fallback(cx);
1310 let self_metadata = if fallback {
1311 self.containing_scope
1313 type_metadata(cx, self.enum_type, self.span)
1316 match self.layout.variants {
1317 layout::Variants::Single { index } => {
1318 if let ty::Adt(adt, _) = &self.enum_type.sty {
1319 if adt.variants.is_empty() {
1324 let variant_info = variant_info_for(index);
1325 let (variant_type_metadata, member_description_factory) =
1326 describe_enum_variant(cx,
1333 let member_descriptions =
1334 member_description_factory.create_member_descriptions(cx);
1336 set_members_of_composite_type(cx,
1338 variant_type_metadata,
1339 member_descriptions);
1345 variant_info.variant_name()
1347 type_metadata: variant_type_metadata,
1349 size: self.layout.size,
1350 align: self.layout.align.abi,
1351 flags: DIFlags::FlagZero,
1356 layout::Variants::Multiple {
1357 discr_kind: layout::DiscriminantKind::Tag,
1362 let discriminant_info = if fallback {
1363 RegularDiscriminant {
1364 discr_field: Field::from(discr_index),
1365 discr_type_metadata: self.discriminant_type_metadata.unwrap()
1368 // This doesn't matter in this case.
1371 variants.iter_enumerated().map(|(i, _)| {
1372 let variant = self.layout.for_variant(cx, i);
1373 let variant_info = variant_info_for(i);
1374 let (variant_type_metadata, member_desc_factory) =
1375 describe_enum_variant(cx,
1382 let member_descriptions = member_desc_factory
1383 .create_member_descriptions(cx);
1385 set_members_of_composite_type(cx,
1387 variant_type_metadata,
1388 member_descriptions);
1394 variant_info.variant_name()
1396 type_metadata: variant_type_metadata,
1398 size: self.layout.size,
1399 align: self.layout.align.abi,
1400 flags: DIFlags::FlagZero,
1402 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val as u64
1407 layout::Variants::Multiple {
1408 discr_kind: layout::DiscriminantKind::Niche {
1418 let variant = self.layout.for_variant(cx, dataful_variant);
1419 // Create a description of the non-null variant
1420 let (variant_type_metadata, member_description_factory) =
1421 describe_enum_variant(cx,
1423 variant_info_for(dataful_variant),
1424 OptimizedDiscriminant,
1425 self.containing_scope,
1428 let variant_member_descriptions =
1429 member_description_factory.create_member_descriptions(cx);
1431 set_members_of_composite_type(cx,
1433 variant_type_metadata,
1434 variant_member_descriptions);
1436 // Encode the information about the null variant in the union
1438 let mut name = String::from("RUST$ENCODED$ENUM$");
1439 // Right now it's not even going to work for `niche_start > 0`,
1440 // and for multiple niche variants it only supports the first.
1441 fn compute_field_path<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
1443 layout: TyLayout<'tcx>,
1446 for i in 0..layout.fields.count() {
1447 let field_offset = layout.fields.offset(i);
1448 if field_offset > offset {
1451 let inner_offset = offset - field_offset;
1452 let field = layout.field(cx, i);
1453 if inner_offset + size <= field.size {
1454 write!(name, "{}$", i).unwrap();
1455 compute_field_path(cx, name, field, inner_offset, size);
1459 compute_field_path(cx, &mut name,
1461 self.layout.fields.offset(discr_index),
1462 self.layout.field(cx, discr_index).size);
1463 variant_info_for(*niche_variants.start()).map_struct_name(|variant_name| {
1464 name.push_str(variant_name);
1467 // Create the (singleton) list of descriptions of union members.
1471 type_metadata: variant_type_metadata,
1474 align: variant.align.abi,
1475 flags: DIFlags::FlagZero,
1480 variants.iter_enumerated().map(|(i, _)| {
1481 let variant = self.layout.for_variant(cx, i);
1482 let variant_info = variant_info_for(i);
1483 let (variant_type_metadata, member_desc_factory) =
1484 describe_enum_variant(cx,
1487 OptimizedDiscriminant,
1491 let member_descriptions = member_desc_factory
1492 .create_member_descriptions(cx);
1494 set_members_of_composite_type(cx,
1496 variant_type_metadata,
1497 member_descriptions);
1499 let niche_value = if i == dataful_variant {
1502 let value = (i.as_u32() as u128)
1503 .wrapping_sub(niche_variants.start().as_u32() as u128)
1504 .wrapping_add(niche_start);
1505 let value = truncate(value, discr.value.size(cx));
1506 // NOTE(eddyb) do *NOT* remove this assert, until
1507 // we pass the full 128-bit value to LLVM, otherwise
1508 // truncation will be silent and remain undetected.
1509 assert_eq!(value as u64 as u128, value);
1514 name: variant_info.variant_name(),
1515 type_metadata: variant_type_metadata,
1517 size: self.layout.size,
1518 align: self.layout.align.abi,
1519 flags: DIFlags::FlagZero,
1520 discriminant: niche_value,
1529 // Creates MemberDescriptions for the fields of a single enum variant.
1530 struct VariantMemberDescriptionFactory<'ll, 'tcx> {
1531 // Cloned from the layout::Struct describing the variant.
1532 offsets: Vec<layout::Size>,
1533 args: Vec<(String, Ty<'tcx>)>,
1534 discriminant_type_metadata: Option<&'ll DIType>,
1538 impl VariantMemberDescriptionFactory<'ll, 'tcx> {
1539 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>)
1540 -> Vec<MemberDescription<'ll>> {
1541 self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1542 let (size, align) = cx.size_and_align_of(ty);
1544 name: name.to_string(),
1545 type_metadata: if use_enum_fallback(cx) {
1546 match self.discriminant_type_metadata {
1547 // Discriminant is always the first field of our variant
1548 // when using the enum fallback.
1549 Some(metadata) if i == 0 => metadata,
1550 _ => type_metadata(cx, ty, self.span)
1553 type_metadata(cx, ty, self.span)
1555 offset: self.offsets[i],
1558 flags: DIFlags::FlagZero,
1565 #[derive(Copy, Clone)]
1566 enum EnumDiscriminantInfo<'ll> {
1567 RegularDiscriminant{ discr_field: Field, discr_type_metadata: &'ll DIType },
1568 OptimizedDiscriminant,
1572 #[derive(Copy, Clone)]
1573 enum VariantInfo<'tcx> {
1574 Adt(&'tcx ty::VariantDef),
1575 Generator(ty::GeneratorSubsts<'tcx>, &'tcx GeneratorLayout<'tcx>, VariantIdx),
1578 impl<'tcx> VariantInfo<'tcx> {
1579 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1581 VariantInfo::Adt(variant) => f(&variant.ident.as_str()),
1582 VariantInfo::Generator(substs, _, variant_index) =>
1583 f(&substs.variant_name(*variant_index)),
1587 fn variant_name(&self) -> String {
1589 VariantInfo::Adt(variant) => variant.ident.to_string(),
1590 VariantInfo::Generator(_, _, variant_index) => {
1591 // Since GDB currently prints out the raw discriminant along
1592 // with every variant, make each variant name be just the value
1593 // of the discriminant. The struct name for the variant includes
1594 // the actual variant description.
1595 format!("{}", variant_index.as_usize()).to_string()
1600 fn field_name(&self, i: usize) -> String {
1601 let field_name = match self {
1602 VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn =>
1603 Some(variant.fields[i].ident.to_string()),
1604 VariantInfo::Generator(_, generator_layout, variant_index) => {
1605 let field = generator_layout.variant_fields[*variant_index][i.into()];
1606 let decl = &generator_layout.__local_debuginfo_codegen_only_do_not_use[field];
1607 decl.name.map(|name| name.to_string())
1611 field_name.unwrap_or_else(|| format!("__{}", i))
1615 // Returns a tuple of (1) type_metadata_stub of the variant, (2) a
1616 // MemberDescriptionFactory for producing the descriptions of the
1617 // fields of the variant. This is a rudimentary version of a full
1618 // RecursiveTypeDescription.
1619 fn describe_enum_variant(
1620 cx: &CodegenCx<'ll, 'tcx>,
1621 layout: layout::TyLayout<'tcx>,
1622 variant: VariantInfo<'tcx>,
1623 discriminant_info: EnumDiscriminantInfo<'ll>,
1624 containing_scope: &'ll DIScope,
1626 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1627 let metadata_stub = variant.map_struct_name(|variant_name| {
1628 let unique_type_id = debug_context(cx).type_map
1630 .get_unique_type_id_of_enum_variant(
1634 create_struct_stub(cx,
1638 Some(containing_scope))
1641 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1642 let (offsets, args) = if use_enum_fallback(cx) {
1643 // If this is not a univariant enum, there is also the discriminant field.
1644 let (discr_offset, discr_arg) = match discriminant_info {
1645 RegularDiscriminant { discr_field, .. } => {
1646 // We have the layout of an enum variant, we need the layout of the outer enum
1647 let enum_layout = cx.layout_of(layout.ty);
1648 let offset = enum_layout.fields.offset(discr_field.as_usize());
1650 "RUST$ENUM$DISR".to_owned(),
1651 enum_layout.field(cx, discr_field.as_usize()).ty);
1652 (Some(offset), Some(args))
1657 discr_offset.into_iter().chain((0..layout.fields.count()).map(|i| {
1658 layout.fields.offset(i)
1660 discr_arg.into_iter().chain((0..layout.fields.count()).map(|i| {
1661 (variant.field_name(i), layout.field(cx, i).ty)
1666 (0..layout.fields.count()).map(|i| {
1667 layout.fields.offset(i)
1669 (0..layout.fields.count()).map(|i| {
1670 (variant.field_name(i), layout.field(cx, i).ty)
1675 let member_description_factory =
1676 VariantMDF(VariantMemberDescriptionFactory {
1679 discriminant_type_metadata: match discriminant_info {
1680 RegularDiscriminant { discr_type_metadata, .. } => {
1681 Some(discr_type_metadata)
1688 (metadata_stub, member_description_factory)
1691 fn prepare_enum_metadata(
1692 cx: &CodegenCx<'ll, 'tcx>,
1693 enum_type: Ty<'tcx>,
1695 unique_type_id: UniqueTypeId,
1697 outer_field_tys: Vec<Ty<'tcx>>,
1698 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1699 let enum_name = compute_debuginfo_type_name(cx.tcx, enum_type, false);
1701 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1702 // FIXME: This should emit actual file metadata for the enum, but we
1703 // currently can't get the necessary information when it comes to types
1704 // imported from other crates. Formerly we violated the ODR when performing
1705 // LTO because we emitted debuginfo for the same type with varying file
1706 // metadata, so as a workaround we pretend that the type comes from
1708 let file_metadata = unknown_file_metadata(cx);
1710 let discriminant_type_metadata = |discr: layout::Primitive| {
1711 let enumerators_metadata: Vec<_> = match enum_type.sty {
1712 ty::Adt(def, _) => def
1713 .discriminants(cx.tcx)
1715 .map(|((_, discr), v)| {
1716 let name = SmallCStr::new(&v.ident.as_str());
1718 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1721 // FIXME: what if enumeration has i128 discriminant?
1726 ty::Generator(_, substs, _) => substs
1727 .variant_range(enum_def_id, cx.tcx)
1728 .map(|variant_index| {
1729 let name = SmallCStr::new(&substs.variant_name(variant_index));
1731 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1734 // FIXME: what if enumeration has i128 discriminant?
1735 variant_index.as_usize() as u64))
1742 let disr_type_key = (enum_def_id, discr);
1743 let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1745 .get(&disr_type_key).cloned();
1746 match cached_discriminant_type_metadata {
1747 Some(discriminant_type_metadata) => discriminant_type_metadata,
1749 let (discriminant_size, discriminant_align) =
1750 (discr.size(cx), discr.align(cx));
1751 let discriminant_base_type_metadata =
1752 type_metadata(cx, discr.to_ty(cx.tcx), syntax_pos::DUMMY_SP);
1754 let discriminant_name = match enum_type.sty {
1755 ty::Adt(..) => SmallCStr::new(&cx.tcx.item_name(enum_def_id).as_str()),
1756 ty::Generator(..) => SmallCStr::new(&enum_name),
1760 let discriminant_type_metadata = unsafe {
1761 llvm::LLVMRustDIBuilderCreateEnumerationType(
1764 discriminant_name.as_ptr(),
1766 UNKNOWN_LINE_NUMBER,
1767 discriminant_size.bits(),
1768 discriminant_align.abi.bits() as u32,
1769 create_DIArray(DIB(cx), &enumerators_metadata),
1770 discriminant_base_type_metadata, true)
1773 debug_context(cx).created_enum_disr_types
1775 .insert(disr_type_key, discriminant_type_metadata);
1777 discriminant_type_metadata
1782 let layout = cx.layout_of(enum_type);
1784 match (&layout.abi, &layout.variants) {
1785 (&layout::Abi::Scalar(_), &layout::Variants::Multiple {
1786 discr_kind: layout::DiscriminantKind::Tag,
1789 }) => return FinalMetadata(discriminant_type_metadata(discr.value)),
1793 let enum_name = SmallCStr::new(&enum_name);
1794 let unique_type_id_str = SmallCStr::new(
1795 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
1798 if use_enum_fallback(cx) {
1799 let discriminant_type_metadata = match layout.variants {
1800 layout::Variants::Single { .. } |
1801 layout::Variants::Multiple {
1802 discr_kind: layout::DiscriminantKind::Niche { .. },
1805 layout::Variants::Multiple {
1806 discr_kind: layout::DiscriminantKind::Tag,
1810 Some(discriminant_type_metadata(discr.value))
1814 let enum_metadata = unsafe {
1815 llvm::LLVMRustDIBuilderCreateUnionType(
1820 UNKNOWN_LINE_NUMBER,
1822 layout.align.abi.bits() as u32,
1826 unique_type_id_str.as_ptr())
1829 return create_and_register_recursive_type_forward_declaration(
1835 EnumMDF(EnumMemberDescriptionFactory {
1838 discriminant_type_metadata,
1845 let discriminator_name = match &enum_type.sty {
1846 ty::Generator(..) => Some(SmallCStr::new(&"__state")),
1849 let discriminator_name = discriminator_name.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut());
1850 let discriminator_metadata = match layout.variants {
1851 // A single-variant enum has no discriminant.
1852 layout::Variants::Single { .. } => None,
1854 layout::Variants::Multiple {
1855 discr_kind: layout::DiscriminantKind::Niche { .. },
1860 // Find the integer type of the correct size.
1861 let size = discr.value.size(cx);
1862 let align = discr.value.align(cx);
1864 let discr_type = match discr.value {
1865 layout::Int(t, _) => t,
1866 layout::Float(layout::FloatTy::F32) => Integer::I32,
1867 layout::Float(layout::FloatTy::F64) => Integer::I64,
1868 layout::Pointer => cx.data_layout().ptr_sized_integer(),
1869 }.to_ty(cx.tcx, false);
1871 let discr_metadata = basic_type_metadata(cx, discr_type);
1873 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1878 UNKNOWN_LINE_NUMBER,
1880 align.abi.bits() as u32,
1881 layout.fields.offset(discr_index).bits(),
1882 DIFlags::FlagArtificial,
1887 layout::Variants::Multiple {
1888 discr_kind: layout::DiscriminantKind::Tag,
1893 let discr_type = discr.value.to_ty(cx.tcx);
1894 let (size, align) = cx.size_and_align_of(discr_type);
1896 let discr_metadata = basic_type_metadata(cx, discr_type);
1898 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1903 UNKNOWN_LINE_NUMBER,
1905 align.bits() as u32,
1906 layout.fields.offset(discr_index).bits(),
1907 DIFlags::FlagArtificial,
1913 let mut outer_fields = match layout.variants {
1914 layout::Variants::Single { .. } => vec![],
1915 layout::Variants::Multiple { .. } => {
1916 let tuple_mdf = TupleMemberDescriptionFactory {
1918 component_types: outer_field_tys,
1922 .create_member_descriptions(cx)
1924 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
1929 let variant_part_unique_type_id_str = SmallCStr::new(
1930 debug_context(cx).type_map
1932 .get_unique_type_id_str_of_enum_variant_part(unique_type_id)
1934 let empty_array = create_DIArray(DIB(cx), &[]);
1935 let variant_part = unsafe {
1936 llvm::LLVMRustDIBuilderCreateVariantPart(
1941 UNKNOWN_LINE_NUMBER,
1943 layout.align.abi.bits() as u32,
1945 discriminator_metadata,
1947 variant_part_unique_type_id_str.as_ptr())
1949 outer_fields.push(Some(variant_part));
1951 // The variant part must be wrapped in a struct according to DWARF.
1952 let type_array = create_DIArray(DIB(cx), &outer_fields);
1953 let struct_wrapper = unsafe {
1954 llvm::LLVMRustDIBuilderCreateStructType(
1956 Some(containing_scope),
1959 UNKNOWN_LINE_NUMBER,
1961 layout.align.abi.bits() as u32,
1967 unique_type_id_str.as_ptr())
1970 return create_and_register_recursive_type_forward_declaration(
1976 EnumMDF(EnumMemberDescriptionFactory {
1979 discriminant_type_metadata: None,
1986 /// Creates debug information for a composite type, that is, anything that
1987 /// results in a LLVM struct.
1989 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1990 fn composite_type_metadata(
1991 cx: &CodegenCx<'ll, 'tcx>,
1992 composite_type: Ty<'tcx>,
1993 composite_type_name: &str,
1994 composite_type_unique_id: UniqueTypeId,
1995 member_descriptions: Vec<MemberDescription<'ll>>,
1996 containing_scope: Option<&'ll DIScope>,
1998 // Ignore source location information as long as it
1999 // can't be reconstructed for non-local crates.
2000 _file_metadata: &'ll DIFile,
2001 _definition_span: Span,
2002 ) -> &'ll DICompositeType {
2003 // Create the (empty) struct metadata node ...
2004 let composite_type_metadata = create_struct_stub(cx,
2006 composite_type_name,
2007 composite_type_unique_id,
2009 // ... and immediately create and add the member descriptions.
2010 set_members_of_composite_type(cx,
2012 composite_type_metadata,
2013 member_descriptions);
2015 composite_type_metadata
2018 fn set_members_of_composite_type(cx: &CodegenCx<'ll, 'tcx>,
2019 composite_type: Ty<'tcx>,
2020 composite_type_metadata: &'ll DICompositeType,
2021 member_descriptions: Vec<MemberDescription<'ll>>) {
2022 // In some rare cases LLVM metadata uniquing would lead to an existing type
2023 // description being used instead of a new one created in
2024 // create_struct_stub. This would cause a hard to trace assertion in
2025 // DICompositeType::SetTypeArray(). The following check makes sure that we
2026 // get a better error message if this should happen again due to some
2029 let mut composite_types_completed =
2030 debug_context(cx).composite_types_completed.borrow_mut();
2031 if composite_types_completed.contains(&composite_type_metadata) {
2032 bug!("debuginfo::set_members_of_composite_type() - \
2033 Already completed forward declaration re-encountered.");
2035 composite_types_completed.insert(composite_type_metadata);
2039 let member_metadata: Vec<_> = member_descriptions
2041 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2044 let type_params = compute_type_parameters(cx, composite_type);
2046 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
2047 llvm::LLVMRustDICompositeTypeReplaceArrays(
2048 DIB(cx), composite_type_metadata, Some(type_array), type_params);
2052 // Compute the type parameters for a type, if any, for the given
2054 fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> Option<&'ll DIArray> {
2055 if let ty::Adt(def, substs) = ty.sty {
2056 if !substs.types().next().is_none() {
2057 let generics = cx.tcx.generics_of(def.did);
2058 let names = get_parameter_names(cx, generics);
2059 let template_params: Vec<_> = substs.iter().zip(names).filter_map(|(kind, name)| {
2060 if let UnpackedKind::Type(ty) = kind.unpack() {
2061 let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2062 let actual_type_metadata =
2063 type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
2064 let name = SmallCStr::new(&name.as_str());
2067 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2071 actual_type_metadata,
2072 unknown_file_metadata(cx),
2082 return Some(create_DIArray(DIB(cx), &template_params[..]));
2085 return Some(create_DIArray(DIB(cx), &[]));
2087 fn get_parameter_names(cx: &CodegenCx<'_, '_>,
2088 generics: &ty::Generics)
2089 -> Vec<InternedString> {
2090 let mut names = generics.parent.map_or(vec![], |def_id| {
2091 get_parameter_names(cx, cx.tcx.generics_of(def_id))
2093 names.extend(generics.params.iter().map(|param| param.name));
2098 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
2099 // any caching, does not add any fields to the struct. This can be done later
2100 // with set_members_of_composite_type().
2101 fn create_struct_stub(
2102 cx: &CodegenCx<'ll, 'tcx>,
2103 struct_type: Ty<'tcx>,
2104 struct_type_name: &str,
2105 unique_type_id: UniqueTypeId,
2106 containing_scope: Option<&'ll DIScope>,
2107 ) -> &'ll DICompositeType {
2108 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2110 let name = SmallCStr::new(struct_type_name);
2111 let unique_type_id = SmallCStr::new(
2112 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
2114 let metadata_stub = unsafe {
2115 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
2116 // pointer will lead to hard to trace and debug LLVM assertions
2117 // later on in llvm/lib/IR/Value.cpp.
2118 let empty_array = create_DIArray(DIB(cx), &[]);
2120 llvm::LLVMRustDIBuilderCreateStructType(
2124 unknown_file_metadata(cx),
2125 UNKNOWN_LINE_NUMBER,
2127 struct_align.bits() as u32,
2133 unique_type_id.as_ptr())
2139 fn create_union_stub(
2140 cx: &CodegenCx<'ll, 'tcx>,
2141 union_type: Ty<'tcx>,
2142 union_type_name: &str,
2143 unique_type_id: UniqueTypeId,
2144 containing_scope: &'ll DIScope,
2145 ) -> &'ll DICompositeType {
2146 let (union_size, union_align) = cx.size_and_align_of(union_type);
2148 let name = SmallCStr::new(union_type_name);
2149 let unique_type_id = SmallCStr::new(
2150 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id)
2152 let metadata_stub = unsafe {
2153 // LLVMRustDIBuilderCreateUnionType() wants an empty array. A null
2154 // pointer will lead to hard to trace and debug LLVM assertions
2155 // later on in llvm/lib/IR/Value.cpp.
2156 let empty_array = create_DIArray(DIB(cx), &[]);
2158 llvm::LLVMRustDIBuilderCreateUnionType(
2162 unknown_file_metadata(cx),
2163 UNKNOWN_LINE_NUMBER,
2165 union_align.bits() as u32,
2169 unique_type_id.as_ptr())
2175 /// Creates debug information for the given global variable.
2177 /// Adds the created metadata nodes directly to the crate's IR.
2178 pub fn create_global_var_metadata(
2179 cx: &CodegenCx<'ll, '_>,
2183 if cx.dbg_cx.is_none() {
2188 let attrs = tcx.codegen_fn_attrs(def_id);
2190 if attrs.flags.contains(CodegenFnAttrFlags::NO_DEBUG) {
2194 let no_mangle = attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE);
2195 // We may want to remove the namespace scope if we're in an extern block, see:
2196 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952
2197 let var_scope = get_namespace_for_item(cx, def_id);
2198 let span = tcx.def_span(def_id);
2200 let (file_metadata, line_number) = if !span.is_dummy() {
2201 let loc = span_start(cx, span);
2202 (file_metadata(cx, &loc.file.name, LOCAL_CRATE), loc.line as c_uint)
2204 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2207 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2208 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx);
2209 let type_metadata = type_metadata(cx, variable_type, span);
2210 let var_name = SmallCStr::new(&tcx.item_name(def_id).as_str());
2211 let linkage_name = if no_mangle {
2214 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id));
2215 Some(SmallCStr::new(&linkage_name.as_str()))
2218 let global_align = cx.align_of(variable_type);
2221 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
2224 // If null, linkage_name field is omitted,
2225 // which is what we want for no_mangle statics
2226 linkage_name.as_ref()
2227 .map_or(ptr::null(), |name| name.as_ptr()),
2234 global_align.bytes() as u32,
2239 /// Creates debug information for the given vtable, which is for the
2242 /// Adds the created metadata nodes directly to the crate's IR.
2243 pub fn create_vtable_metadata(
2244 cx: &CodegenCx<'ll, 'tcx>,
2248 if cx.dbg_cx.is_none() {
2252 let type_metadata = type_metadata(cx, ty, syntax_pos::DUMMY_SP);
2255 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
2256 // pointer will lead to hard to trace and debug LLVM assertions
2257 // later on in llvm/lib/IR/Value.cpp.
2258 let empty_array = create_DIArray(DIB(cx), &[]);
2260 let name = const_cstr!("vtable");
2262 // Create a new one each time. We don't want metadata caching
2263 // here, because each vtable will refer to a unique containing
2265 let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
2269 unknown_file_metadata(cx),
2270 UNKNOWN_LINE_NUMBER,
2272 cx.tcx.data_layout.pointer_align.abi.bits() as u32,
2273 DIFlags::FlagArtificial,
2277 Some(type_metadata),
2281 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
2285 unknown_file_metadata(cx),
2286 UNKNOWN_LINE_NUMBER,
2295 // Creates an "extension" of an existing DIScope into another file.
2296 pub fn extend_scope_to_file(
2297 cx: &CodegenCx<'ll, '_>,
2298 scope_metadata: &'ll DIScope,
2299 file: &syntax_pos::SourceFile,
2300 defining_crate: CrateNum,
2301 ) -> &'ll DILexicalBlock {
2302 let file_metadata = file_metadata(cx, &file.name, defining_crate);
2304 llvm::LLVMRustDIBuilderCreateLexicalBlockFile(