1 use self::type_map::DINodeCreationResult;
2 use self::type_map::Stub;
3 use self::type_map::UniqueTypeId;
5 use super::namespace::mangled_name_of_instance;
6 use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
8 create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB,
10 use super::CodegenUnitDebugContext;
13 use crate::common::CodegenCx;
14 use crate::debuginfo::metadata::type_map::build_type_with_children;
15 use crate::debuginfo::utils::fat_pointer_kind;
16 use crate::debuginfo::utils::FatPtrKind;
18 use crate::llvm::debuginfo::{
19 DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType, DebugEmissionKind,
21 use crate::value::Value;
24 use rustc_codegen_ssa::debuginfo::type_names::cpp_like_debuginfo;
25 use rustc_codegen_ssa::debuginfo::type_names::VTableNameKind;
26 use rustc_codegen_ssa::traits::*;
27 use rustc_fs_util::path_to_c_string;
28 use rustc_hir::def::CtorKind;
29 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
30 use rustc_middle::bug;
31 use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
32 use rustc_middle::ty::subst::GenericArgKind;
33 use rustc_middle::ty::{
34 self, AdtKind, Instance, ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt, Visibility,
36 use rustc_session::config::{self, DebugInfo, Lto};
37 use rustc_span::symbol::Symbol;
38 use rustc_span::FileName;
39 use rustc_span::{self, FileNameDisplayPreference, SourceFile};
40 use rustc_symbol_mangling::typeid_for_trait_ref;
41 use rustc_target::abi::{Align, Size};
42 use smallvec::smallvec;
44 use libc::{c_char, c_longlong, c_uint};
46 use std::fmt::{self, Write};
47 use std::hash::{Hash, Hasher};
49 use std::path::{Path, PathBuf};
52 impl PartialEq for llvm::Metadata {
53 fn eq(&self, other: &Self) -> bool {
58 impl Eq for llvm::Metadata {}
60 impl Hash for llvm::Metadata {
61 fn hash<H: Hasher>(&self, hasher: &mut H) {
62 (self as *const Self).hash(hasher);
66 impl fmt::Debug for llvm::Metadata {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 (self as *const Self).fmt(f)
73 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
74 const DW_LANG_RUST: c_uint = 0x1c;
75 #[allow(non_upper_case_globals)]
76 const DW_ATE_boolean: c_uint = 0x02;
77 #[allow(non_upper_case_globals)]
78 const DW_ATE_float: c_uint = 0x04;
79 #[allow(non_upper_case_globals)]
80 const DW_ATE_signed: c_uint = 0x05;
81 #[allow(non_upper_case_globals)]
82 const DW_ATE_unsigned: c_uint = 0x07;
83 #[allow(non_upper_case_globals)]
84 const DW_ATE_UTF: c_uint = 0x10;
86 pub(super) const UNKNOWN_LINE_NUMBER: c_uint = 0;
87 pub(super) const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
89 const NO_SCOPE_METADATA: Option<&DIScope> = None;
90 /// A function that returns an empty list of generic parameter debuginfo nodes.
91 const NO_GENERICS: for<'ll> fn(&CodegenCx<'ll, '_>) -> SmallVec<&'ll DIType> = |_| SmallVec::new();
93 // SmallVec is used quite a bit in this module, so create a shorthand.
94 // The actual number of elements is not so important.
95 pub type SmallVec<T> = smallvec::SmallVec<[T; 16]>;
100 pub(crate) use type_map::TypeMap;
102 /// Returns from the enclosing function if the type debuginfo node with the given
103 /// unique ID can be found in the type map.
104 macro_rules! return_if_di_node_created_in_meantime {
105 ($cx: expr, $unique_type_id: expr) => {
106 if let Some(di_node) = debug_context($cx).type_map.di_node_for_unique_id($unique_type_id) {
107 return DINodeCreationResult::new(di_node, true);
112 /// Extract size and alignment from a TyAndLayout.
114 fn size_and_align_of<'tcx>(ty_and_layout: TyAndLayout<'tcx>) -> (Size, Align) {
115 (ty_and_layout.size, ty_and_layout.align.abi)
118 /// Creates debuginfo for a fixed size array (e.g. `[u64; 123]`).
119 /// For slices (that is, "arrays" of unknown size) use [build_slice_type_di_node].
120 fn build_fixed_size_array_di_node<'ll, 'tcx>(
121 cx: &CodegenCx<'ll, 'tcx>,
122 unique_type_id: UniqueTypeId<'tcx>,
123 array_type: Ty<'tcx>,
124 ) -> DINodeCreationResult<'ll> {
125 let ty::Array(element_type, len) = array_type.kind() else {
126 bug!("build_fixed_size_array_di_node() called with non-ty::Array type `{:?}`", array_type)
129 let element_type_di_node = type_di_node(cx, *element_type);
131 return_if_di_node_created_in_meantime!(cx, unique_type_id);
133 let (size, align) = cx.size_and_align_of(array_type);
135 let upper_bound = len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong;
138 unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
140 let subscripts = create_DIArray(DIB(cx), &[subrange]);
141 let di_node = unsafe {
142 llvm::LLVMRustDIBuilderCreateArrayType(
146 element_type_di_node,
151 DINodeCreationResult::new(di_node, false)
154 /// Creates debuginfo for built-in pointer-like things:
158 /// - ty::Adt in the case it's Box
160 /// At some point we might want to remove the special handling of Box
161 /// and treat it the same as other smart pointers (like Rc, Arc, ...).
162 fn build_pointer_or_reference_di_node<'ll, 'tcx>(
163 cx: &CodegenCx<'ll, 'tcx>,
165 pointee_type: Ty<'tcx>,
166 unique_type_id: UniqueTypeId<'tcx>,
167 ) -> DINodeCreationResult<'ll> {
168 // The debuginfo generated by this function is only valid if `ptr_type` is really just
169 // a (fat) pointer. Make sure it is not called for e.g. `Box<T, NonZSTAllocator>`.
171 cx.size_and_align_of(ptr_type),
172 cx.size_and_align_of(cx.tcx.mk_mut_ptr(pointee_type))
175 let pointee_type_di_node = type_di_node(cx, pointee_type);
177 return_if_di_node_created_in_meantime!(cx, unique_type_id);
179 let (thin_pointer_size, thin_pointer_align) =
180 cx.size_and_align_of(cx.tcx.mk_imm_ptr(cx.tcx.types.unit));
181 let ptr_type_debuginfo_name = compute_debuginfo_type_name(cx.tcx, ptr_type, true);
183 match fat_pointer_kind(cx, pointee_type) {
185 // This is a thin pointer. Create a regular pointer type and give it the correct name.
187 (thin_pointer_size, thin_pointer_align),
188 cx.size_and_align_of(ptr_type),
189 "ptr_type={}, pointee_type={}",
194 let di_node = unsafe {
195 llvm::LLVMRustDIBuilderCreatePointerType(
197 pointee_type_di_node,
198 thin_pointer_size.bits(),
199 thin_pointer_align.bits() as u32,
200 0, // Ignore DWARF address space.
201 ptr_type_debuginfo_name.as_ptr().cast(),
202 ptr_type_debuginfo_name.len(),
206 DINodeCreationResult { di_node, already_stored_in_typemap: false }
208 Some(fat_pointer_kind) => {
209 type_map::build_type_with_children(
215 &ptr_type_debuginfo_name,
216 cx.size_and_align_of(ptr_type),
221 // FIXME: If this fat pointer is a `Box` then we don't want to use its
222 // type layout and instead use the layout of the raw pointer inside
224 // The proper way to handle this is to not treat Box as a pointer
225 // at all and instead emit regular struct debuginfo for it. We just
226 // need to make sure that we don't break existing debuginfo consumers
227 // by doing that (at least not without a warning period).
229 if ptr_type.is_box() { cx.tcx.mk_mut_ptr(pointee_type) } else { ptr_type };
231 let layout = cx.layout_of(layout_type);
232 let addr_field = layout.field(cx, abi::FAT_PTR_ADDR);
233 let extra_field = layout.field(cx, abi::FAT_PTR_EXTRA);
235 let (addr_field_name, extra_field_name) = match fat_pointer_kind {
236 FatPtrKind::Dyn => ("pointer", "vtable"),
237 FatPtrKind::Slice => ("data_ptr", "length"),
240 debug_assert_eq!(abi::FAT_PTR_ADDR, 0);
241 debug_assert_eq!(abi::FAT_PTR_EXTRA, 1);
243 // The data pointer type is a regular, thin pointer, regardless of whether this
244 // is a slice or a trait object.
245 let data_ptr_type_di_node = unsafe {
246 llvm::LLVMRustDIBuilderCreatePointerType(
248 pointee_type_di_node,
249 addr_field.size.bits(),
250 addr_field.align.abi.bits() as u32,
251 0, // Ignore DWARF address space.
262 (addr_field.size, addr_field.align.abi),
263 layout.fields.offset(abi::FAT_PTR_ADDR),
265 data_ptr_type_di_node,
271 (extra_field.size, extra_field.align.abi),
272 layout.fields.offset(abi::FAT_PTR_EXTRA),
274 type_di_node(cx, extra_field.ty),
284 fn build_subroutine_type_di_node<'ll, 'tcx>(
285 cx: &CodegenCx<'ll, 'tcx>,
286 unique_type_id: UniqueTypeId<'tcx>,
287 ) -> DINodeCreationResult<'ll> {
288 // It's possible to create a self-referential
289 // type in Rust by using 'impl trait':
291 // fn foo() -> impl Copy { foo }
293 // Unfortunately LLVM's API does not allow us to create recursive subroutine types.
294 // In order to work around that restriction we place a marker type in the type map,
295 // before creating the actual type. If the actual type is recursive, it will hit the
296 // marker type. So we end up with a type that looks like
298 // fn foo() -> <recursive_type>
300 // Once that is created, we replace the marker in the typemap with the actual type.
303 .unique_id_to_di_node
305 .insert(unique_type_id, recursion_marker_type_di_node(cx));
307 let fn_ty = unique_type_id.expect_ty();
310 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), fn_ty.fn_sig(cx.tcx));
312 let signature_di_nodes: SmallVec<_> = iter::once(
314 match signature.output().kind() {
315 ty::Tuple(tys) if tys.is_empty() => {
316 // this is a "void" function
319 _ => Some(type_di_node(cx, signature.output())),
324 signature.inputs().iter().map(|&argument_type| Some(type_di_node(cx, argument_type))),
328 debug_context(cx).type_map.unique_id_to_di_node.borrow_mut().remove(&unique_type_id);
330 let fn_di_node = unsafe {
331 llvm::LLVMRustDIBuilderCreateSubroutineType(
333 create_DIArray(DIB(cx), &signature_di_nodes[..]),
337 // This is actually a function pointer, so wrap it in pointer DI.
338 let name = compute_debuginfo_type_name(cx.tcx, fn_ty, false);
339 let di_node = unsafe {
340 llvm::LLVMRustDIBuilderCreatePointerType(
343 cx.tcx.data_layout.pointer_size.bits(),
344 cx.tcx.data_layout.pointer_align.abi.bits() as u32,
345 0, // Ignore DWARF address space.
346 name.as_ptr().cast(),
351 DINodeCreationResult::new(di_node, false)
354 /// Create debuginfo for `dyn SomeTrait` types. Currently these are empty structs
355 /// we with the correct type name (e.g. "dyn SomeTrait<Foo, Item=u32> + Sync").
356 fn build_dyn_type_di_node<'ll, 'tcx>(
357 cx: &CodegenCx<'ll, 'tcx>,
359 unique_type_id: UniqueTypeId<'tcx>,
360 ) -> DINodeCreationResult<'ll> {
361 if let ty::Dynamic(..) = dyn_type.kind() {
362 let type_name = compute_debuginfo_type_name(cx.tcx, dyn_type, true);
363 type_map::build_type_with_children(
370 cx.size_and_align_of(dyn_type),
379 "Only ty::Dynamic is valid for build_dyn_type_di_node(). Found {:?} instead.",
385 /// Create debuginfo for `[T]` and `str`. These are unsized.
387 /// NOTE: We currently emit just emit the debuginfo for the element type here
388 /// (i.e. `T` for slices and `u8` for `str`), so that we end up with
389 /// `*const T` for the `data_ptr` field of the corresponding fat-pointer
390 /// debuginfo of `&[T]`.
392 /// It would be preferable and more accurate if we emitted a DIArray of T
393 /// without an upper bound instead. That is, LLVM already supports emitting
394 /// debuginfo of arrays of unknown size. But GDB currently seems to end up
395 /// in an infinite loop when confronted with such a type.
397 /// As a side effect of the current encoding every instance of a type like
398 /// `struct Foo { unsized_field: [u8] }` will look like
399 /// `struct Foo { unsized_field: u8 }` in debuginfo. If the length of the
400 /// slice is zero, then accessing `unsized_field` in the debugger would
401 /// result in an out-of-bounds access.
402 fn build_slice_type_di_node<'ll, 'tcx>(
403 cx: &CodegenCx<'ll, 'tcx>,
404 slice_type: Ty<'tcx>,
405 unique_type_id: UniqueTypeId<'tcx>,
406 ) -> DINodeCreationResult<'ll> {
407 let element_type = match slice_type.kind() {
408 ty::Slice(element_type) => *element_type,
409 ty::Str => cx.tcx.types.u8,
412 "Only ty::Slice is valid for build_slice_type_di_node(). Found {:?} instead.",
418 let element_type_di_node = type_di_node(cx, element_type);
419 return_if_di_node_created_in_meantime!(cx, unique_type_id);
420 DINodeCreationResult { di_node: element_type_di_node, already_stored_in_typemap: false }
423 /// Get the debuginfo node for the given type.
425 /// This function will look up the debuginfo node in the TypeMap. If it can't find it, it
426 /// will create the node by dispatching to the corresponding `build_*_di_node()` function.
427 pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
428 let unique_type_id = UniqueTypeId::for_ty(cx.tcx, t);
430 if let Some(existing_di_node) = debug_context(cx).type_map.di_node_for_unique_id(unique_type_id)
432 return existing_di_node;
435 debug!("type_di_node: {:?}", t);
437 let DINodeCreationResult { di_node, already_stored_in_typemap } = match *t.kind() {
438 ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
439 build_basic_type_di_node(cx, t)
441 ty::Tuple(elements) if elements.is_empty() => build_basic_type_di_node(cx, t),
442 ty::Array(..) => build_fixed_size_array_di_node(cx, unique_type_id, t),
443 ty::Slice(_) | ty::Str => build_slice_type_di_node(cx, t, unique_type_id),
444 ty::Dynamic(..) => build_dyn_type_di_node(cx, t, unique_type_id),
445 ty::Foreign(..) => build_foreign_type_di_node(cx, t, unique_type_id),
446 ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => {
447 build_pointer_or_reference_di_node(cx, t, pointee_type, unique_type_id)
449 // Box<T, A> may have a non-ZST allocator A. In that case, we
450 // cannot treat Box<T, A> as just an owned alias of `*mut T`.
451 ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => {
452 build_pointer_or_reference_di_node(cx, t, t.boxed_ty(), unique_type_id)
454 ty::FnDef(..) | ty::FnPtr(_) => build_subroutine_type_di_node(cx, unique_type_id),
455 ty::Closure(..) => build_closure_env_di_node(cx, unique_type_id),
456 ty::Generator(..) => enums::build_generator_di_node(cx, unique_type_id),
457 ty::Adt(def, ..) => match def.adt_kind() {
458 AdtKind::Struct => build_struct_type_di_node(cx, unique_type_id),
459 AdtKind::Union => build_union_type_di_node(cx, unique_type_id),
460 AdtKind::Enum => enums::build_enum_type_di_node(cx, unique_type_id),
462 ty::Tuple(_) => build_tuple_type_di_node(cx, unique_type_id),
463 // Type parameters from polymorphized functions.
464 ty::Param(_) => build_param_type_di_node(cx, t),
465 _ => bug!("debuginfo: unexpected type in type_di_node(): {:?}", t),
469 if already_stored_in_typemap {
470 // Make sure that we really do have a `TypeMap` entry for the unique type ID.
471 let di_node_for_uid =
472 match debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
473 Some(di_node) => di_node,
476 "expected type debuginfo node for unique \
477 type ID '{:?}' to already be in \
478 the `debuginfo::TypeMap` but it \
485 debug_assert_eq!(di_node_for_uid as *const _, di_node as *const _);
487 debug_context(cx).type_map.insert(unique_type_id, di_node);
494 // FIXME(mw): Cache this via a regular UniqueTypeId instead of an extra field in the debug context.
495 fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType {
496 *debug_context(cx).recursion_marker_type.get_or_init(move || {
498 // The choice of type here is pretty arbitrary -
499 // anything reading the debuginfo for a recursive
500 // type is going to see *something* weird - the only
501 // question is what exactly it will see.
503 // FIXME: the name `<recur_type>` does not fit the naming scheme
506 // FIXME: it might make sense to use an actual pointer type here
507 // so that debuggers can show the address.
508 let name = "<recur_type>";
509 llvm::LLVMRustDIBuilderCreateBasicType(
511 name.as_ptr().cast(),
513 cx.tcx.data_layout.pointer_size.bits(),
520 fn hex_encode(data: &[u8]) -> String {
521 let mut hex_string = String::with_capacity(data.len() * 2);
522 for byte in data.iter() {
523 write!(&mut hex_string, "{:02x}", byte).unwrap();
528 pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
529 let cache_key = Some((source_file.name_hash, source_file.src_hash));
530 return debug_context(cx)
534 .or_insert_with(|| alloc_new_file_metadata(cx, source_file));
536 #[instrument(skip(cx, source_file), level = "debug")]
537 fn alloc_new_file_metadata<'ll>(
538 cx: &CodegenCx<'ll, '_>,
539 source_file: &SourceFile,
541 debug!(?source_file.name);
543 let (directory, file_name) = match &source_file.name {
544 FileName::Real(filename) => {
545 let working_directory = &cx.sess().opts.working_dir;
546 debug!(?working_directory);
552 .to_embeddable_absolute_path(filename.clone(), working_directory);
554 // Construct the absolute path of the file
555 let abs_path = filename.remapped_path_if_available();
558 if let Ok(rel_path) =
559 abs_path.strip_prefix(working_directory.remapped_path_if_available())
561 // If the compiler's working directory (which also is the DW_AT_comp_dir of
562 // the compilation unit) is a prefix of the path we are about to emit, then
563 // only emit the part relative to the working directory.
564 // Because of path remapping we sometimes see strange things here: `abs_path`
565 // might actually look like a relative path
566 // (e.g. `<crate-name-and-version>/src/lib.rs`), so if we emit it without
567 // taking the working directory into account, downstream tooling will
568 // interpret it as `<working-directory>/<crate-name-and-version>/src/lib.rs`,
569 // which makes no sense. Usually in such cases the working directory will also
570 // be remapped to `<crate-name-and-version>` or some other prefix of the path
571 // we are remapping, so we end up with
572 // `<crate-name-and-version>/<crate-name-and-version>/src/lib.rs`.
573 // By moving the working directory portion into the `directory` part of the
574 // DIFile, we allow LLVM to emit just the relative path for DWARF, while
575 // still emitting the correct absolute path for CodeView.
577 working_directory.to_string_lossy(FileNameDisplayPreference::Remapped),
578 rel_path.to_string_lossy().into_owned(),
581 ("".into(), abs_path.to_string_lossy().into_owned())
584 other => ("".into(), other.prefer_remapped().to_string_lossy().into_owned()),
587 let hash_kind = match source_file.src_hash.kind {
588 rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
589 rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
590 rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
592 let hash_value = hex_encode(source_file.src_hash.hash_bytes());
595 llvm::LLVMRustDIBuilderCreateFile(
597 file_name.as_ptr().cast(),
599 directory.as_ptr().cast(),
602 hash_value.as_ptr().cast(),
609 pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
610 debug_context(cx).created_files.borrow_mut().entry(None).or_insert_with(|| unsafe {
611 let file_name = "<unknown>";
615 llvm::LLVMRustDIBuilderCreateFile(
617 file_name.as_ptr().cast(),
619 directory.as_ptr().cast(),
621 llvm::ChecksumKind::None,
622 hash_value.as_ptr().cast(),
628 trait MsvcBasicName {
629 fn msvc_basic_name(self) -> &'static str;
632 impl MsvcBasicName for ty::IntTy {
633 fn msvc_basic_name(self) -> &'static str {
635 ty::IntTy::Isize => "ptrdiff_t",
636 ty::IntTy::I8 => "__int8",
637 ty::IntTy::I16 => "__int16",
638 ty::IntTy::I32 => "__int32",
639 ty::IntTy::I64 => "__int64",
640 ty::IntTy::I128 => "__int128",
645 impl MsvcBasicName for ty::UintTy {
646 fn msvc_basic_name(self) -> &'static str {
648 ty::UintTy::Usize => "size_t",
649 ty::UintTy::U8 => "unsigned __int8",
650 ty::UintTy::U16 => "unsigned __int16",
651 ty::UintTy::U32 => "unsigned __int32",
652 ty::UintTy::U64 => "unsigned __int64",
653 ty::UintTy::U128 => "unsigned __int128",
658 impl MsvcBasicName for ty::FloatTy {
659 fn msvc_basic_name(self) -> &'static str {
661 ty::FloatTy::F32 => "float",
662 ty::FloatTy::F64 => "double",
667 fn build_basic_type_di_node<'ll, 'tcx>(
668 cx: &CodegenCx<'ll, 'tcx>,
670 ) -> DINodeCreationResult<'ll> {
671 debug!("build_basic_type_di_node: {:?}", t);
673 // When targeting MSVC, emit MSVC style type names for compatibility with
674 // .natvis visualizers (and perhaps other existing native debuggers?)
675 let cpp_like_debuginfo = cpp_like_debuginfo(cx.tcx);
677 let (name, encoding) = match t.kind() {
678 ty::Never => ("!", DW_ATE_unsigned),
679 ty::Tuple(elements) if elements.is_empty() => {
680 if cpp_like_debuginfo {
681 return build_tuple_type_di_node(cx, UniqueTypeId::for_ty(cx.tcx, t));
683 ("()", DW_ATE_unsigned)
686 ty::Bool => ("bool", DW_ATE_boolean),
687 ty::Char => ("char", DW_ATE_UTF),
688 ty::Int(int_ty) if cpp_like_debuginfo => (int_ty.msvc_basic_name(), DW_ATE_signed),
689 ty::Uint(uint_ty) if cpp_like_debuginfo => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
690 ty::Float(float_ty) if cpp_like_debuginfo => (float_ty.msvc_basic_name(), DW_ATE_float),
691 ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
692 ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
693 ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
694 _ => bug!("debuginfo::build_basic_type_di_node - `t` is invalid type"),
697 let ty_di_node = unsafe {
698 llvm::LLVMRustDIBuilderCreateBasicType(
700 name.as_ptr().cast(),
702 cx.size_of(t).bits(),
707 if !cpp_like_debuginfo {
708 return DINodeCreationResult::new(ty_di_node, false);
711 let typedef_name = match t.kind() {
712 ty::Int(int_ty) => int_ty.name_str(),
713 ty::Uint(uint_ty) => uint_ty.name_str(),
714 ty::Float(float_ty) => float_ty.name_str(),
715 _ => return DINodeCreationResult::new(ty_di_node, false),
718 let typedef_di_node = unsafe {
719 llvm::LLVMRustDIBuilderCreateTypedef(
722 typedef_name.as_ptr().cast(),
724 unknown_file_metadata(cx),
730 DINodeCreationResult::new(typedef_di_node, false)
733 fn build_foreign_type_di_node<'ll, 'tcx>(
734 cx: &CodegenCx<'ll, 'tcx>,
736 unique_type_id: UniqueTypeId<'tcx>,
737 ) -> DINodeCreationResult<'ll> {
738 debug!("build_foreign_type_di_node: {:?}", t);
740 let &ty::Foreign(def_id) = unique_type_id.expect_ty().kind() else {
741 bug!("build_foreign_type_di_node() called with unexpected type: {:?}", unique_type_id.expect_ty());
744 build_type_with_children(
750 &compute_debuginfo_type_name(cx.tcx, t, false),
751 cx.size_and_align_of(t),
752 Some(get_namespace_for_item(cx, def_id)),
760 fn build_param_type_di_node<'ll, 'tcx>(
761 cx: &CodegenCx<'ll, 'tcx>,
763 ) -> DINodeCreationResult<'ll> {
764 debug!("build_param_type_di_node: {:?}", t);
765 let name = format!("{:?}", t);
766 DINodeCreationResult {
768 llvm::LLVMRustDIBuilderCreateBasicType(
770 name.as_ptr().cast(),
776 already_stored_in_typemap: false,
780 pub fn build_compile_unit_di_node<'ll, 'tcx>(
782 codegen_unit_name: &str,
783 debug_context: &CodegenUnitDebugContext<'ll, 'tcx>,
784 ) -> &'ll DIDescriptor {
785 let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
786 Some(ref path) => path.clone(),
787 None => PathBuf::from(tcx.crate_name(LOCAL_CRATE).as_str()),
790 // To avoid breaking split DWARF, we need to ensure that each codegen unit
791 // has a unique `DW_AT_name`. This is because there's a remote chance that
792 // different codegen units for the same module will have entirely
793 // identical DWARF entries for the purpose of the DWO ID, which would
794 // violate Appendix F ("Split Dwarf Object Files") of the DWARF 5
795 // specification. LLVM uses the algorithm specified in section 7.32 "Type
796 // Signature Computation" to compute the DWO ID, which does not include
797 // any fields that would distinguish compilation units. So we must embed
798 // the codegen unit name into the `DW_AT_name`. (Issue #88521.)
800 // Additionally, the OSX linker has an idiosyncrasy where it will ignore
801 // some debuginfo if multiple object files with the same `DW_AT_name` are
804 // As a workaround for these two issues, we generate unique names for each
805 // object file. Those do not correspond to an actual source file but that
807 name_in_debuginfo.push("@");
808 name_in_debuginfo.push(codegen_unit_name);
810 debug!("build_compile_unit_di_node: {:?}", name_in_debuginfo);
812 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
813 // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
814 let producer = format!("clang LLVM ({})", rustc_producer);
816 let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
817 let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
819 let output_filenames = tcx.output_filenames(());
820 let split_name = if tcx.sess.target_can_use_split_dwarf() {
823 tcx.sess.split_debuginfo(),
824 tcx.sess.opts.unstable_opts.split_dwarf_kind,
825 Some(codegen_unit_name),
827 // We get a path relative to the working directory from split_dwarf_path
828 .map(|f| tcx.sess.source_map().path_mapping().map_prefix(f).0)
832 .unwrap_or_default();
833 let split_name = split_name.to_str().unwrap();
837 // This should actually be
839 // let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
841 // That is, we should set LLVM's emission kind to `LineTablesOnly` if
842 // we are compiling with "limited" debuginfo. However, some of the
843 // existing tools relied on slightly more debuginfo being generated than
844 // would be the case with `LineTablesOnly`, and we did not want to break
845 // these tools in a "drive-by fix", without a good idea or plan about
846 // what limited debuginfo should exactly look like. So for now we keep
847 // the emission kind as `FullDebug`.
849 // See https://github.com/rust-lang/rust/issues/60020 for details.
850 let kind = DebugEmissionKind::FullDebug;
851 assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
854 let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
855 debug_context.builder,
856 name_in_debuginfo.as_ptr().cast(),
857 name_in_debuginfo.len(),
858 work_dir.as_ptr().cast(),
860 llvm::ChecksumKind::None,
865 let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
866 debug_context.builder,
869 producer.as_ptr().cast(),
871 tcx.sess.opts.optimize != config::OptLevel::No,
872 flags.as_ptr().cast(),
874 // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
875 // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
877 split_name.as_ptr().cast(),
881 tcx.sess.opts.unstable_opts.split_dwarf_inlining,
884 if tcx.sess.opts.unstable_opts.profile {
885 let cu_desc_metadata =
886 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
887 let default_gcda_path = &output_filenames.with_extension("gcda");
889 tcx.sess.opts.unstable_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
892 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
893 path_to_mdstring(debug_context.llcontext, gcda_path),
896 let gcov_metadata = llvm::LLVMMDNodeInContext(
897 debug_context.llcontext,
898 gcov_cu_info.as_ptr(),
899 gcov_cu_info.len() as c_uint,
902 let llvm_gcov_ident = cstr!("llvm.gcov");
903 llvm::LLVMAddNamedMetadataOperand(
905 llvm_gcov_ident.as_ptr(),
910 // Insert `llvm.ident` metadata on the wasm targets since that will
911 // get hooked up to the "producer" sections `processed-by` information.
912 if tcx.sess.target.is_like_wasm {
913 let name_metadata = llvm::LLVMMDStringInContext(
914 debug_context.llcontext,
915 rustc_producer.as_ptr().cast(),
916 rustc_producer.as_bytes().len() as c_uint,
918 llvm::LLVMAddNamedMetadataOperand(
920 cstr!("llvm.ident").as_ptr(),
921 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
925 return unit_metadata;
928 fn path_to_mdstring<'ll>(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
929 let path_str = path_to_c_string(path);
931 llvm::LLVMMDStringInContext(
934 path_str.as_bytes().len() as c_uint,
940 /// Creates a `DW_TAG_member` entry inside the DIE represented by the given `type_di_node`.
941 fn build_field_di_node<'ll, 'tcx>(
942 cx: &CodegenCx<'ll, 'tcx>,
945 size_and_align: (Size, Align),
948 type_di_node: &'ll DIType,
951 llvm::LLVMRustDIBuilderCreateMemberType(
954 name.as_ptr().cast(),
956 unknown_file_metadata(cx),
958 size_and_align.0.bits(),
959 size_and_align.1.bits() as u32,
967 /// Creates the debuginfo node for a Rust struct type. Maybe be a regular struct or a tuple-struct.
968 fn build_struct_type_di_node<'ll, 'tcx>(
969 cx: &CodegenCx<'ll, 'tcx>,
970 unique_type_id: UniqueTypeId<'tcx>,
971 ) -> DINodeCreationResult<'ll> {
972 let struct_type = unique_type_id.expect_ty();
973 let ty::Adt(adt_def, _) = struct_type.kind() else {
974 bug!("build_struct_type_di_node() called with non-struct-type: {:?}", struct_type);
976 debug_assert!(adt_def.is_struct());
977 let containing_scope = get_namespace_for_item(cx, adt_def.did());
978 let struct_type_and_layout = cx.layout_of(struct_type);
979 let variant_def = adt_def.non_enum_variant();
981 type_map::build_type_with_children(
987 &compute_debuginfo_type_name(cx.tcx, struct_type, false),
988 size_and_align_of(struct_type_and_layout),
989 Some(containing_scope),
999 let field_name = if variant_def.ctor_kind() == Some(CtorKind::Fn) {
1000 // This is a tuple struct
1003 // This is struct with named fields
1004 Cow::Borrowed(f.name.as_str())
1006 let field_layout = struct_type_and_layout.field(cx, i);
1007 build_field_di_node(
1011 (field_layout.size, field_layout.align.abi),
1012 struct_type_and_layout.fields.offset(i),
1014 type_di_node(cx, field_layout.ty),
1019 |cx| build_generic_type_param_di_nodes(cx, struct_type),
1023 //=-----------------------------------------------------------------------------
1025 //=-----------------------------------------------------------------------------
1027 /// Builds the DW_TAG_member debuginfo nodes for the upvars of a closure or generator.
1028 /// For a generator, this will handle upvars shared by all states.
1029 fn build_upvar_field_di_nodes<'ll, 'tcx>(
1030 cx: &CodegenCx<'ll, 'tcx>,
1031 closure_or_generator_ty: Ty<'tcx>,
1032 closure_or_generator_di_node: &'ll DIType,
1033 ) -> SmallVec<&'ll DIType> {
1034 let (&def_id, up_var_tys) = match closure_or_generator_ty.kind() {
1035 ty::Generator(def_id, substs, _) => {
1036 let upvar_tys: SmallVec<_> = substs.as_generator().prefix_tys().collect();
1039 ty::Closure(def_id, substs) => {
1040 let upvar_tys: SmallVec<_> = substs.as_closure().upvar_tys().collect();
1045 "build_upvar_field_di_nodes() called with non-closure-or-generator-type: {:?}",
1046 closure_or_generator_ty
1054 .all(|&t| t == cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
1057 let capture_names = cx.tcx.closure_saved_names_of_captured_variables(def_id);
1058 let layout = cx.layout_of(closure_or_generator_ty);
1062 .zip(capture_names.iter())
1064 .map(|(index, (up_var_ty, capture_name))| {
1065 build_field_di_node(
1067 closure_or_generator_di_node,
1069 cx.size_and_align_of(up_var_ty),
1070 layout.fields.offset(index),
1072 type_di_node(cx, up_var_ty),
1078 /// Builds the DW_TAG_structure_type debuginfo node for a Rust tuple type.
1079 fn build_tuple_type_di_node<'ll, 'tcx>(
1080 cx: &CodegenCx<'ll, 'tcx>,
1081 unique_type_id: UniqueTypeId<'tcx>,
1082 ) -> DINodeCreationResult<'ll> {
1083 let tuple_type = unique_type_id.expect_ty();
1084 let &ty::Tuple(component_types) = tuple_type.kind() else {
1085 bug!("build_tuple_type_di_node() called with non-tuple-type: {:?}", tuple_type)
1088 let tuple_type_and_layout = cx.layout_of(tuple_type);
1089 let type_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1091 type_map::build_type_with_children(
1098 size_and_align_of(tuple_type_and_layout),
1103 |cx, tuple_di_node| {
1107 .map(|(index, component_type)| {
1108 build_field_di_node(
1111 &tuple_field_name(index),
1112 cx.size_and_align_of(component_type),
1113 tuple_type_and_layout.fields.offset(index),
1115 type_di_node(cx, component_type),
1124 /// Builds the debuginfo node for a closure environment.
1125 fn build_closure_env_di_node<'ll, 'tcx>(
1126 cx: &CodegenCx<'ll, 'tcx>,
1127 unique_type_id: UniqueTypeId<'tcx>,
1128 ) -> DINodeCreationResult<'ll> {
1129 let closure_env_type = unique_type_id.expect_ty();
1130 let &ty::Closure(def_id, _substs) = closure_env_type.kind() else {
1131 bug!("build_closure_env_di_node() called with non-closure-type: {:?}", closure_env_type)
1133 let containing_scope = get_namespace_for_item(cx, def_id);
1134 let type_name = compute_debuginfo_type_name(cx.tcx, closure_env_type, false);
1136 type_map::build_type_with_children(
1143 cx.size_and_align_of(closure_env_type),
1144 Some(containing_scope),
1148 |cx, owner| build_upvar_field_di_nodes(cx, closure_env_type, owner),
1153 /// Build the debuginfo node for a Rust `union` type.
1154 fn build_union_type_di_node<'ll, 'tcx>(
1155 cx: &CodegenCx<'ll, 'tcx>,
1156 unique_type_id: UniqueTypeId<'tcx>,
1157 ) -> DINodeCreationResult<'ll> {
1158 let union_type = unique_type_id.expect_ty();
1159 let (union_def_id, variant_def) = match union_type.kind() {
1160 ty::Adt(def, _) => (def.did(), def.non_enum_variant()),
1161 _ => bug!("build_union_type_di_node on a non-ADT"),
1163 let containing_scope = get_namespace_for_item(cx, union_def_id);
1164 let union_ty_and_layout = cx.layout_of(union_type);
1165 let type_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1167 type_map::build_type_with_children(
1174 size_and_align_of(union_ty_and_layout),
1175 Some(containing_scope),
1185 let field_layout = union_ty_and_layout.field(cx, i);
1186 build_field_di_node(
1190 size_and_align_of(field_layout),
1193 type_di_node(cx, field_layout.ty),
1199 |cx| build_generic_type_param_di_nodes(cx, union_type),
1203 /// Computes the type parameters for a type, if any, for the given metadata.
1204 fn build_generic_type_param_di_nodes<'ll, 'tcx>(
1205 cx: &CodegenCx<'ll, 'tcx>,
1207 ) -> SmallVec<&'ll DIType> {
1208 if let ty::Adt(def, substs) = *ty.kind() {
1209 if substs.types().next().is_some() {
1210 let generics = cx.tcx.generics_of(def.did());
1211 let names = get_parameter_names(cx, generics);
1212 let template_params: SmallVec<_> = iter::zip(substs, names)
1213 .filter_map(|(kind, name)| {
1214 if let GenericArgKind::Type(ty) = kind.unpack() {
1216 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
1217 let actual_type_di_node = type_di_node(cx, actual_type);
1218 let name = name.as_str();
1220 llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
1223 name.as_ptr().cast(),
1225 actual_type_di_node,
1234 return template_params;
1240 fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
1241 let mut names = generics
1243 .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
1244 names.extend(generics.params.iter().map(|param| param.name));
1249 /// Creates debug information for the given global variable.
1251 /// Adds the created debuginfo nodes directly to the crate's IR.
1252 pub fn build_global_var_di_node<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
1253 if cx.dbg_cx.is_none() {
1257 // Only create type information if full debuginfo is enabled
1258 if cx.sess().opts.debuginfo != DebugInfo::Full {
1264 // We may want to remove the namespace scope if we're in an extern block (see
1265 // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
1266 let var_scope = get_namespace_for_item(cx, def_id);
1267 let span = tcx.def_span(def_id);
1269 let (file_metadata, line_number) = if !span.is_dummy() {
1270 let loc = cx.lookup_debug_loc(span.lo());
1271 (file_metadata(cx, &loc.file), loc.line)
1273 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1276 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
1277 let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
1278 let type_di_node = type_di_node(cx, variable_type);
1279 let var_name = tcx.item_name(def_id);
1280 let var_name = var_name.as_str();
1281 let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
1282 // When empty, linkage_name field is omitted,
1283 // which is what we want for no_mangle statics
1284 let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
1286 let global_align = cx.align_of(variable_type);
1289 llvm::LLVMRustDIBuilderCreateStaticVariable(
1292 var_name.as_ptr().cast(),
1294 linkage_name.as_ptr().cast(),
1302 global_align.bits() as u32,
1307 /// Generates LLVM debuginfo for a vtable.
1309 /// The vtable type looks like a struct with a field for each function pointer and super-trait
1310 /// pointer it contains (plus the `size` and `align` fields).
1312 /// Except for `size`, `align`, and `drop_in_place`, the field names don't try to mirror
1313 /// the name of the method they implement. This can be implemented in the future once there
1314 /// is a proper disambiguation scheme for dealing with methods from different traits that have
1316 fn build_vtable_type_di_node<'ll, 'tcx>(
1317 cx: &CodegenCx<'ll, 'tcx>,
1319 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
1323 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
1324 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
1325 let trait_ref = tcx.erase_regions(trait_ref);
1327 tcx.vtable_entries(trait_ref)
1329 TyCtxt::COMMON_VTABLE_ENTRIES
1332 // All function pointers are described as opaque pointers. This could be improved in the future
1333 // by describing them as actual function pointers.
1334 let void_pointer_ty = tcx.mk_imm_ptr(tcx.types.unit);
1335 let void_pointer_type_di_node = type_di_node(cx, void_pointer_ty);
1336 let usize_di_node = type_di_node(cx, tcx.types.usize);
1337 let (pointer_size, pointer_align) = cx.size_and_align_of(void_pointer_ty);
1338 // If `usize` is not pointer-sized and -aligned then the size and alignment computations
1339 // for the vtable as a whole would be wrong. Let's make sure this holds even on weird
1341 assert_eq!(cx.size_and_align_of(tcx.types.usize), (pointer_size, pointer_align));
1343 let vtable_type_name =
1344 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::Type);
1345 let unique_type_id = UniqueTypeId::for_vtable_ty(tcx, ty, poly_trait_ref);
1346 let size = pointer_size * vtable_entries.len() as u64;
1348 // This gets mapped to a DW_AT_containing_type attribute which allows GDB to correlate
1349 // the vtable to the type it is for.
1350 let vtable_holder = type_di_node(cx, ty);
1352 build_type_with_children(
1356 Stub::VTableTy { vtable_holder },
1359 (size, pointer_align),
1361 DIFlags::FlagArtificial,
1363 |cx, vtable_type_di_node| {
1367 .filter_map(|(index, vtable_entry)| {
1368 let (field_name, field_type_di_node) = match vtable_entry {
1369 ty::VtblEntry::MetadataDropInPlace => {
1370 ("drop_in_place".to_string(), void_pointer_type_di_node)
1372 ty::VtblEntry::Method(_) => {
1373 // Note: This code does not try to give a proper name to each method
1374 // because their might be multiple methods with the same name
1375 // (coming from different traits).
1376 (format!("__method{}", index), void_pointer_type_di_node)
1378 ty::VtblEntry::TraitVPtr(_) => {
1379 (format!("__super_trait_ptr{}", index), void_pointer_type_di_node)
1381 ty::VtblEntry::MetadataAlign => ("align".to_string(), usize_di_node),
1382 ty::VtblEntry::MetadataSize => ("size".to_string(), usize_di_node),
1383 ty::VtblEntry::Vacant => return None,
1386 let field_offset = pointer_size * index as u64;
1388 Some(build_field_di_node(
1390 vtable_type_di_node,
1392 (pointer_size, pointer_align),
1405 fn vcall_visibility_metadata<'ll, 'tcx>(
1406 cx: &CodegenCx<'ll, 'tcx>,
1408 trait_ref: Option<PolyExistentialTraitRef<'tcx>>,
1411 enum VCallVisibility {
1414 TranslationUnit = 2,
1417 let Some(trait_ref) = trait_ref else { return };
1419 let trait_ref_self = trait_ref.with_self_ty(cx.tcx, ty);
1420 let trait_ref_self = cx.tcx.erase_regions(trait_ref_self);
1421 let trait_def_id = trait_ref_self.def_id();
1422 let trait_vis = cx.tcx.visibility(trait_def_id);
1424 let cgus = cx.sess().codegen_units();
1425 let single_cgu = cgus == 1;
1427 let lto = cx.sess().lto();
1429 // Since LLVM requires full LTO for the virtual function elimination optimization to apply,
1430 // only the `Lto::Fat` cases are relevant currently.
1431 let vcall_visibility = match (lto, trait_vis, single_cgu) {
1432 // If there is not LTO and the visibility in public, we have to assume that the vtable can
1433 // be seen from anywhere. With multiple CGUs, the vtable is quasi-public.
1434 (Lto::No | Lto::ThinLocal, Visibility::Public, _)
1435 | (Lto::No, Visibility::Restricted(_), false) => VCallVisibility::Public,
1436 // With LTO and a quasi-public visibility, the usages of the functions of the vtable are
1437 // all known by the `LinkageUnit`.
1438 // FIXME: LLVM only supports this optimization for `Lto::Fat` currently. Once it also
1439 // supports `Lto::Thin` the `VCallVisibility` may have to be adjusted for those.
1440 (Lto::Fat | Lto::Thin, Visibility::Public, _)
1441 | (Lto::ThinLocal | Lto::Thin | Lto::Fat, Visibility::Restricted(_), false) => {
1442 VCallVisibility::LinkageUnit
1444 // If there is only one CGU, private vtables can only be seen by that CGU/translation unit
1445 // and therefore we know of all usages of functions in the vtable.
1446 (_, Visibility::Restricted(_), true) => VCallVisibility::TranslationUnit,
1449 let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref);
1452 let typeid = llvm::LLVMMDStringInContext(
1454 trait_ref_typeid.as_ptr() as *const c_char,
1455 trait_ref_typeid.as_bytes().len() as c_uint,
1457 let v = [cx.const_usize(0), typeid];
1458 llvm::LLVMRustGlobalAddMetadata(
1460 llvm::MD_type as c_uint,
1461 llvm::LLVMValueAsMetadata(llvm::LLVMMDNodeInContext(
1467 let vcall_visibility = llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64));
1468 let vcall_visibility_metadata = llvm::LLVMMDNodeInContext2(cx.llcx, &vcall_visibility, 1);
1469 llvm::LLVMGlobalSetMetadata(
1471 llvm::MetadataType::MD_vcall_visibility as c_uint,
1472 vcall_visibility_metadata,
1477 /// Creates debug information for the given vtable, which is for the
1480 /// Adds the created metadata nodes directly to the crate's IR.
1481 pub fn create_vtable_di_node<'ll, 'tcx>(
1482 cx: &CodegenCx<'ll, 'tcx>,
1484 poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
1487 // FIXME(flip1995): The virtual function elimination optimization only works with full LTO in
1488 // LLVM at the moment.
1489 if cx.sess().opts.unstable_opts.virtual_function_elimination && cx.sess().lto() == Lto::Fat {
1490 vcall_visibility_metadata(cx, ty, poly_trait_ref, vtable);
1493 if cx.dbg_cx.is_none() {
1497 // Only create type information if full debuginfo is enabled
1498 if cx.sess().opts.debuginfo != DebugInfo::Full {
1503 compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref, VTableNameKind::GlobalVariable);
1504 let vtable_type_di_node = build_vtable_type_di_node(cx, ty, poly_trait_ref);
1505 let linkage_name = "";
1508 llvm::LLVMRustDIBuilderCreateStaticVariable(
1511 vtable_name.as_ptr().cast(),
1513 linkage_name.as_ptr().cast(),
1515 unknown_file_metadata(cx),
1516 UNKNOWN_LINE_NUMBER,
1517 vtable_type_di_node,
1526 /// Creates an "extension" of an existing `DIScope` into another file.
1527 pub fn extend_scope_to_file<'ll>(
1528 cx: &CodegenCx<'ll, '_>,
1529 scope_metadata: &'ll DIScope,
1531 ) -> &'ll DILexicalBlock {
1532 let file_metadata = file_metadata(cx, file);
1533 unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }
1536 pub fn tuple_field_name(field_index: usize) -> Cow<'static, str> {
1537 const TUPLE_FIELD_NAMES: [&'static str; 16] = [
1538 "__0", "__1", "__2", "__3", "__4", "__5", "__6", "__7", "__8", "__9", "__10", "__11",
1539 "__12", "__13", "__14", "__15",
1543 .map(|s| Cow::from(*s))
1544 .unwrap_or_else(|| Cow::from(format!("__{}", field_index)))