1 use self::EnumDiscriminantInfo::*;
2 use self::MemberDescriptionFactory::*;
3 use self::RecursiveTypeDescription::*;
5 use super::namespace::mangled_name_of_instance;
6 use super::type_names::compute_debuginfo_type_name;
8 create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, span_start, DIB,
10 use super::CrateDebugContext;
13 use crate::common::CodegenCx;
15 use crate::llvm::debuginfo::{
16 DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
20 use crate::value::Value;
23 use rustc::ich::NodeIdHashingMode;
24 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
25 use rustc::mir::interpret::truncate;
26 use rustc::mir::{self, Field, GeneratorLayout};
27 use rustc::session::config::{self, DebugInfo};
28 use rustc::ty::layout::{
29 self, Align, Integer, IntegerExt, LayoutOf, PrimitiveExt, Size, TyLayout, VariantIdx,
31 use rustc::ty::subst::{GenericArgKind, SubstsRef};
32 use rustc::ty::Instance;
33 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
34 use rustc::{bug, span_bug};
35 use rustc_codegen_ssa::traits::*;
36 use rustc_data_structures::const_cstr;
37 use rustc_data_structures::fingerprint::Fingerprint;
38 use rustc_data_structures::fx::FxHashMap;
39 use rustc_data_structures::small_c_str::SmallCStr;
40 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
41 use rustc_fs_util::path_to_c_string;
42 use rustc_hir::def::CtorKind;
43 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
44 use rustc_index::vec::{Idx, IndexVec};
45 use rustc_span::symbol::{Interner, Symbol};
46 use rustc_span::{self, FileName, Span};
47 use rustc_target::abi::HasDataLayout;
50 use libc::{c_longlong, c_uint};
51 use std::collections::hash_map::Entry;
52 use std::ffi::CString;
53 use std::fmt::{self, Write};
54 use std::hash::{Hash, Hasher};
56 use std::path::{Path, PathBuf};
59 impl PartialEq for llvm::Metadata {
60 fn eq(&self, other: &Self) -> bool {
65 impl Eq for llvm::Metadata {}
67 impl Hash for llvm::Metadata {
68 fn hash<H: Hasher>(&self, hasher: &mut H) {
69 (self as *const Self).hash(hasher);
73 impl fmt::Debug for llvm::Metadata {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 (self as *const Self).fmt(f)
80 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
81 const DW_LANG_RUST: c_uint = 0x1c;
82 #[allow(non_upper_case_globals)]
83 const DW_ATE_boolean: c_uint = 0x02;
84 #[allow(non_upper_case_globals)]
85 const DW_ATE_float: c_uint = 0x04;
86 #[allow(non_upper_case_globals)]
87 const DW_ATE_signed: c_uint = 0x05;
88 #[allow(non_upper_case_globals)]
89 const DW_ATE_unsigned: c_uint = 0x07;
90 #[allow(non_upper_case_globals)]
91 const DW_ATE_unsigned_char: c_uint = 0x08;
93 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
94 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
96 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
98 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
99 pub struct UniqueTypeId(ast::Name);
101 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
102 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
103 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
106 pub struct TypeMap<'ll, 'tcx> {
107 /// The `UniqueTypeId`s created so far.
108 unique_id_interner: Interner,
109 /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
110 unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
111 /// A map from types to debuginfo metadata. This is an N:1 mapping.
112 type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
113 /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
114 type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
117 impl TypeMap<'ll, 'tcx> {
118 /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
119 /// the mapping already exists.
120 fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
121 if self.type_to_metadata.insert(type_, metadata).is_some() {
122 bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
126 /// Removes a `Ty`-to-metadata mapping.
127 /// This is useful when computing the metadata for a potentially
128 /// recursive type (e.g., a function pointer of the form:
130 /// fn foo() -> impl Copy { foo }
132 /// This kind of type cannot be properly represented
133 /// via LLVM debuginfo. As a workaround,
134 /// we register a temporary Ty to metadata mapping
135 /// for the function before we compute its actual metadata.
136 /// If the metadata computation ends up recursing back to the
137 /// original function, it will use the temporary mapping
138 /// for the inner self-reference, preventing us from
139 /// recursing forever.
141 /// This function is used to remove the temporary metadata
142 /// mapping after we've computed the actual metadata.
143 fn remove_type(&mut self, type_: Ty<'tcx>) {
144 if self.type_to_metadata.remove(type_).is_none() {
145 bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", type_);
149 /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
150 /// fail if the mapping already exists.
151 fn register_unique_id_with_metadata(
153 unique_type_id: UniqueTypeId,
154 metadata: &'ll DIType,
156 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
158 "type metadata for unique ID '{}' is already in the `TypeMap`!",
159 self.get_unique_type_id_as_string(unique_type_id)
164 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
165 self.type_to_metadata.get(&type_).cloned()
168 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
169 self.unique_id_to_metadata.get(&unique_type_id).cloned()
172 /// Gets the string representation of a `UniqueTypeId`. This method will fail if
173 /// the ID is unknown.
174 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
175 let UniqueTypeId(interner_key) = unique_type_id;
176 self.unique_id_interner.get(interner_key)
179 /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
180 /// type has been requested before, this is just a table lookup. Otherwise, an
181 /// ID will be generated and stored for later lookup.
182 fn get_unique_type_id_of_type<'a>(
184 cx: &CodegenCx<'a, 'tcx>,
187 // Let's see if we already have something in the cache.
188 if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
189 return unique_type_id;
191 // If not, generate one.
193 // The hasher we are using to generate the UniqueTypeId. We want
194 // something that provides more than the 64 bits of the DefaultHasher.
195 let mut hasher = StableHasher::new();
196 let mut hcx = cx.tcx.create_stable_hashing_context();
197 let type_ = cx.tcx.erase_regions(&type_);
198 hcx.while_hashing_spans(false, |hcx| {
199 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
200 type_.hash_stable(hcx, &mut hasher);
203 let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
205 let key = self.unique_id_interner.intern(&unique_type_id);
206 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
208 return UniqueTypeId(key);
211 /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
212 /// types of their own, so they need special handling. We still need a
213 /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
214 fn get_unique_type_id_of_enum_variant<'a>(
216 cx: &CodegenCx<'a, 'tcx>,
220 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
221 let enum_variant_type_id =
222 format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
223 let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
224 UniqueTypeId(interner_key)
227 /// Gets the unique type ID string for an enum variant part.
228 /// Variant parts are not types and shouldn't really have their own ID,
229 /// but it makes `set_members_of_composite_type()` simpler.
230 fn get_unique_type_id_str_of_enum_variant_part(&mut self, enum_type_id: UniqueTypeId) -> &str {
231 let variant_part_type_id =
232 format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id));
233 let interner_key = self.unique_id_interner.intern(&variant_part_type_id);
234 self.unique_id_interner.get(interner_key)
238 /// A description of some recursive type. It can either be already finished (as
239 /// with `FinalMetadata`) or it is not yet finished, but contains all information
240 /// needed to generate the missing parts of the description. See the
241 /// documentation section on Recursive Types at the top of this file for more
243 enum RecursiveTypeDescription<'ll, 'tcx> {
245 unfinished_type: Ty<'tcx>,
246 unique_type_id: UniqueTypeId,
247 metadata_stub: &'ll DICompositeType,
248 member_holding_stub: &'ll DICompositeType,
249 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
251 FinalMetadata(&'ll DICompositeType),
254 fn create_and_register_recursive_type_forward_declaration(
255 cx: &CodegenCx<'ll, 'tcx>,
256 unfinished_type: Ty<'tcx>,
257 unique_type_id: UniqueTypeId,
258 metadata_stub: &'ll DICompositeType,
259 member_holding_stub: &'ll DICompositeType,
260 member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
261 ) -> RecursiveTypeDescription<'ll, 'tcx> {
262 // Insert the stub into the `TypeMap` in order to allow for recursive references.
263 let mut type_map = debug_context(cx).type_map.borrow_mut();
264 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
265 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
272 member_description_factory,
276 impl RecursiveTypeDescription<'ll, 'tcx> {
277 /// Finishes up the description of the type in question (mostly by providing
278 /// descriptions of the fields of the given type) and returns the final type
280 fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
282 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
288 ref member_description_factory,
290 // Make sure that we have a forward declaration of the type in
291 // the TypeMap so that recursive references are possible. This
292 // will always be the case if the RecursiveTypeDescription has
293 // been properly created through the
294 // `create_and_register_recursive_type_forward_declaration()`
297 let type_map = debug_context(cx).type_map.borrow();
298 if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
299 || type_map.find_metadata_for_type(unfinished_type).is_none()
302 "Forward declaration of potentially recursive type \
303 '{:?}' was not found in TypeMap!",
309 // ... then create the member descriptions ...
310 let member_descriptions = member_description_factory.create_member_descriptions(cx);
312 // ... and attach them to the stub to complete it.
313 set_members_of_composite_type(
319 return MetadataCreationResult::new(metadata_stub, true);
325 /// Returns from the enclosing function if the type metadata with the given
326 /// unique ID can be found in the type map.
327 macro_rules! return_if_metadata_created_in_meantime {
328 ($cx: expr, $unique_type_id: expr) => {
329 if let Some(metadata) =
330 debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
332 return MetadataCreationResult::new(metadata, true);
337 fn fixed_vec_metadata(
338 cx: &CodegenCx<'ll, 'tcx>,
339 unique_type_id: UniqueTypeId,
340 array_or_slice_type: Ty<'tcx>,
341 element_type: Ty<'tcx>,
343 ) -> MetadataCreationResult<'ll> {
344 let element_type_metadata = type_metadata(cx, element_type, span);
346 return_if_metadata_created_in_meantime!(cx, unique_type_id);
348 let (size, align) = cx.size_and_align_of(array_or_slice_type);
350 let upper_bound = match array_or_slice_type.kind {
351 ty::Array(_, len) => len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong,
356 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
358 let subscripts = create_DIArray(DIB(cx), &[subrange]);
359 let metadata = unsafe {
360 llvm::LLVMRustDIBuilderCreateArrayType(
364 element_type_metadata,
369 return MetadataCreationResult::new(metadata, false);
372 fn vec_slice_metadata(
373 cx: &CodegenCx<'ll, 'tcx>,
374 slice_ptr_type: Ty<'tcx>,
375 element_type: Ty<'tcx>,
376 unique_type_id: UniqueTypeId,
378 ) -> MetadataCreationResult<'ll> {
379 let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
381 let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
383 return_if_metadata_created_in_meantime!(cx, unique_type_id);
385 let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
387 let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
388 let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
390 let member_descriptions = vec![
392 name: "data_ptr".to_owned(),
393 type_metadata: data_ptr_metadata,
396 align: pointer_align,
397 flags: DIFlags::FlagZero,
401 name: "length".to_owned(),
402 type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
403 offset: pointer_size,
406 flags: DIFlags::FlagZero,
411 let file_metadata = unknown_file_metadata(cx);
413 let metadata = composite_type_metadata(
416 &slice_type_name[..],
423 MetadataCreationResult::new(metadata, false)
426 fn subroutine_type_metadata(
427 cx: &CodegenCx<'ll, 'tcx>,
428 unique_type_id: UniqueTypeId,
429 signature: ty::PolyFnSig<'tcx>,
431 ) -> MetadataCreationResult<'ll> {
433 cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &signature);
435 let signature_metadata: Vec<_> = iter::once(
437 match signature.output().kind {
438 ty::Tuple(ref tys) if tys.is_empty() => None,
439 _ => Some(type_metadata(cx, signature.output(), span)),
444 signature.inputs().iter().map(|argument_type| Some(type_metadata(cx, argument_type, span))),
448 return_if_metadata_created_in_meantime!(cx, unique_type_id);
450 return MetadataCreationResult::new(
452 llvm::LLVMRustDIBuilderCreateSubroutineType(
454 unknown_file_metadata(cx),
455 create_DIArray(DIB(cx), &signature_metadata[..]),
462 // FIXME(1563): This is all a bit of a hack because 'trait pointer' is an ill-
463 // defined concept. For the case of an actual trait pointer (i.e., `Box<Trait>`,
464 // `&Trait`), `trait_object_type` should be the whole thing (e.g, `Box<Trait>`) and
465 // `trait_type` should be the actual trait (e.g., `Trait`). Where the trait is part
466 // of a DST struct, there is no `trait_object_type` and the results of this
467 // function will be a little bit weird.
468 fn trait_pointer_metadata(
469 cx: &CodegenCx<'ll, 'tcx>,
470 trait_type: Ty<'tcx>,
471 trait_object_type: Option<Ty<'tcx>>,
472 unique_type_id: UniqueTypeId,
474 // The implementation provided here is a stub. It makes sure that the trait
475 // type is assigned the correct name, size, namespace, and source location.
476 // However, it does not describe the trait's methods.
478 let containing_scope = match trait_type.kind {
479 ty::Dynamic(ref data, ..) => {
480 data.principal_def_id().map(|did| get_namespace_for_item(cx, did))
484 "debuginfo: unexpected trait-object type in \
485 trait_pointer_metadata(): {:?}",
491 let trait_object_type = trait_object_type.unwrap_or(trait_type);
492 let trait_type_name = compute_debuginfo_type_name(cx.tcx, trait_object_type, false);
494 let file_metadata = unknown_file_metadata(cx);
496 let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
498 assert_eq!(abi::FAT_PTR_ADDR, 0);
499 assert_eq!(abi::FAT_PTR_EXTRA, 1);
501 let data_ptr_field = layout.field(cx, 0);
502 let vtable_field = layout.field(cx, 1);
503 let member_descriptions = vec![
505 name: "pointer".to_owned(),
506 type_metadata: type_metadata(
508 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
509 rustc_span::DUMMY_SP,
511 offset: layout.fields.offset(0),
512 size: data_ptr_field.size,
513 align: data_ptr_field.align.abi,
514 flags: DIFlags::FlagArtificial,
518 name: "vtable".to_owned(),
519 type_metadata: type_metadata(cx, vtable_field.ty, rustc_span::DUMMY_SP),
520 offset: layout.fields.offset(1),
521 size: vtable_field.size,
522 align: vtable_field.align.abi,
523 flags: DIFlags::FlagArtificial,
528 composite_type_metadata(
531 &trait_type_name[..],
536 rustc_span::DUMMY_SP,
540 pub fn type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Span) -> &'ll DIType {
541 // Get the unique type ID of this type.
542 let unique_type_id = {
543 let mut type_map = debug_context(cx).type_map.borrow_mut();
544 // First, try to find the type in `TypeMap`. If we have seen it before, we
545 // can exit early here.
546 match type_map.find_metadata_for_type(t) {
551 // The Ty is not in the `TypeMap` but maybe we have already seen
552 // an equivalent type (e.g., only differing in region arguments).
553 // In order to find out, generate the unique type ID and look
555 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
556 match type_map.find_metadata_for_unique_id(unique_type_id) {
558 // There is already an equivalent type in the TypeMap.
559 // Register this Ty as an alias in the cache and
560 // return the cached metadata.
561 type_map.register_type_with_metadata(t, metadata);
565 // There really is no type metadata for this type, so
566 // proceed by creating it.
574 debug!("type_metadata: {:?}", t);
576 let ptr_metadata = |ty: Ty<'tcx>| match ty.kind {
577 ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)),
578 ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)),
579 ty::Dynamic(..) => Ok(MetadataCreationResult::new(
580 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
584 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
586 if let Some(metadata) =
587 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
589 return Err(metadata);
592 Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), false))
596 let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.kind {
597 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
598 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
600 ty::Tuple(ref elements) if elements.is_empty() => {
601 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
603 ty::Array(typ, _) | ty::Slice(typ) => {
604 fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
606 ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span),
608 MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false)
611 MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
613 ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => match ptr_metadata(ty) {
615 Err(metadata) => return metadata,
617 ty::Adt(def, _) if def.is_box() => match ptr_metadata(t.boxed_ty()) {
619 Err(metadata) => return metadata,
621 ty::FnDef(..) | ty::FnPtr(_) => {
622 if let Some(metadata) =
623 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
628 // It's possible to create a self-referential
629 // type in Rust by using 'impl trait':
631 // fn foo() -> impl Copy { foo }
633 // See `TypeMap::remove_type` for more detals
634 // about the workaround.
638 // The choice of type here is pretty arbitrary -
639 // anything reading the debuginfo for a recursive
640 // type is going to see *somthing* weird - the only
641 // question is what exactly it will see.
642 let (size, align) = cx.size_and_align_of(t);
643 llvm::LLVMRustDIBuilderCreateBasicType(
645 SmallCStr::new("<recur_type>").as_ptr(),
653 let type_map = &debug_context(cx).type_map;
654 type_map.borrow_mut().register_type_with_metadata(t, temp_type);
657 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx), usage_site_span)
660 type_map.borrow_mut().remove_type(t);
662 // This is actually a function pointer, so wrap it in pointer DI.
663 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
665 ty::Closure(def_id, substs) => {
666 let upvar_tys: Vec<_> = substs.as_closure().upvar_tys(def_id, cx.tcx).collect();
667 let containing_scope = get_namespace_for_item(cx, def_id);
668 prepare_tuple_metadata(
674 Some(containing_scope),
678 ty::Generator(def_id, substs, _) => {
679 let upvar_tys: Vec<_> = substs
681 .prefix_tys(def_id, cx.tcx)
682 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
684 prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span, upvar_tys)
687 ty::Adt(def, ..) => match def.adt_kind() {
689 prepare_struct_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
692 prepare_union_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
695 prepare_enum_metadata(cx, t, def.did, unique_type_id, usage_site_span, vec![])
699 ty::Tuple(ref elements) => {
700 let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
701 prepare_tuple_metadata(cx, t, &tys, unique_type_id, usage_site_span, NO_SCOPE_METADATA)
704 _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
708 let mut type_map = debug_context(cx).type_map.borrow_mut();
710 if already_stored_in_typemap {
711 // Also make sure that we already have a `TypeMap` entry for the unique type ID.
712 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
713 Some(metadata) => metadata,
717 "expected type metadata for unique \
718 type ID '{}' to already be in \
719 the `debuginfo::TypeMap` but it \
721 type_map.get_unique_type_id_as_string(unique_type_id),
727 match type_map.find_metadata_for_type(t) {
729 if metadata != metadata_for_uid {
732 "mismatch between `Ty` and \
733 `UniqueTypeId` maps in \
734 `debuginfo::TypeMap`. \
735 UniqueTypeId={}, Ty={}",
736 type_map.get_unique_type_id_as_string(unique_type_id),
742 type_map.register_type_with_metadata(t, metadata);
746 type_map.register_type_with_metadata(t, metadata);
747 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
754 pub fn file_metadata(
755 cx: &CodegenCx<'ll, '_>,
756 file_name: &FileName,
757 defining_crate: CrateNum,
759 debug!("file_metadata: file_name: {}, defining_crate: {}", file_name, defining_crate);
761 let file_name = Some(file_name.to_string());
762 let directory = if defining_crate == LOCAL_CRATE {
763 Some(cx.sess().working_dir.0.to_string_lossy().to_string())
765 // If the path comes from an upstream crate we assume it has been made
766 // independent of the compiler's working directory one way or another.
769 file_metadata_raw(cx, file_name, directory)
772 pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
773 file_metadata_raw(cx, None, None)
776 fn file_metadata_raw(
777 cx: &CodegenCx<'ll, '_>,
778 file_name: Option<String>,
779 directory: Option<String>,
781 let key = (file_name, directory);
783 match debug_context(cx).created_files.borrow_mut().entry(key) {
784 Entry::Occupied(o) => return o.get(),
785 Entry::Vacant(v) => {
786 let (file_name, directory) = v.key();
787 debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
789 let file_name = SmallCStr::new(if let Some(file_name) = file_name {
795 SmallCStr::new(if let Some(directory) = directory { &directory } else { "" });
797 let file_metadata = unsafe {
798 llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(), directory.as_ptr())
801 v.insert(file_metadata);
807 fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
808 debug!("basic_type_metadata: {:?}", t);
810 let (name, encoding) = match t.kind {
811 ty::Never => ("!", DW_ATE_unsigned),
812 ty::Tuple(ref elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
813 ty::Bool => ("bool", DW_ATE_boolean),
814 ty::Char => ("char", DW_ATE_unsigned_char),
815 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
816 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
817 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
818 _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
821 let (size, align) = cx.size_and_align_of(t);
822 let name = SmallCStr::new(name);
823 let ty_metadata = unsafe {
824 llvm::LLVMRustDIBuilderCreateBasicType(
836 fn foreign_type_metadata(
837 cx: &CodegenCx<'ll, 'tcx>,
839 unique_type_id: UniqueTypeId,
841 debug!("foreign_type_metadata: {:?}", t);
843 let name = compute_debuginfo_type_name(cx.tcx, t, false);
844 create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA)
847 fn pointer_type_metadata(
848 cx: &CodegenCx<'ll, 'tcx>,
849 pointer_type: Ty<'tcx>,
850 pointee_type_metadata: &'ll DIType,
852 let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
853 let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
854 let name = SmallCStr::new(&name);
856 llvm::LLVMRustDIBuilderCreatePointerType(
858 pointee_type_metadata,
860 pointer_align.bits() as u32,
866 pub fn compile_unit_metadata(
868 codegen_unit_name: &str,
869 debug_context: &CrateDebugContext<'ll, '_>,
870 ) -> &'ll DIDescriptor {
871 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
872 Some(ref path) => path.clone(),
873 None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
876 // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
877 // if multiple object files with the same `DW_AT_name` are linked together.
878 // As a workaround we generate unique names for each object file. Those do
879 // not correspond to an actual source file but that should be harmless.
880 if tcx.sess.target.target.options.is_like_osx {
881 name_in_debuginfo.push("@");
882 name_in_debuginfo.push(codegen_unit_name);
885 debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
887 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
888 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
889 let producer = format!("clang LLVM ({})", rustc_producer);
891 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
892 let name_in_debuginfo = SmallCStr::new(&name_in_debuginfo);
893 let work_dir = SmallCStr::new(&tcx.sess.working_dir.0.to_string_lossy());
894 let producer = CString::new(producer).unwrap();
896 let split_name = "\0";
900 // This should actually be
902 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
904 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
905 // we are compiling with "limited" debuginfo. However, some of the
906 // existing tools relied on slightly more debuginfo being generated than
907 // would be the case with `LineTablesOnly`, and we did not want to break
908 // these tools in a "drive-by fix", without a good idea or plan about
909 // what limited debuginfo should exactly look like. So for now we keep
910 // the emission kind as `FullDebug`.
912 // See https://github.com/rust-lang/rust/issues/60020 for details.
913 let kind = DebugEmissionKind::FullDebug;
914 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
917 let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
918 debug_context.builder,
919 name_in_debuginfo.as_ptr(),
923 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
924 debug_context.builder,
928 tcx.sess.opts.optimize != config::OptLevel::No,
929 flags.as_ptr().cast(),
931 split_name.as_ptr().cast(),
935 if tcx.sess.opts.debugging_opts.profile {
936 let cu_desc_metadata =
937 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
941 debug_context.llcontext,
942 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno"),
945 debug_context.llcontext,
946 &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda"),
950 let gcov_metadata = llvm::LLVMMDNodeInContext(
951 debug_context.llcontext,
952 gcov_cu_info.as_ptr(),
953 gcov_cu_info.len() as c_uint,
956 let llvm_gcov_ident = const_cstr!("llvm.gcov");
957 llvm::LLVMAddNamedMetadataOperand(
959 llvm_gcov_ident.as_ptr(),
964 // Insert `llvm.ident` metadata on the wasm32 targets since that will
965 // get hooked up to the "producer" sections `processed-by` information.
966 if tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
967 let name_metadata = llvm::LLVMMDStringInContext(
968 debug_context.llcontext,
969 rustc_producer.as_ptr().cast(),
970 rustc_producer.as_bytes().len() as c_uint,
972 llvm::LLVMAddNamedMetadataOperand(
974 const_cstr!("llvm.ident").as_ptr(),
975 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
979 return unit_metadata;
982 fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
983 let path_str = path_to_c_string(path);
985 llvm::LLVMMDStringInContext(
988 path_str.as_bytes().len() as c_uint,
994 struct MetadataCreationResult<'ll> {
995 metadata: &'ll DIType,
996 already_stored_in_typemap: bool,
999 impl MetadataCreationResult<'ll> {
1000 fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1001 MetadataCreationResult { metadata, already_stored_in_typemap }
1005 /// Description of a type member, which can either be a regular field (as in
1006 /// structs or tuples) or an enum variant.
1008 struct MemberDescription<'ll> {
1010 type_metadata: &'ll DIType,
1015 discriminant: Option<u64>,
1018 impl<'ll> MemberDescription<'ll> {
1021 cx: &CodegenCx<'ll, '_>,
1022 composite_type_metadata: &'ll DIScope,
1024 let member_name = CString::new(self.name).unwrap();
1026 llvm::LLVMRustDIBuilderCreateVariantMemberType(
1028 composite_type_metadata,
1029 member_name.as_ptr(),
1030 unknown_file_metadata(cx),
1031 UNKNOWN_LINE_NUMBER,
1033 self.align.bits() as u32,
1035 match self.discriminant {
1037 Some(value) => Some(cx.const_u64(value)),
1046 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1047 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1048 /// creation of type member descriptions in order to break cycles arising from
1049 /// recursive type definitions.
1050 enum MemberDescriptionFactory<'ll, 'tcx> {
1051 StructMDF(StructMemberDescriptionFactory<'tcx>),
1052 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1053 EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1054 UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1055 VariantMDF(VariantMemberDescriptionFactory<'ll, 'tcx>),
1058 impl MemberDescriptionFactory<'ll, 'tcx> {
1059 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1061 StructMDF(ref this) => this.create_member_descriptions(cx),
1062 TupleMDF(ref this) => this.create_member_descriptions(cx),
1063 EnumMDF(ref this) => this.create_member_descriptions(cx),
1064 UnionMDF(ref this) => this.create_member_descriptions(cx),
1065 VariantMDF(ref this) => this.create_member_descriptions(cx),
1070 //=-----------------------------------------------------------------------------
1072 //=-----------------------------------------------------------------------------
1074 /// Creates `MemberDescription`s for the fields of a struct.
1075 struct StructMemberDescriptionFactory<'tcx> {
1077 variant: &'tcx ty::VariantDef,
1081 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1082 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1083 let layout = cx.layout_of(self.ty);
1089 let name = if self.variant.ctor_kind == CtorKind::Fn {
1094 let field = layout.field(cx, i);
1097 type_metadata: type_metadata(cx, field.ty, self.span),
1098 offset: layout.fields.offset(i),
1100 align: field.align.abi,
1101 flags: DIFlags::FlagZero,
1109 fn prepare_struct_metadata(
1110 cx: &CodegenCx<'ll, 'tcx>,
1111 struct_type: Ty<'tcx>,
1112 unique_type_id: UniqueTypeId,
1114 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1115 let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1117 let (struct_def_id, variant) = match struct_type.kind {
1118 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1119 _ => bug!("prepare_struct_metadata on a non-ADT"),
1122 let containing_scope = get_namespace_for_item(cx, struct_def_id);
1124 let struct_metadata_stub =
1125 create_struct_stub(cx, struct_type, &struct_name, unique_type_id, Some(containing_scope));
1127 create_and_register_recursive_type_forward_declaration(
1131 struct_metadata_stub,
1132 struct_metadata_stub,
1133 StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant, span }),
1137 //=-----------------------------------------------------------------------------
1139 //=-----------------------------------------------------------------------------
1141 /// Creates `MemberDescription`s 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>) -> Vec<MemberDescription<'ll>> {
1150 let layout = cx.layout_of(self.ty);
1151 self.component_types
1154 .map(|(i, &component_type)| {
1155 let (size, align) = cx.size_and_align_of(component_type);
1157 name: format!("__{}", i),
1158 type_metadata: type_metadata(cx, component_type, self.span),
1159 offset: layout.fields.offset(i),
1162 flags: DIFlags::FlagZero,
1170 fn prepare_tuple_metadata(
1171 cx: &CodegenCx<'ll, 'tcx>,
1172 tuple_type: Ty<'tcx>,
1173 component_types: &[Ty<'tcx>],
1174 unique_type_id: UniqueTypeId,
1176 containing_scope: Option<&'ll DIScope>,
1177 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1178 let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1181 create_struct_stub(cx, tuple_type, &tuple_name[..], unique_type_id, containing_scope);
1183 create_and_register_recursive_type_forward_declaration(
1189 TupleMDF(TupleMemberDescriptionFactory {
1191 component_types: component_types.to_vec(),
1197 //=-----------------------------------------------------------------------------
1199 //=-----------------------------------------------------------------------------
1201 struct UnionMemberDescriptionFactory<'tcx> {
1202 layout: TyLayout<'tcx>,
1203 variant: &'tcx ty::VariantDef,
1207 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1208 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1214 let field = self.layout.field(cx, i);
1216 name: f.ident.to_string(),
1217 type_metadata: type_metadata(cx, field.ty, self.span),
1220 align: field.align.abi,
1221 flags: DIFlags::FlagZero,
1229 fn prepare_union_metadata(
1230 cx: &CodegenCx<'ll, 'tcx>,
1231 union_type: Ty<'tcx>,
1232 unique_type_id: UniqueTypeId,
1234 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1235 let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1237 let (union_def_id, variant) = match union_type.kind {
1238 ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1239 _ => bug!("prepare_union_metadata on a non-ADT"),
1242 let containing_scope = get_namespace_for_item(cx, union_def_id);
1244 let union_metadata_stub =
1245 create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1247 create_and_register_recursive_type_forward_declaration(
1251 union_metadata_stub,
1252 union_metadata_stub,
1253 UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant, span }),
1257 //=-----------------------------------------------------------------------------
1259 //=-----------------------------------------------------------------------------
1261 /// DWARF variant support is only available starting in LLVM 8.
1262 /// Although the earlier enum debug info output did not work properly
1263 /// in all situations, it is better for the time being to continue to
1264 /// sometimes emit the old style rather than emit something completely
1265 /// useless when rust is compiled against LLVM 6 or older. LLVM 7
1266 /// contains an early version of the DWARF variant support, and will
1267 /// crash when handling the new debug info format. This function
1268 /// decides which representation will be emitted.
1269 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1270 // On MSVC we have to use the fallback mode, because LLVM doesn't
1271 // lower variant parts to PDB.
1272 return cx.sess().target.target.options.is_like_msvc
1273 // LLVM version 7 did not release with an important bug fix;
1274 // but the required patch is in the LLVM 8. Rust LLVM reports
1276 || llvm_util::get_major_version() < 8;
1279 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1280 // per generator monomorphization, but it doesn't depend on substs.
1281 fn generator_layout_and_saved_local_names(
1284 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<ast::Name>>) {
1285 let body = tcx.optimized_mir(def_id);
1286 let generator_layout = body.generator_layout.as_ref().unwrap();
1287 let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1289 let state_arg = mir::Local::new(1);
1290 for var in &body.var_debug_info {
1291 if var.place.local != state_arg {
1294 match var.place.projection[..] {
1296 // Deref of the `Pin<&mut Self>` state argument.
1297 mir::ProjectionElem::Field(..),
1298 mir::ProjectionElem::Deref,
1300 // Field of a variant of the state.
1301 mir::ProjectionElem::Downcast(_, variant),
1302 mir::ProjectionElem::Field(field, _),
1304 let name = &mut generator_saved_local_names[
1305 generator_layout.variant_fields[variant][field]
1308 name.replace(var.name);
1314 (generator_layout, generator_saved_local_names)
1317 /// Describes the members of an enum value; an enum is described as a union of
1318 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1319 /// the members of this union; so for every variant of the given enum, this
1320 /// factory will produce one `MemberDescription` (all with no name and a fixed
1321 /// offset of zero bytes).
1322 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1323 enum_type: Ty<'tcx>,
1324 layout: TyLayout<'tcx>,
1325 discriminant_type_metadata: Option<&'ll DIType>,
1326 containing_scope: &'ll DIScope,
1330 impl EnumMemberDescriptionFactory<'ll, 'tcx> {
1331 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1332 let generator_variant_info_data = match self.enum_type.kind {
1333 ty::Generator(def_id, ..) => {
1334 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1339 let variant_info_for = |index: VariantIdx| match self.enum_type.kind {
1340 ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1341 ty::Generator(_, substs, _) => {
1342 let (generator_layout, generator_saved_local_names) =
1343 generator_variant_info_data.as_ref().unwrap();
1344 VariantInfo::Generator {
1346 generator_layout: *generator_layout,
1347 generator_saved_local_names,
1348 variant_index: index,
1354 // This will always find the metadata in the type map.
1355 let fallback = use_enum_fallback(cx);
1356 let self_metadata = if fallback {
1357 self.containing_scope
1359 type_metadata(cx, self.enum_type, self.span)
1362 match self.layout.variants {
1363 layout::Variants::Single { index } => {
1364 if let ty::Adt(adt, _) = &self.enum_type.kind {
1365 if adt.variants.is_empty() {
1370 let variant_info = variant_info_for(index);
1371 let (variant_type_metadata, member_description_factory) = describe_enum_variant(
1380 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1382 set_members_of_composite_type(
1385 variant_type_metadata,
1386 member_descriptions,
1388 vec![MemberDescription {
1389 name: if fallback { String::new() } else { variant_info.variant_name() },
1390 type_metadata: variant_type_metadata,
1392 size: self.layout.size,
1393 align: self.layout.align.abi,
1394 flags: DIFlags::FlagZero,
1398 layout::Variants::Multiple {
1399 discr_kind: layout::DiscriminantKind::Tag,
1404 let discriminant_info = if fallback {
1405 RegularDiscriminant {
1406 discr_field: Field::from(discr_index),
1407 discr_type_metadata: self.discriminant_type_metadata.unwrap(),
1410 // This doesn't matter in this case.
1416 let variant = self.layout.for_variant(cx, i);
1417 let variant_info = variant_info_for(i);
1418 let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1427 let member_descriptions =
1428 member_desc_factory.create_member_descriptions(cx);
1430 set_members_of_composite_type(
1433 variant_type_metadata,
1434 member_descriptions,
1441 variant_info.variant_name()
1443 type_metadata: variant_type_metadata,
1445 size: self.layout.size,
1446 align: self.layout.align.abi,
1447 flags: DIFlags::FlagZero,
1449 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1456 layout::Variants::Multiple {
1458 layout::DiscriminantKind::Niche { ref niche_variants, niche_start, dataful_variant },
1464 let variant = self.layout.for_variant(cx, dataful_variant);
1465 // Create a description of the non-null variant.
1466 let (variant_type_metadata, member_description_factory) = describe_enum_variant(
1469 variant_info_for(dataful_variant),
1470 OptimizedDiscriminant,
1471 self.containing_scope,
1475 let variant_member_descriptions =
1476 member_description_factory.create_member_descriptions(cx);
1478 set_members_of_composite_type(
1481 variant_type_metadata,
1482 variant_member_descriptions,
1485 // Encode the information about the null variant in the union
1487 let mut name = String::from("RUST$ENCODED$ENUM$");
1488 // Right now it's not even going to work for `niche_start > 0`,
1489 // and for multiple niche variants it only supports the first.
1490 fn compute_field_path<'a, 'tcx>(
1491 cx: &CodegenCx<'a, 'tcx>,
1493 layout: TyLayout<'tcx>,
1497 for i in 0..layout.fields.count() {
1498 let field_offset = layout.fields.offset(i);
1499 if field_offset > offset {
1502 let inner_offset = offset - field_offset;
1503 let field = layout.field(cx, i);
1504 if inner_offset + size <= field.size {
1505 write!(name, "{}$", i).unwrap();
1506 compute_field_path(cx, name, field, inner_offset, size);
1514 self.layout.fields.offset(discr_index),
1515 self.layout.field(cx, discr_index).size,
1517 variant_info_for(*niche_variants.start()).map_struct_name(|variant_name| {
1518 name.push_str(variant_name);
1521 // Create the (singleton) list of descriptions of union members.
1522 vec![MemberDescription {
1524 type_metadata: variant_type_metadata,
1527 align: variant.align.abi,
1528 flags: DIFlags::FlagZero,
1535 let variant = self.layout.for_variant(cx, i);
1536 let variant_info = variant_info_for(i);
1537 let (variant_type_metadata, member_desc_factory) =
1538 describe_enum_variant(
1542 OptimizedDiscriminant,
1547 let member_descriptions =
1548 member_desc_factory.create_member_descriptions(cx);
1550 set_members_of_composite_type(
1553 variant_type_metadata,
1554 member_descriptions,
1557 let niche_value = if i == dataful_variant {
1560 let value = (i.as_u32() as u128)
1561 .wrapping_sub(niche_variants.start().as_u32() as u128)
1562 .wrapping_add(niche_start);
1563 let value = truncate(value, discr.value.size(cx));
1564 // NOTE(eddyb) do *NOT* remove this assert, until
1565 // we pass the full 128-bit value to LLVM, otherwise
1566 // truncation will be silent and remain undetected.
1567 assert_eq!(value as u64 as u128, value);
1572 name: variant_info.variant_name(),
1573 type_metadata: variant_type_metadata,
1575 size: self.layout.size,
1576 align: self.layout.align.abi,
1577 flags: DIFlags::FlagZero,
1578 discriminant: niche_value,
1588 // Creates `MemberDescription`s for the fields of a single enum variant.
1589 struct VariantMemberDescriptionFactory<'ll, 'tcx> {
1590 /// Cloned from the `layout::Struct` describing the variant.
1591 offsets: Vec<layout::Size>,
1592 args: Vec<(String, Ty<'tcx>)>,
1593 discriminant_type_metadata: Option<&'ll DIType>,
1597 impl VariantMemberDescriptionFactory<'ll, 'tcx> {
1598 fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1602 .map(|(i, &(ref name, ty))| {
1603 let (size, align) = cx.size_and_align_of(ty);
1605 name: name.to_string(),
1606 type_metadata: if use_enum_fallback(cx) {
1607 match self.discriminant_type_metadata {
1608 // Discriminant is always the first field of our variant
1609 // when using the enum fallback.
1610 Some(metadata) if i == 0 => metadata,
1611 _ => type_metadata(cx, ty, self.span),
1614 type_metadata(cx, ty, self.span)
1616 offset: self.offsets[i],
1619 flags: DIFlags::FlagZero,
1627 #[derive(Copy, Clone)]
1628 enum EnumDiscriminantInfo<'ll> {
1629 RegularDiscriminant { discr_field: Field, discr_type_metadata: &'ll DIType },
1630 OptimizedDiscriminant,
1634 #[derive(Copy, Clone)]
1635 enum VariantInfo<'a, 'tcx> {
1636 Adt(&'tcx ty::VariantDef),
1638 substs: SubstsRef<'tcx>,
1639 generator_layout: &'tcx GeneratorLayout<'tcx>,
1640 generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<ast::Name>>,
1641 variant_index: VariantIdx,
1645 impl<'tcx> VariantInfo<'_, 'tcx> {
1646 fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1648 VariantInfo::Adt(variant) => f(&variant.ident.as_str()),
1649 VariantInfo::Generator { substs, variant_index, .. } => {
1650 f(&substs.as_generator().variant_name(*variant_index))
1655 fn variant_name(&self) -> String {
1657 VariantInfo::Adt(variant) => variant.ident.to_string(),
1658 VariantInfo::Generator { variant_index, .. } => {
1659 // Since GDB currently prints out the raw discriminant along
1660 // with every variant, make each variant name be just the value
1661 // of the discriminant. The struct name for the variant includes
1662 // the actual variant description.
1663 format!("{}", variant_index.as_usize())
1668 fn field_name(&self, i: usize) -> String {
1669 let field_name = match *self {
1670 VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1671 Some(variant.fields[i].ident.name)
1673 VariantInfo::Generator {
1675 generator_saved_local_names,
1679 generator_saved_local_names
1680 [generator_layout.variant_fields[variant_index][i.into()]]
1684 field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1688 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1689 /// `MemberDescriptionFactory` for producing the descriptions of the
1690 /// fields of the variant. This is a rudimentary version of a full
1691 /// `RecursiveTypeDescription`.
1692 fn describe_enum_variant(
1693 cx: &CodegenCx<'ll, 'tcx>,
1694 layout: layout::TyLayout<'tcx>,
1695 variant: VariantInfo<'_, 'tcx>,
1696 discriminant_info: EnumDiscriminantInfo<'ll>,
1697 containing_scope: &'ll DIScope,
1699 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
1700 let metadata_stub = variant.map_struct_name(|variant_name| {
1701 let unique_type_id = debug_context(cx)
1704 .get_unique_type_id_of_enum_variant(cx, layout.ty, &variant_name);
1705 create_struct_stub(cx, layout.ty, &variant_name, unique_type_id, Some(containing_scope))
1708 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1709 let (offsets, args) = if use_enum_fallback(cx) {
1710 // If this is not a univariant enum, there is also the discriminant field.
1711 let (discr_offset, discr_arg) = match discriminant_info {
1712 RegularDiscriminant { discr_field, .. } => {
1713 // We have the layout of an enum variant, we need the layout of the outer enum
1714 let enum_layout = cx.layout_of(layout.ty);
1715 let offset = enum_layout.fields.offset(discr_field.as_usize());
1717 ("RUST$ENUM$DISR".to_owned(), enum_layout.field(cx, discr_field.as_usize()).ty);
1718 (Some(offset), Some(args))
1725 .chain((0..layout.fields.count()).map(|i| layout.fields.offset(i)))
1730 (0..layout.fields.count())
1731 .map(|i| (variant.field_name(i), layout.field(cx, i).ty)),
1737 (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect(),
1738 (0..layout.fields.count())
1739 .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
1744 let member_description_factory = VariantMDF(VariantMemberDescriptionFactory {
1747 discriminant_type_metadata: match discriminant_info {
1748 RegularDiscriminant { discr_type_metadata, .. } => Some(discr_type_metadata),
1754 (metadata_stub, member_description_factory)
1757 fn prepare_enum_metadata(
1758 cx: &CodegenCx<'ll, 'tcx>,
1759 enum_type: Ty<'tcx>,
1761 unique_type_id: UniqueTypeId,
1763 outer_field_tys: Vec<Ty<'tcx>>,
1764 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1765 let enum_name = compute_debuginfo_type_name(cx.tcx, enum_type, false);
1767 let containing_scope = get_namespace_for_item(cx, enum_def_id);
1768 // FIXME: This should emit actual file metadata for the enum, but we
1769 // currently can't get the necessary information when it comes to types
1770 // imported from other crates. Formerly we violated the ODR when performing
1771 // LTO because we emitted debuginfo for the same type with varying file
1772 // metadata, so as a workaround we pretend that the type comes from
1774 let file_metadata = unknown_file_metadata(cx);
1776 let discriminant_type_metadata = |discr: layout::Primitive| {
1777 let enumerators_metadata: Vec<_> = match enum_type.kind {
1778 ty::Adt(def, _) => def
1779 .discriminants(cx.tcx)
1781 .map(|((_, discr), v)| {
1782 let name = SmallCStr::new(&v.ident.as_str());
1784 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1787 // FIXME: what if enumeration has i128 discriminant?
1793 ty::Generator(_, substs, _) => substs
1795 .variant_range(enum_def_id, cx.tcx)
1796 .map(|variant_index| {
1797 let name = SmallCStr::new(&substs.as_generator().variant_name(variant_index));
1799 Some(llvm::LLVMRustDIBuilderCreateEnumerator(
1802 // FIXME: what if enumeration has i128 discriminant?
1803 variant_index.as_usize() as u64,
1811 let disr_type_key = (enum_def_id, discr);
1812 let cached_discriminant_type_metadata =
1813 debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
1814 match cached_discriminant_type_metadata {
1815 Some(discriminant_type_metadata) => discriminant_type_metadata,
1817 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
1818 let discriminant_base_type_metadata =
1819 type_metadata(cx, discr.to_ty(cx.tcx), rustc_span::DUMMY_SP);
1821 let discriminant_name = match enum_type.kind {
1822 ty::Adt(..) => SmallCStr::new(&cx.tcx.item_name(enum_def_id).as_str()),
1823 ty::Generator(..) => SmallCStr::new(&enum_name),
1827 let discriminant_type_metadata = unsafe {
1828 llvm::LLVMRustDIBuilderCreateEnumerationType(
1831 discriminant_name.as_ptr(),
1833 UNKNOWN_LINE_NUMBER,
1834 discriminant_size.bits(),
1835 discriminant_align.abi.bits() as u32,
1836 create_DIArray(DIB(cx), &enumerators_metadata),
1837 discriminant_base_type_metadata,
1843 .created_enum_disr_types
1845 .insert(disr_type_key, discriminant_type_metadata);
1847 discriminant_type_metadata
1852 let layout = cx.layout_of(enum_type);
1854 match (&layout.abi, &layout.variants) {
1856 &layout::Abi::Scalar(_),
1857 &layout::Variants::Multiple {
1858 discr_kind: layout::DiscriminantKind::Tag,
1862 ) => return FinalMetadata(discriminant_type_metadata(discr.value)),
1866 let enum_name = SmallCStr::new(&enum_name);
1867 let unique_type_id_str = SmallCStr::new(
1868 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id),
1871 if use_enum_fallback(cx) {
1872 let discriminant_type_metadata = match layout.variants {
1873 layout::Variants::Single { .. }
1874 | layout::Variants::Multiple {
1875 discr_kind: layout::DiscriminantKind::Niche { .. },
1878 layout::Variants::Multiple {
1879 discr_kind: layout::DiscriminantKind::Tag,
1882 } => Some(discriminant_type_metadata(discr.value)),
1885 let enum_metadata = unsafe {
1886 llvm::LLVMRustDIBuilderCreateUnionType(
1891 UNKNOWN_LINE_NUMBER,
1893 layout.align.abi.bits() as u32,
1897 unique_type_id_str.as_ptr(),
1901 return create_and_register_recursive_type_forward_declaration(
1907 EnumMDF(EnumMemberDescriptionFactory {
1910 discriminant_type_metadata,
1917 let discriminator_name = match &enum_type.kind {
1918 ty::Generator(..) => Some(SmallCStr::new(&"__state")),
1921 let discriminator_name = discriminator_name.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut());
1922 let discriminator_metadata = match layout.variants {
1923 // A single-variant enum has no discriminant.
1924 layout::Variants::Single { .. } => None,
1926 layout::Variants::Multiple {
1927 discr_kind: layout::DiscriminantKind::Niche { .. },
1932 // Find the integer type of the correct size.
1933 let size = discr.value.size(cx);
1934 let align = discr.value.align(cx);
1936 let discr_type = match discr.value {
1937 layout::Int(t, _) => t,
1938 layout::F32 => Integer::I32,
1939 layout::F64 => Integer::I64,
1940 layout::Pointer => cx.data_layout().ptr_sized_integer(),
1942 .to_ty(cx.tcx, false);
1944 let discr_metadata = basic_type_metadata(cx, discr_type);
1946 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1951 UNKNOWN_LINE_NUMBER,
1953 align.abi.bits() as u32,
1954 layout.fields.offset(discr_index).bits(),
1955 DIFlags::FlagArtificial,
1961 layout::Variants::Multiple {
1962 discr_kind: layout::DiscriminantKind::Tag,
1967 let discr_type = discr.value.to_ty(cx.tcx);
1968 let (size, align) = cx.size_and_align_of(discr_type);
1970 let discr_metadata = basic_type_metadata(cx, discr_type);
1972 Some(llvm::LLVMRustDIBuilderCreateMemberType(
1977 UNKNOWN_LINE_NUMBER,
1979 align.bits() as u32,
1980 layout.fields.offset(discr_index).bits(),
1981 DIFlags::FlagArtificial,
1988 let mut outer_fields = match layout.variants {
1989 layout::Variants::Single { .. } => vec![],
1990 layout::Variants::Multiple { .. } => {
1991 let tuple_mdf = TupleMemberDescriptionFactory {
1993 component_types: outer_field_tys,
1997 .create_member_descriptions(cx)
1999 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2004 let variant_part_unique_type_id_str = SmallCStr::new(
2008 .get_unique_type_id_str_of_enum_variant_part(unique_type_id),
2010 let empty_array = create_DIArray(DIB(cx), &[]);
2011 let variant_part = unsafe {
2012 llvm::LLVMRustDIBuilderCreateVariantPart(
2017 UNKNOWN_LINE_NUMBER,
2019 layout.align.abi.bits() as u32,
2021 discriminator_metadata,
2023 variant_part_unique_type_id_str.as_ptr(),
2026 outer_fields.push(Some(variant_part));
2028 // The variant part must be wrapped in a struct according to DWARF.
2029 let type_array = create_DIArray(DIB(cx), &outer_fields);
2030 let struct_wrapper = unsafe {
2031 llvm::LLVMRustDIBuilderCreateStructType(
2033 Some(containing_scope),
2036 UNKNOWN_LINE_NUMBER,
2038 layout.align.abi.bits() as u32,
2044 unique_type_id_str.as_ptr(),
2048 return create_and_register_recursive_type_forward_declaration(
2054 EnumMDF(EnumMemberDescriptionFactory {
2057 discriminant_type_metadata: None,
2064 /// Creates debug information for a composite type, that is, anything that
2065 /// results in a LLVM struct.
2067 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2068 fn composite_type_metadata(
2069 cx: &CodegenCx<'ll, 'tcx>,
2070 composite_type: Ty<'tcx>,
2071 composite_type_name: &str,
2072 composite_type_unique_id: UniqueTypeId,
2073 member_descriptions: Vec<MemberDescription<'ll>>,
2074 containing_scope: Option<&'ll DIScope>,
2076 // Ignore source location information as long as it
2077 // can't be reconstructed for non-local crates.
2078 _file_metadata: &'ll DIFile,
2079 _definition_span: Span,
2080 ) -> &'ll DICompositeType {
2081 // Create the (empty) struct metadata node ...
2082 let composite_type_metadata = create_struct_stub(
2085 composite_type_name,
2086 composite_type_unique_id,
2089 // ... and immediately create and add the member descriptions.
2090 set_members_of_composite_type(cx, composite_type, composite_type_metadata, member_descriptions);
2092 composite_type_metadata
2095 fn set_members_of_composite_type(
2096 cx: &CodegenCx<'ll, 'tcx>,
2097 composite_type: Ty<'tcx>,
2098 composite_type_metadata: &'ll DICompositeType,
2099 member_descriptions: Vec<MemberDescription<'ll>>,
2101 // In some rare cases LLVM metadata uniquing would lead to an existing type
2102 // description being used instead of a new one created in
2103 // create_struct_stub. This would cause a hard to trace assertion in
2104 // DICompositeType::SetTypeArray(). The following check makes sure that we
2105 // get a better error message if this should happen again due to some
2108 let mut composite_types_completed =
2109 debug_context(cx).composite_types_completed.borrow_mut();
2110 if !composite_types_completed.insert(&composite_type_metadata) {
2112 "debuginfo::set_members_of_composite_type() - \
2113 Already completed forward declaration re-encountered."
2118 let member_metadata: Vec<_> = member_descriptions
2120 .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2123 let type_params = compute_type_parameters(cx, composite_type);
2125 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
2126 llvm::LLVMRustDICompositeTypeReplaceArrays(
2128 composite_type_metadata,
2135 /// Computes the type parameters for a type, if any, for the given metadata.
2136 fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> Option<&'ll DIArray> {
2137 if let ty::Adt(def, substs) = ty.kind {
2138 if !substs.types().next().is_none() {
2139 let generics = cx.tcx.generics_of(def.did);
2140 let names = get_parameter_names(cx, generics);
2141 let template_params: Vec<_> = substs
2144 .filter_map(|(kind, name)| {
2145 if let GenericArgKind::Type(ty) = kind.unpack() {
2147 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2148 let actual_type_metadata =
2149 type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
2150 let name = SmallCStr::new(&name.as_str());
2152 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2156 actual_type_metadata,
2157 unknown_file_metadata(cx),
2168 return Some(create_DIArray(DIB(cx), &template_params[..]));
2171 return Some(create_DIArray(DIB(cx), &[]));
2173 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2174 let mut names = generics
2176 .map_or(vec![], |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2177 names.extend(generics.params.iter().map(|param| param.name));
2182 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2183 /// any caching, does not add any fields to the struct. This can be done later
2184 /// with `set_members_of_composite_type()`.
2185 fn create_struct_stub(
2186 cx: &CodegenCx<'ll, 'tcx>,
2187 struct_type: Ty<'tcx>,
2188 struct_type_name: &str,
2189 unique_type_id: UniqueTypeId,
2190 containing_scope: Option<&'ll DIScope>,
2191 ) -> &'ll DICompositeType {
2192 let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2194 let name = SmallCStr::new(struct_type_name);
2195 let unique_type_id = SmallCStr::new(
2196 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id),
2198 let metadata_stub = unsafe {
2199 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2200 // pointer will lead to hard to trace and debug LLVM assertions
2201 // later on in `llvm/lib/IR/Value.cpp`.
2202 let empty_array = create_DIArray(DIB(cx), &[]);
2204 llvm::LLVMRustDIBuilderCreateStructType(
2208 unknown_file_metadata(cx),
2209 UNKNOWN_LINE_NUMBER,
2211 struct_align.bits() as u32,
2217 unique_type_id.as_ptr(),
2224 fn create_union_stub(
2225 cx: &CodegenCx<'ll, 'tcx>,
2226 union_type: Ty<'tcx>,
2227 union_type_name: &str,
2228 unique_type_id: UniqueTypeId,
2229 containing_scope: &'ll DIScope,
2230 ) -> &'ll DICompositeType {
2231 let (union_size, union_align) = cx.size_and_align_of(union_type);
2233 let name = SmallCStr::new(union_type_name);
2234 let unique_type_id = SmallCStr::new(
2235 debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id),
2237 let metadata_stub = unsafe {
2238 // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2239 // pointer will lead to hard to trace and debug LLVM assertions
2240 // later on in `llvm/lib/IR/Value.cpp`.
2241 let empty_array = create_DIArray(DIB(cx), &[]);
2243 llvm::LLVMRustDIBuilderCreateUnionType(
2247 unknown_file_metadata(cx),
2248 UNKNOWN_LINE_NUMBER,
2250 union_align.bits() as u32,
2254 unique_type_id.as_ptr(),
2261 /// Creates debug information for the given global variable.
2263 /// Adds the created metadata nodes directly to the crate's IR.
2264 pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2265 if cx.dbg_cx.is_none() {
2270 let attrs = tcx.codegen_fn_attrs(def_id);
2272 if attrs.flags.contains(CodegenFnAttrFlags::NO_DEBUG) {
2276 let no_mangle = attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE);
2277 // We may want to remove the namespace scope if we're in an extern block (see
2278 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2279 let var_scope = get_namespace_for_item(cx, def_id);
2280 let span = tcx.def_span(def_id);
2282 let (file_metadata, line_number) = if !span.is_dummy() {
2283 let loc = span_start(cx, span);
2284 (file_metadata(cx, &loc.file.name, LOCAL_CRATE), loc.line as c_uint)
2286 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2289 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2290 let variable_type = Instance::mono(cx.tcx, def_id).monomorphic_ty(cx.tcx);
2291 let type_metadata = type_metadata(cx, variable_type, span);
2292 let var_name = SmallCStr::new(&tcx.item_name(def_id).as_str());
2293 let linkage_name = if no_mangle {
2296 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id));
2297 Some(SmallCStr::new(&linkage_name.name.as_str()))
2300 let global_align = cx.align_of(variable_type);
2303 llvm::LLVMRustDIBuilderCreateStaticVariable(
2307 // If null, linkage_name field is omitted,
2308 // which is what we want for no_mangle statics
2309 linkage_name.as_ref().map_or(ptr::null(), |name| name.as_ptr()),
2316 global_align.bytes() as u32,
2321 /// Creates debug information for the given vtable, which is for the
2324 /// Adds the created metadata nodes directly to the crate's IR.
2325 pub fn create_vtable_metadata(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, vtable: &'ll Value) {
2326 if cx.dbg_cx.is_none() {
2330 let type_metadata = type_metadata(cx, ty, rustc_span::DUMMY_SP);
2333 // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2334 // pointer will lead to hard to trace and debug LLVM assertions
2335 // later on in `llvm/lib/IR/Value.cpp`.
2336 let empty_array = create_DIArray(DIB(cx), &[]);
2338 let name = const_cstr!("vtable");
2340 // Create a new one each time. We don't want metadata caching
2341 // here, because each vtable will refer to a unique containing
2343 let vtable_type = llvm::LLVMRustDIBuilderCreateStructType(
2347 unknown_file_metadata(cx),
2348 UNKNOWN_LINE_NUMBER,
2350 cx.tcx.data_layout.pointer_align.abi.bits() as u32,
2351 DIFlags::FlagArtificial,
2355 Some(type_metadata),
2359 llvm::LLVMRustDIBuilderCreateStaticVariable(
2364 unknown_file_metadata(cx),
2365 UNKNOWN_LINE_NUMBER,
2375 /// Creates an "extension" of an existing `DIScope` into another file.
2376 pub fn extend_scope_to_file(
2377 cx: &CodegenCx<'ll, '_>,
2378 scope_metadata: &'ll DIScope,
2379 file: &rustc_span::SourceFile,
2380 defining_crate: CrateNum,
2381 ) -> &'ll DILexicalBlock {
2382 let file_metadata = file_metadata(cx, &file.name, defining_crate);
2383 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }