1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use self::RecursiveTypeDescription::*;
12 use self::MemberOffset::*;
13 use self::MemberDescriptionFactory::*;
14 use self::EnumDiscriminantInfo::*;
16 use super::utils::{debug_context, DIB, span_start, bytes_to_bits, size_and_align_of,
17 get_namespace_and_span_for_item, create_DIArray,
18 fn_should_be_ignored, is_node_local_to_unit};
19 use super::namespace::mangled_name_of_item;
20 use super::type_names::{compute_debuginfo_type_name, push_debuginfo_type_name};
21 use super::{declare_local, VariableKind, VariableAccess, CrateDebugContext};
22 use context::SharedCrateContext;
25 use llvm::{self, ValueRef};
26 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor, DICompositeType};
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::pat_util;
31 use rustc::hir::map as hir_map;
32 use rustc::hir::{self, PatKind};
33 use {type_of, adt, machine, monomorphize};
34 use common::{self, CrateContext, FunctionContext, Block};
35 use _match::{BindingInfo, TransBindingMode};
37 use rustc::ty::{self, Ty};
38 use session::config::{self, FullDebugInfo};
39 use util::nodemap::FnvHashMap;
40 use util::common::path2cstr;
42 use libc::{c_uint, c_longlong};
43 use std::ffi::CString;
48 use syntax::util::interner::Interner;
50 use syntax::parse::token;
51 use syntax_pos::{self, Span};
54 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
55 const DW_LANG_RUST: c_uint = 0x1c;
56 #[allow(non_upper_case_globals)]
57 const DW_ATE_boolean: c_uint = 0x02;
58 #[allow(non_upper_case_globals)]
59 const DW_ATE_float: c_uint = 0x04;
60 #[allow(non_upper_case_globals)]
61 const DW_ATE_signed: c_uint = 0x05;
62 #[allow(non_upper_case_globals)]
63 const DW_ATE_unsigned: c_uint = 0x07;
64 #[allow(non_upper_case_globals)]
65 const DW_ATE_unsigned_char: c_uint = 0x08;
67 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
68 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
70 // ptr::null() doesn't work :(
71 pub const NO_SCOPE_METADATA: DIScope = (0 as DIScope);
73 const FLAGS_NONE: c_uint = 0;
75 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
76 pub struct UniqueTypeId(ast::Name);
78 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
79 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
80 // faster lookup, also by Ty. The TypeMap is responsible for creating
82 pub struct TypeMap<'tcx> {
83 // The UniqueTypeIds created so far
84 unique_id_interner: Interner,
85 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
86 unique_id_to_metadata: FnvHashMap<UniqueTypeId, DIType>,
87 // A map from types to debuginfo metadata. This is a N:1 mapping.
88 type_to_metadata: FnvHashMap<Ty<'tcx>, DIType>,
89 // A map from types to UniqueTypeId. This is a N:1 mapping.
90 type_to_unique_id: FnvHashMap<Ty<'tcx>, UniqueTypeId>
93 impl<'tcx> TypeMap<'tcx> {
94 pub fn new() -> TypeMap<'tcx> {
96 unique_id_interner: Interner::new(),
97 type_to_metadata: FnvHashMap(),
98 unique_id_to_metadata: FnvHashMap(),
99 type_to_unique_id: FnvHashMap(),
103 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
104 // the mapping already exists.
105 fn register_type_with_metadata<'a>(&mut self,
108 if self.type_to_metadata.insert(type_, metadata).is_some() {
109 bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
113 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
114 // fail if the mapping already exists.
115 fn register_unique_id_with_metadata(&mut self,
116 unique_type_id: UniqueTypeId,
118 if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
119 let unique_type_id_str = self.get_unique_type_id_as_string(unique_type_id);
120 bug!("Type metadata for unique id '{}' is already in the TypeMap!",
121 &unique_type_id_str[..]);
125 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
126 self.type_to_metadata.get(&type_).cloned()
129 fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<DIType> {
130 self.unique_id_to_metadata.get(&unique_type_id).cloned()
133 // Get the string representation of a UniqueTypeId. This method will fail if
134 // the id is unknown.
135 fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> Rc<String> {
136 let UniqueTypeId(interner_key) = unique_type_id;
137 self.unique_id_interner.get(interner_key)
140 // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
141 // type has been requested before, this is just a table lookup. Otherwise an
142 // ID will be generated and stored for later lookup.
143 fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
144 type_: Ty<'tcx>) -> UniqueTypeId {
146 // basic type -> {:name of the type:}
147 // tuple -> {tuple_(:param-uid:)*}
148 // struct -> {struct_:svh: / :node-id:_<(:param-uid:),*> }
149 // enum -> {enum_:svh: / :node-id:_<(:param-uid:),*> }
150 // enum variant -> {variant_:variant-name:_:enum-uid:}
151 // reference (&) -> {& :pointee-uid:}
152 // mut reference (&mut) -> {&mut :pointee-uid:}
153 // ptr (*) -> {* :pointee-uid:}
154 // mut ptr (*mut) -> {*mut :pointee-uid:}
155 // unique ptr (box) -> {box :pointee-uid:}
156 // @-ptr (@) -> {@ :pointee-uid:}
157 // sized vec ([T; x]) -> {[:size:] :element-uid:}
158 // unsized vec ([T]) -> {[] :element-uid:}
159 // trait (T) -> {trait_:svh: / :node-id:_<(:param-uid:),*> }
160 // closure -> {<unsafe_> <once_> :store-sigil: |(:param-uid:),* <,_...>| -> \
161 // :return-type-uid: : (:bounds:)*}
162 // function -> {<unsafe_> <abi_> fn( (:param-uid:)* <,_...> ) -> \
163 // :return-type-uid:}
165 match self.type_to_unique_id.get(&type_).cloned() {
166 Some(unique_type_id) => return unique_type_id,
167 None => { /* generate one */}
170 let mut unique_type_id = String::with_capacity(256);
171 unique_type_id.push('{');
180 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
182 ty::TyEnum(def, substs) => {
183 unique_type_id.push_str("enum ");
184 from_def_id_and_substs(self, cx, def.did, substs, &mut unique_type_id);
186 ty::TyStruct(def, substs) => {
187 unique_type_id.push_str("struct ");
188 from_def_id_and_substs(self, cx, def.did, substs, &mut unique_type_id);
190 ty::TyTuple(component_types) if component_types.is_empty() => {
191 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
193 ty::TyTuple(component_types) => {
194 unique_type_id.push_str("tuple ");
195 for &component_type in component_types {
196 let component_type_id =
197 self.get_unique_type_id_of_type(cx, component_type);
198 let component_type_id =
199 self.get_unique_type_id_as_string(component_type_id);
200 unique_type_id.push_str(&component_type_id[..]);
203 ty::TyBox(inner_type) => {
204 unique_type_id.push_str("box ");
205 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
206 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
207 unique_type_id.push_str(&inner_type_id[..]);
209 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
210 unique_type_id.push('*');
211 if mutbl == hir::MutMutable {
212 unique_type_id.push_str("mut");
215 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
216 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
217 unique_type_id.push_str(&inner_type_id[..]);
219 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
220 unique_type_id.push('&');
221 if mutbl == hir::MutMutable {
222 unique_type_id.push_str("mut");
225 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
226 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
227 unique_type_id.push_str(&inner_type_id[..]);
229 ty::TyArray(inner_type, len) => {
230 unique_type_id.push_str(&format!("[{}]", len));
232 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
233 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
234 unique_type_id.push_str(&inner_type_id[..]);
236 ty::TySlice(inner_type) => {
237 unique_type_id.push_str("[]");
239 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
240 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
241 unique_type_id.push_str(&inner_type_id[..]);
243 ty::TyTrait(ref trait_data) => {
244 unique_type_id.push_str("trait ");
246 let principal = cx.tcx().erase_late_bound_regions(&trait_data.principal);
248 from_def_id_and_substs(self,
252 &mut unique_type_id);
254 ty::TyFnDef(_, _, &ty::BareFnTy{ unsafety, abi, ref sig } ) |
255 ty::TyFnPtr(&ty::BareFnTy{ unsafety, abi, ref sig } ) => {
256 if unsafety == hir::Unsafety::Unsafe {
257 unique_type_id.push_str("unsafe ");
260 unique_type_id.push_str(abi.name());
262 unique_type_id.push_str(" fn(");
264 let sig = cx.tcx().erase_late_bound_regions(sig);
265 let sig = cx.tcx().normalize_associated_type(&sig);
267 for ¶meter_type in &sig.inputs {
268 let parameter_type_id =
269 self.get_unique_type_id_of_type(cx, parameter_type);
270 let parameter_type_id =
271 self.get_unique_type_id_as_string(parameter_type_id);
272 unique_type_id.push_str(¶meter_type_id[..]);
273 unique_type_id.push(',');
277 unique_type_id.push_str("...");
280 unique_type_id.push_str(")->");
282 ty::FnConverging(ret_ty) => {
283 let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
284 let return_type_id = self.get_unique_type_id_as_string(return_type_id);
285 unique_type_id.push_str(&return_type_id[..]);
288 unique_type_id.push_str("!");
292 ty::TyClosure(_, substs) if substs.upvar_tys.is_empty() => {
293 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
295 ty::TyClosure(_, substs) => {
296 unique_type_id.push_str("closure ");
297 for upvar_type in substs.upvar_tys {
299 self.get_unique_type_id_of_type(cx, upvar_type);
301 self.get_unique_type_id_as_string(upvar_type_id);
302 unique_type_id.push_str(&upvar_type_id[..]);
306 bug!("get_unique_type_id_of_type() - unexpected type: {:?}",
311 unique_type_id.push('}');
313 // Trim to size before storing permanently
314 unique_type_id.shrink_to_fit();
316 let key = self.unique_id_interner.intern(unique_type_id);
317 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
319 return UniqueTypeId(key);
321 fn from_def_id_and_substs<'a, 'tcx>(type_map: &mut TypeMap<'tcx>,
322 cx: &CrateContext<'a, 'tcx>,
324 substs: &subst::Substs<'tcx>,
325 output: &mut String) {
326 // First, find out the 'real' def_id of the type. Items inlined from
327 // other crates have to be mapped back to their source.
328 let def_id = if let Some(node_id) = cx.tcx().map.as_local_node_id(def_id) {
329 if cx.tcx().map.is_inlined_node_id(node_id) {
330 // The given def_id identifies the inlined copy of a
331 // type definition, let's take the source of the copy.
332 cx.defid_for_inlined_node(node_id).unwrap()
340 // Get the crate name/disambiguator as first part of the identifier.
341 let crate_name = if def_id.is_local() {
342 cx.tcx().crate_name.clone()
344 cx.sess().cstore.original_crate_name(def_id.krate)
346 let crate_disambiguator = cx.tcx().crate_disambiguator(def_id.krate);
348 output.push_str(&crate_name[..]);
349 output.push_str("/");
350 output.push_str(&crate_disambiguator[..]);
351 output.push_str("/");
352 // Add the def-index as the second part
353 output.push_str(&format!("{:x}", def_id.index.as_usize()));
355 let tps = substs.types.get_slice(subst::TypeSpace);
359 for &type_parameter in tps {
361 type_map.get_unique_type_id_of_type(cx, type_parameter);
363 type_map.get_unique_type_id_as_string(param_type_id);
364 output.push_str(¶m_type_id[..]);
373 // Get the UniqueTypeId for an enum variant. Enum variants are not really
374 // types of their own, so they need special handling. We still need a
375 // UniqueTypeId for them, since to debuginfo they *are* real types.
376 fn get_unique_type_id_of_enum_variant<'a>(&mut self,
377 cx: &CrateContext<'a, 'tcx>,
381 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
382 let enum_variant_type_id = format!("{}::{}",
383 &self.get_unique_type_id_as_string(enum_type_id),
385 let interner_key = self.unique_id_interner.intern(enum_variant_type_id);
386 UniqueTypeId(interner_key)
390 // A description of some recursive type. It can either be already finished (as
391 // with FinalMetadata) or it is not yet finished, but contains all information
392 // needed to generate the missing parts of the description. See the
393 // documentation section on Recursive Types at the top of this file for more
395 enum RecursiveTypeDescription<'tcx> {
397 unfinished_type: Ty<'tcx>,
398 unique_type_id: UniqueTypeId,
399 metadata_stub: DICompositeType,
401 member_description_factory: MemberDescriptionFactory<'tcx>,
403 FinalMetadata(DICompositeType)
406 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
407 cx: &CrateContext<'a, 'tcx>,
408 unfinished_type: Ty<'tcx>,
409 unique_type_id: UniqueTypeId,
410 metadata_stub: DICompositeType,
412 member_description_factory: MemberDescriptionFactory<'tcx>)
413 -> RecursiveTypeDescription<'tcx> {
415 // Insert the stub into the TypeMap in order to allow for recursive references
416 let mut type_map = debug_context(cx).type_map.borrow_mut();
417 type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
418 type_map.register_type_with_metadata(unfinished_type, metadata_stub);
421 unfinished_type: unfinished_type,
422 unique_type_id: unique_type_id,
423 metadata_stub: metadata_stub,
424 llvm_type: llvm_type,
425 member_description_factory: member_description_factory,
429 impl<'tcx> RecursiveTypeDescription<'tcx> {
430 // Finishes up the description of the type in question (mostly by providing
431 // descriptions of the fields of the given type) and returns the final type
433 fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
435 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
441 ref member_description_factory,
444 // Make sure that we have a forward declaration of the type in
445 // the TypeMap so that recursive references are possible. This
446 // will always be the case if the RecursiveTypeDescription has
447 // been properly created through the
448 // create_and_register_recursive_type_forward_declaration()
451 let type_map = debug_context(cx).type_map.borrow();
452 if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
453 type_map.find_metadata_for_type(unfinished_type).is_none() {
454 bug!("Forward declaration of potentially recursive type \
455 '{:?}' was not found in TypeMap!",
460 // ... then create the member descriptions ...
461 let member_descriptions =
462 member_description_factory.create_member_descriptions(cx);
464 // ... and attach them to the stub to complete it.
465 set_members_of_composite_type(cx,
468 &member_descriptions[..]);
469 return MetadataCreationResult::new(metadata_stub, true);
475 // Returns from the enclosing function if the type metadata with the given
476 // unique id can be found in the type map
477 macro_rules! return_if_metadata_created_in_meantime {
478 ($cx: expr, $unique_type_id: expr) => (
479 match debug_context($cx).type_map
481 .find_metadata_for_unique_id($unique_type_id) {
482 Some(metadata) => return MetadataCreationResult::new(metadata, true),
483 None => { /* proceed normally */ }
488 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
489 unique_type_id: UniqueTypeId,
490 element_type: Ty<'tcx>,
493 -> MetadataCreationResult {
494 let element_type_metadata = type_metadata(cx, element_type, span);
496 return_if_metadata_created_in_meantime!(cx, unique_type_id);
498 let element_llvm_type = type_of::type_of(cx, element_type);
499 let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
501 let (array_size_in_bytes, upper_bound) = match len {
502 Some(len) => (element_type_size * len, len as c_longlong),
506 let subrange = unsafe {
507 llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
510 let subscripts = create_DIArray(DIB(cx), &[subrange]);
511 let metadata = unsafe {
512 llvm::LLVMRustDIBuilderCreateArrayType(
514 bytes_to_bits(array_size_in_bytes),
515 bytes_to_bits(element_type_align),
516 element_type_metadata,
520 return MetadataCreationResult::new(metadata, false);
523 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
525 element_type: Ty<'tcx>,
526 unique_type_id: UniqueTypeId,
528 -> MetadataCreationResult {
529 let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
531 mutbl: hir::MutImmutable
534 let element_type_metadata = type_metadata(cx, data_ptr_type, span);
536 return_if_metadata_created_in_meantime!(cx, unique_type_id);
538 let slice_llvm_type = type_of::type_of(cx, vec_type);
539 let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
541 let member_llvm_types = slice_llvm_type.field_types();
542 assert!(slice_layout_is_correct(cx,
543 &member_llvm_types[..],
545 let member_descriptions = [
547 name: "data_ptr".to_string(),
548 llvm_type: member_llvm_types[0],
549 type_metadata: element_type_metadata,
550 offset: ComputedMemberOffset,
554 name: "length".to_string(),
555 llvm_type: member_llvm_types[1],
556 type_metadata: type_metadata(cx, cx.tcx().types.usize, span),
557 offset: ComputedMemberOffset,
562 assert!(member_descriptions.len() == member_llvm_types.len());
564 let loc = span_start(cx, span);
565 let file_metadata = file_metadata(cx, &loc.file.name, &loc.file.abs_path);
567 let metadata = composite_type_metadata(cx,
569 &slice_type_name[..],
571 &member_descriptions,
575 return MetadataCreationResult::new(metadata, false);
577 fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
578 member_llvm_types: &[Type],
579 element_type: Ty<'tcx>)
581 member_llvm_types.len() == 2 &&
582 member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
583 member_llvm_types[1] == cx.int_type()
587 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
588 unique_type_id: UniqueTypeId,
589 signature: &ty::PolyFnSig<'tcx>,
591 -> MetadataCreationResult
593 let signature = cx.tcx().erase_late_bound_regions(signature);
595 let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs.len() + 1);
598 signature_metadata.push(match signature.output {
599 ty::FnConverging(ret_ty) => match ret_ty.sty {
600 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
601 _ => type_metadata(cx, ret_ty, span)
603 ty::FnDiverging => diverging_type_metadata(cx)
607 for &argument_type in &signature.inputs {
608 signature_metadata.push(type_metadata(cx, argument_type, span));
611 return_if_metadata_created_in_meantime!(cx, unique_type_id);
613 return MetadataCreationResult::new(
615 llvm::LLVMRustDIBuilderCreateSubroutineType(
617 unknown_file_metadata(cx),
618 create_DIArray(DIB(cx), &signature_metadata[..]))
623 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
624 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
625 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
626 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
627 // of a DST struct, there is no trait_object_type and the results of this
628 // function will be a little bit weird.
629 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
630 trait_type: Ty<'tcx>,
631 trait_object_type: Option<Ty<'tcx>>,
632 unique_type_id: UniqueTypeId)
634 // The implementation provided here is a stub. It makes sure that the trait
635 // type is assigned the correct name, size, namespace, and source location.
636 // But it does not describe the trait's methods.
638 let def_id = match trait_type.sty {
639 ty::TyTrait(ref data) => data.principal_def_id(),
641 bug!("debuginfo: Unexpected trait-object type in \
642 trait_pointer_metadata(): {:?}",
647 let trait_object_type = trait_object_type.unwrap_or(trait_type);
648 let trait_type_name =
649 compute_debuginfo_type_name(cx, trait_object_type, false);
651 let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
653 let trait_llvm_type = type_of::type_of(cx, trait_object_type);
654 let file_metadata = unknown_file_metadata(cx);
656 composite_type_metadata(cx,
658 &trait_type_name[..],
663 syntax_pos::DUMMY_SP)
666 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
668 usage_site_span: Span)
670 // Get the unique type id of this type.
671 let unique_type_id = {
672 let mut type_map = debug_context(cx).type_map.borrow_mut();
673 // First, try to find the type in TypeMap. If we have seen it before, we
674 // can exit early here.
675 match type_map.find_metadata_for_type(t) {
680 // The Ty is not in the TypeMap but maybe we have already seen
681 // an equivalent type (e.g. only differing in region arguments).
682 // In order to find out, generate the unique type id and look
684 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
685 match type_map.find_metadata_for_unique_id(unique_type_id) {
687 // There is already an equivalent type in the TypeMap.
688 // Register this Ty as an alias in the cache and
689 // return the cached metadata.
690 type_map.register_type_with_metadata(t, metadata);
694 // There really is no type metadata for this type, so
695 // proceed by creating it.
703 debug!("type_metadata: {:?}", t);
706 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
712 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
714 ty::TyTuple(ref elements) if elements.is_empty() => {
715 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
717 ty::TyEnum(def, _) => {
718 prepare_enum_metadata(cx,
722 usage_site_span).finalize(cx)
724 ty::TyArray(typ, len) => {
725 fixed_vec_metadata(cx, unique_type_id, typ, Some(len as u64), usage_site_span)
727 ty::TySlice(typ) => {
728 fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
731 fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
734 MetadataCreationResult::new(
735 trait_pointer_metadata(cx, t, None, unique_type_id),
739 ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
740 ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
742 ty::TySlice(typ) => {
743 vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
746 vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span)
749 MetadataCreationResult::new(
750 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
754 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
756 match debug_context(cx).type_map
758 .find_metadata_for_unique_id(unique_type_id) {
759 Some(metadata) => return metadata,
760 None => { /* proceed normally */ }
763 MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
768 ty::TyFnDef(_, _, ref barefnty) | ty::TyFnPtr(ref barefnty) => {
769 let fn_metadata = subroutine_type_metadata(cx,
772 usage_site_span).metadata;
773 match debug_context(cx).type_map
775 .find_metadata_for_unique_id(unique_type_id) {
776 Some(metadata) => return metadata,
777 None => { /* proceed normally */ }
780 // This is actually a function pointer, so wrap it in pointer DI
781 MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
784 ty::TyClosure(_, ref substs) => {
785 prepare_tuple_metadata(cx,
789 usage_site_span).finalize(cx)
791 ty::TyStruct(..) => {
792 prepare_struct_metadata(cx,
795 usage_site_span).finalize(cx)
797 ty::TyTuple(ref elements) => {
798 prepare_tuple_metadata(cx,
802 usage_site_span).finalize(cx)
805 bug!("debuginfo: unexpected type in type_metadata: {:?}", sty)
810 let mut type_map = debug_context(cx).type_map.borrow_mut();
812 if already_stored_in_typemap {
813 // Also make sure that we already have a TypeMap entry for the unique type id.
814 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
815 Some(metadata) => metadata,
817 let unique_type_id_str =
818 type_map.get_unique_type_id_as_string(unique_type_id);
819 span_bug!(usage_site_span,
820 "Expected type metadata for unique \
821 type id '{}' to already be in \
822 the debuginfo::TypeMap but it \
824 &unique_type_id_str[..],
829 match type_map.find_metadata_for_type(t) {
831 if metadata != metadata_for_uid {
832 let unique_type_id_str =
833 type_map.get_unique_type_id_as_string(unique_type_id);
834 span_bug!(usage_site_span,
835 "Mismatch between Ty and \
836 UniqueTypeId maps in \
837 debuginfo::TypeMap. \
838 UniqueTypeId={}, Ty={}",
839 &unique_type_id_str[..],
844 type_map.register_type_with_metadata(t, metadata);
848 type_map.register_type_with_metadata(t, metadata);
849 type_map.register_unique_id_with_metadata(unique_type_id, metadata);
856 pub fn file_metadata(cx: &CrateContext, path: &str, full_path: &Option<String>) -> DIFile {
857 // FIXME (#9639): This needs to handle non-utf8 paths
858 let work_dir = cx.sess().working_dir.to_str().unwrap();
860 full_path.as_ref().map(|p| p.as_str()).unwrap_or_else(|| {
861 if path.starts_with(work_dir) {
862 &path[work_dir.len() + 1..path.len()]
868 file_metadata_(cx, path, file_name, &work_dir)
871 pub fn unknown_file_metadata(cx: &CrateContext) -> DIFile {
872 // Regular filenames should not be empty, so we abuse an empty name as the
873 // key for the special unknown file metadata
874 file_metadata_(cx, "", "<unknown>", "")
878 fn file_metadata_(cx: &CrateContext, key: &str, file_name: &str, work_dir: &str) -> DIFile {
879 if let Some(file_metadata) = debug_context(cx).created_files.borrow().get(key) {
880 return *file_metadata;
883 debug!("file_metadata: file_name: {}, work_dir: {}", file_name, work_dir);
885 let file_name = CString::new(file_name).unwrap();
886 let work_dir = CString::new(work_dir).unwrap();
887 let file_metadata = unsafe {
888 llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(),
892 let mut created_files = debug_context(cx).created_files.borrow_mut();
893 created_files.insert(key.to_string(), file_metadata);
897 /// Finds the scope metadata node for the given AST node.
898 pub fn scope_metadata(fcx: &FunctionContext,
899 node_id: ast::NodeId,
900 error_reporting_span: Span)
902 let scope_map = &fcx.debug_context
903 .get_ref(error_reporting_span)
905 match scope_map.borrow().get(&node_id).cloned() {
906 Some(scope_metadata) => scope_metadata,
908 let node = fcx.ccx.tcx().map.get(node_id);
910 span_bug!(error_reporting_span,
911 "debuginfo: Could not find scope info for node {:?}",
917 pub fn diverging_type_metadata(cx: &CrateContext) -> DIType {
919 llvm::LLVMRustDIBuilderCreateBasicType(
921 "!\0".as_ptr() as *const _,
928 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
929 t: Ty<'tcx>) -> DIType {
931 debug!("basic_type_metadata: {:?}", t);
933 let (name, encoding) = match t.sty {
934 ty::TyTuple(ref elements) if elements.is_empty() =>
935 ("()", DW_ATE_unsigned),
936 ty::TyBool => ("bool", DW_ATE_boolean),
937 ty::TyChar => ("char", DW_ATE_unsigned_char),
938 ty::TyInt(int_ty) => {
939 (int_ty.ty_to_string(), DW_ATE_signed)
941 ty::TyUint(uint_ty) => {
942 (uint_ty.ty_to_string(), DW_ATE_unsigned)
944 ty::TyFloat(float_ty) => {
945 (float_ty.ty_to_string(), DW_ATE_float)
947 _ => bug!("debuginfo::basic_type_metadata - t is invalid type")
950 let llvm_type = type_of::type_of(cx, t);
951 let (size, align) = size_and_align_of(cx, llvm_type);
952 let name = CString::new(name).unwrap();
953 let ty_metadata = unsafe {
954 llvm::LLVMRustDIBuilderCreateBasicType(
958 bytes_to_bits(align),
965 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
966 pointer_type: Ty<'tcx>,
967 pointee_type_metadata: DIType)
969 let pointer_llvm_type = type_of::type_of(cx, pointer_type);
970 let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
971 let name = compute_debuginfo_type_name(cx, pointer_type, false);
972 let name = CString::new(name).unwrap();
973 let ptr_metadata = unsafe {
974 llvm::LLVMRustDIBuilderCreatePointerType(
976 pointee_type_metadata,
977 bytes_to_bits(pointer_size),
978 bytes_to_bits(pointer_align),
984 pub fn compile_unit_metadata(scc: &SharedCrateContext,
985 debug_context: &CrateDebugContext,
988 let work_dir = &sess.working_dir;
989 let compile_unit_name = match sess.local_crate_source_file {
990 None => fallback_path(scc),
991 Some(ref abs_path) => {
992 if abs_path.is_relative() {
993 sess.warn("debuginfo: Invalid path to crate's local root source file!");
996 match abs_path.strip_prefix(work_dir) {
997 Ok(ref p) if p.is_relative() => {
998 if p.starts_with(Path::new("./")) {
1001 path2cstr(&Path::new(".").join(p))
1004 _ => fallback_path(scc)
1010 debug!("compile_unit_metadata: {:?}", compile_unit_name);
1011 let producer = format!("rustc version {}",
1012 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
1014 let compile_unit_name = compile_unit_name.as_ptr();
1015 let work_dir = path2cstr(&work_dir);
1016 let producer = CString::new(producer).unwrap();
1018 let split_name = "\0";
1020 llvm::LLVMRustDIBuilderCreateCompileUnit(
1021 debug_context.builder,
1026 sess.opts.optimize != config::OptLevel::No,
1027 flags.as_ptr() as *const _,
1029 split_name.as_ptr() as *const _)
1032 fn fallback_path(scc: &SharedCrateContext) -> CString {
1033 CString::new(scc.link_meta().crate_name.clone()).unwrap()
1037 struct MetadataCreationResult {
1039 already_stored_in_typemap: bool
1042 impl MetadataCreationResult {
1043 fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
1044 MetadataCreationResult {
1046 already_stored_in_typemap: already_stored_in_typemap
1053 FixedMemberOffset { bytes: usize },
1054 // For ComputedMemberOffset, the offset is read from the llvm type definition.
1055 ComputedMemberOffset
1058 // Description of a type member, which can either be a regular field (as in
1059 // structs or tuples) or an enum variant.
1061 struct MemberDescription {
1064 type_metadata: DIType,
1065 offset: MemberOffset,
1069 // A factory for MemberDescriptions. It produces a list of member descriptions
1070 // for some record-like type. MemberDescriptionFactories are used to defer the
1071 // creation of type member descriptions in order to break cycles arising from
1072 // recursive type definitions.
1073 enum MemberDescriptionFactory<'tcx> {
1074 StructMDF(StructMemberDescriptionFactory<'tcx>),
1075 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1076 EnumMDF(EnumMemberDescriptionFactory<'tcx>),
1077 VariantMDF(VariantMemberDescriptionFactory<'tcx>)
1080 impl<'tcx> MemberDescriptionFactory<'tcx> {
1081 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1082 -> Vec<MemberDescription> {
1084 StructMDF(ref this) => {
1085 this.create_member_descriptions(cx)
1087 TupleMDF(ref this) => {
1088 this.create_member_descriptions(cx)
1090 EnumMDF(ref this) => {
1091 this.create_member_descriptions(cx)
1093 VariantMDF(ref this) => {
1094 this.create_member_descriptions(cx)
1100 //=-----------------------------------------------------------------------------
1102 //=-----------------------------------------------------------------------------
1104 // Creates MemberDescriptions for the fields of a struct
1105 struct StructMemberDescriptionFactory<'tcx> {
1106 variant: ty::VariantDef<'tcx>,
1107 substs: &'tcx subst::Substs<'tcx>,
1112 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1113 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1114 -> Vec<MemberDescription> {
1115 if self.variant.kind == ty::VariantKind::Unit {
1119 let field_size = if self.is_simd {
1120 let fty = monomorphize::field_ty(cx.tcx(),
1122 &self.variant.fields[0]);
1123 Some(machine::llsize_of_alloc(
1125 type_of::type_of(cx, fty)
1131 self.variant.fields.iter().enumerate().map(|(i, f)| {
1132 let name = if self.variant.kind == ty::VariantKind::Tuple {
1137 let fty = monomorphize::field_ty(cx.tcx(), self.substs, f);
1139 let offset = if self.is_simd {
1140 FixedMemberOffset { bytes: i * field_size.unwrap() }
1142 ComputedMemberOffset
1147 llvm_type: type_of::type_of(cx, fty),
1148 type_metadata: type_metadata(cx, fty, self.span),
1157 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1158 struct_type: Ty<'tcx>,
1159 unique_type_id: UniqueTypeId,
1161 -> RecursiveTypeDescription<'tcx> {
1162 let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
1163 let struct_llvm_type = type_of::in_memory_type_of(cx, struct_type);
1165 let (struct_def_id, variant, substs) = match struct_type.sty {
1166 ty::TyStruct(def, substs) => (def.did, def.struct_variant(), substs),
1167 _ => bug!("prepare_struct_metadata on a non-struct")
1170 let (containing_scope, _) = get_namespace_and_span_for_item(cx, struct_def_id);
1172 let struct_metadata_stub = create_struct_stub(cx,
1178 create_and_register_recursive_type_forward_declaration(
1182 struct_metadata_stub,
1184 StructMDF(StructMemberDescriptionFactory {
1187 is_simd: struct_type.is_simd(),
1194 //=-----------------------------------------------------------------------------
1196 //=-----------------------------------------------------------------------------
1198 // Creates MemberDescriptions for the fields of a tuple
1199 struct TupleMemberDescriptionFactory<'tcx> {
1200 component_types: Vec<Ty<'tcx>>,
1204 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1205 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1206 -> Vec<MemberDescription> {
1207 self.component_types
1210 .map(|(i, &component_type)| {
1212 name: format!("__{}", i),
1213 llvm_type: type_of::type_of(cx, component_type),
1214 type_metadata: type_metadata(cx, component_type, self.span),
1215 offset: ComputedMemberOffset,
1222 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1223 tuple_type: Ty<'tcx>,
1224 component_types: &[Ty<'tcx>],
1225 unique_type_id: UniqueTypeId,
1227 -> RecursiveTypeDescription<'tcx> {
1228 let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1229 let tuple_llvm_type = type_of::type_of(cx, tuple_type);
1231 create_and_register_recursive_type_forward_declaration(
1235 create_struct_stub(cx,
1241 TupleMDF(TupleMemberDescriptionFactory {
1242 component_types: component_types.to_vec(),
1249 //=-----------------------------------------------------------------------------
1251 //=-----------------------------------------------------------------------------
1253 // Describes the members of an enum value: An enum is described as a union of
1254 // structs in DWARF. This MemberDescriptionFactory provides the description for
1255 // the members of this union; so for every variant of the given enum, this
1256 // factory will produce one MemberDescription (all with no name and a fixed
1257 // offset of zero bytes).
1258 struct EnumMemberDescriptionFactory<'tcx> {
1259 enum_type: Ty<'tcx>,
1260 type_rep: Rc<adt::Repr<'tcx>>,
1261 discriminant_type_metadata: Option<DIType>,
1262 containing_scope: DIScope,
1263 file_metadata: DIFile,
1267 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1268 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1269 -> Vec<MemberDescription> {
1270 let adt = &self.enum_type.ty_adt_def().unwrap();
1271 match *self.type_rep {
1272 adt::General(_, ref struct_defs, _) => {
1273 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1278 .map(|(i, struct_def)| {
1279 let (variant_type_metadata,
1281 member_desc_factory) =
1282 describe_enum_variant(cx,
1287 self.containing_scope,
1290 let member_descriptions = member_desc_factory
1291 .create_member_descriptions(cx);
1293 set_members_of_composite_type(cx,
1294 variant_type_metadata,
1296 &member_descriptions);
1298 name: "".to_string(),
1299 llvm_type: variant_llvm_type,
1300 type_metadata: variant_type_metadata,
1301 offset: FixedMemberOffset { bytes: 0 },
1306 adt::Univariant(ref struct_def, _) => {
1307 assert!(adt.variants.len() <= 1);
1309 if adt.variants.is_empty() {
1312 let (variant_type_metadata,
1314 member_description_factory) =
1315 describe_enum_variant(cx,
1320 self.containing_scope,
1323 let member_descriptions =
1324 member_description_factory.create_member_descriptions(cx);
1326 set_members_of_composite_type(cx,
1327 variant_type_metadata,
1329 &member_descriptions[..]);
1332 name: "".to_string(),
1333 llvm_type: variant_llvm_type,
1334 type_metadata: variant_type_metadata,
1335 offset: FixedMemberOffset { bytes: 0 },
1341 adt::RawNullablePointer { nndiscr: non_null_variant_index, nnty, .. } => {
1342 // As far as debuginfo is concerned, the pointer this enum
1343 // represents is still wrapped in a struct. This is to make the
1344 // DWARF representation of enums uniform.
1346 // First create a description of the artificial wrapper struct:
1347 let non_null_variant = &adt.variants[non_null_variant_index.0 as usize];
1348 let non_null_variant_name = non_null_variant.name.as_str();
1350 // The llvm type and metadata of the pointer
1351 let non_null_llvm_type = type_of::type_of(cx, nnty);
1352 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
1354 // The type of the artificial struct wrapping the pointer
1355 let artificial_struct_llvm_type = Type::struct_(cx,
1356 &[non_null_llvm_type],
1359 // For the metadata of the wrapper struct, we need to create a
1360 // MemberDescription of the struct's single field.
1361 let sole_struct_member_description = MemberDescription {
1362 name: match non_null_variant.kind {
1363 ty::VariantKind::Tuple => "__0".to_string(),
1364 ty::VariantKind::Struct => {
1365 non_null_variant.fields[0].name.to_string()
1367 ty::VariantKind::Unit => bug!()
1369 llvm_type: non_null_llvm_type,
1370 type_metadata: non_null_type_metadata,
1371 offset: FixedMemberOffset { bytes: 0 },
1375 let unique_type_id = debug_context(cx).type_map
1377 .get_unique_type_id_of_enum_variant(
1380 &non_null_variant_name);
1382 // Now we can create the metadata of the artificial struct
1383 let artificial_struct_metadata =
1384 composite_type_metadata(cx,
1385 artificial_struct_llvm_type,
1386 &non_null_variant_name,
1388 &[sole_struct_member_description],
1389 self.containing_scope,
1391 syntax_pos::DUMMY_SP);
1393 // Encode the information about the null variant in the union
1395 let null_variant_index = (1 - non_null_variant_index.0) as usize;
1396 let null_variant_name = adt.variants[null_variant_index].name;
1397 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1401 // Finally create the (singleton) list of descriptions of union
1405 name: union_member_name,
1406 llvm_type: artificial_struct_llvm_type,
1407 type_metadata: artificial_struct_metadata,
1408 offset: FixedMemberOffset { bytes: 0 },
1413 adt::StructWrappedNullablePointer { nonnull: ref struct_def,
1415 ref discrfield, ..} => {
1416 // Create a description of the non-null variant
1417 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
1418 describe_enum_variant(cx,
1421 &adt.variants[nndiscr.0 as usize],
1422 OptimizedDiscriminant,
1423 self.containing_scope,
1426 let variant_member_descriptions =
1427 member_description_factory.create_member_descriptions(cx);
1429 set_members_of_composite_type(cx,
1430 variant_type_metadata,
1432 &variant_member_descriptions[..]);
1434 // Encode the information about the null variant in the union
1436 let null_variant_index = (1 - nndiscr.0) as usize;
1437 let null_variant_name = adt.variants[null_variant_index].name;
1438 let discrfield = discrfield.iter()
1440 .map(|x| x.to_string())
1441 .collect::<Vec<_>>().join("$");
1442 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1446 // Create the (singleton) list of descriptions of union members.
1449 name: union_member_name,
1450 llvm_type: variant_llvm_type,
1451 type_metadata: variant_type_metadata,
1452 offset: FixedMemberOffset { bytes: 0 },
1457 adt::CEnum(..) => span_bug!(self.span, "This should be unreachable.")
1462 // Creates MemberDescriptions for the fields of a single enum variant.
1463 struct VariantMemberDescriptionFactory<'tcx> {
1464 args: Vec<(String, Ty<'tcx>)>,
1465 discriminant_type_metadata: Option<DIType>,
1469 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1470 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1471 -> Vec<MemberDescription> {
1472 self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1474 name: name.to_string(),
1475 llvm_type: type_of::type_of(cx, ty),
1476 type_metadata: match self.discriminant_type_metadata {
1477 Some(metadata) if i == 0 => metadata,
1478 _ => type_metadata(cx, ty, self.span)
1480 offset: ComputedMemberOffset,
1487 #[derive(Copy, Clone)]
1488 enum EnumDiscriminantInfo {
1489 RegularDiscriminant(DIType),
1490 OptimizedDiscriminant,
1494 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1495 // of the variant, and (3) a MemberDescriptionFactory for producing the
1496 // descriptions of the fields of the variant. This is a rudimentary version of a
1497 // full RecursiveTypeDescription.
1498 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1499 enum_type: Ty<'tcx>,
1500 struct_def: &adt::Struct<'tcx>,
1501 variant: ty::VariantDef<'tcx>,
1502 discriminant_info: EnumDiscriminantInfo,
1503 containing_scope: DIScope,
1505 -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1506 let variant_llvm_type =
1507 Type::struct_(cx, &struct_def.fields
1509 .map(|&t| type_of::type_of(cx, t))
1510 .collect::<Vec<_>>()
1513 // Could do some consistency checks here: size, align, field count, discr type
1515 let variant_name = variant.name.as_str();
1516 let unique_type_id = debug_context(cx).type_map
1518 .get_unique_type_id_of_enum_variant(
1523 let metadata_stub = create_struct_stub(cx,
1529 // Get the argument names from the enum variant info
1530 let mut arg_names: Vec<_> = match variant.kind {
1531 ty::VariantKind::Unit => vec![],
1532 ty::VariantKind::Tuple => {
1536 .map(|(i, _)| format!("__{}", i))
1539 ty::VariantKind::Struct => {
1542 .map(|f| f.name.to_string())
1547 // If this is not a univariant enum, there is also the discriminant field.
1548 match discriminant_info {
1549 RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
1550 _ => { /* do nothing */ }
1553 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1554 let args: Vec<(String, Ty)> = arg_names.iter()
1555 .zip(&struct_def.fields)
1556 .map(|(s, &t)| (s.to_string(), t))
1559 let member_description_factory =
1560 VariantMDF(VariantMemberDescriptionFactory {
1562 discriminant_type_metadata: match discriminant_info {
1563 RegularDiscriminant(discriminant_type_metadata) => {
1564 Some(discriminant_type_metadata)
1571 (metadata_stub, variant_llvm_type, member_description_factory)
1574 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1575 enum_type: Ty<'tcx>,
1577 unique_type_id: UniqueTypeId,
1579 -> RecursiveTypeDescription<'tcx> {
1580 let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1582 let (containing_scope, _) = get_namespace_and_span_for_item(cx, enum_def_id);
1583 // FIXME: This should emit actual file metadata for the enum, but we
1584 // currently can't get the necessary information when it comes to types
1585 // imported from other crates. Formerly we violated the ODR when performing
1586 // LTO because we emitted debuginfo for the same type with varying file
1587 // metadata, so as a workaround we pretend that the type comes from
1589 let file_metadata = unknown_file_metadata(cx);
1591 let variants = &enum_type.ty_adt_def().unwrap().variants;
1593 let enumerators_metadata: Vec<DIDescriptor> = variants
1596 let token = v.name.as_str();
1597 let name = CString::new(token.as_bytes()).unwrap();
1599 llvm::LLVMRustDIBuilderCreateEnumerator(
1602 v.disr_val.to_u64_unchecked())
1607 let discriminant_type_metadata = |inttype: syntax::attr::IntType| {
1608 let disr_type_key = (enum_def_id, inttype);
1609 let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1611 .get(&disr_type_key).cloned();
1612 match cached_discriminant_type_metadata {
1613 Some(discriminant_type_metadata) => discriminant_type_metadata,
1615 let discriminant_llvm_type = adt::ll_inttype(cx, inttype);
1616 let (discriminant_size, discriminant_align) =
1617 size_and_align_of(cx, discriminant_llvm_type);
1618 let discriminant_base_type_metadata =
1620 adt::ty_of_inttype(cx.tcx(), inttype),
1621 syntax_pos::DUMMY_SP);
1622 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1624 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1625 let discriminant_type_metadata = unsafe {
1626 llvm::LLVMRustDIBuilderCreateEnumerationType(
1631 UNKNOWN_LINE_NUMBER,
1632 bytes_to_bits(discriminant_size),
1633 bytes_to_bits(discriminant_align),
1634 create_DIArray(DIB(cx), &enumerators_metadata),
1635 discriminant_base_type_metadata)
1638 debug_context(cx).created_enum_disr_types
1640 .insert(disr_type_key, discriminant_type_metadata);
1642 discriminant_type_metadata
1647 let type_rep = adt::represent_type(cx, enum_type);
1649 let discriminant_type_metadata = match *type_rep {
1650 adt::CEnum(inttype, _, _) => {
1651 return FinalMetadata(discriminant_type_metadata(inttype))
1653 adt::RawNullablePointer { .. } |
1654 adt::StructWrappedNullablePointer { .. } |
1655 adt::Univariant(..) => None,
1656 adt::General(inttype, _, _) => Some(discriminant_type_metadata(inttype)),
1659 let enum_llvm_type = type_of::type_of(cx, enum_type);
1660 let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
1662 let unique_type_id_str = debug_context(cx)
1665 .get_unique_type_id_as_string(unique_type_id);
1667 let enum_name = CString::new(enum_name).unwrap();
1668 let unique_type_id_str = CString::new(unique_type_id_str.as_bytes()).unwrap();
1669 let enum_metadata = unsafe {
1670 llvm::LLVMRustDIBuilderCreateUnionType(
1675 UNKNOWN_LINE_NUMBER,
1676 bytes_to_bits(enum_type_size),
1677 bytes_to_bits(enum_type_align),
1681 unique_type_id_str.as_ptr())
1684 return create_and_register_recursive_type_forward_declaration(
1690 EnumMDF(EnumMemberDescriptionFactory {
1691 enum_type: enum_type,
1692 type_rep: type_rep.clone(),
1693 discriminant_type_metadata: discriminant_type_metadata,
1694 containing_scope: containing_scope,
1695 file_metadata: file_metadata,
1700 fn get_enum_discriminant_name(cx: &CrateContext,
1702 -> token::InternedString {
1703 cx.tcx().item_name(def_id).as_str()
1707 /// Creates debug information for a composite type, that is, anything that
1708 /// results in a LLVM struct.
1710 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1711 fn composite_type_metadata(cx: &CrateContext,
1712 composite_llvm_type: Type,
1713 composite_type_name: &str,
1714 composite_type_unique_id: UniqueTypeId,
1715 member_descriptions: &[MemberDescription],
1716 containing_scope: DIScope,
1718 // Ignore source location information as long as it
1719 // can't be reconstructed for non-local crates.
1720 _file_metadata: DIFile,
1721 _definition_span: Span)
1722 -> DICompositeType {
1723 // Create the (empty) struct metadata node ...
1724 let composite_type_metadata = create_struct_stub(cx,
1725 composite_llvm_type,
1726 composite_type_name,
1727 composite_type_unique_id,
1729 // ... and immediately create and add the member descriptions.
1730 set_members_of_composite_type(cx,
1731 composite_type_metadata,
1732 composite_llvm_type,
1733 member_descriptions);
1735 return composite_type_metadata;
1738 fn set_members_of_composite_type(cx: &CrateContext,
1739 composite_type_metadata: DICompositeType,
1740 composite_llvm_type: Type,
1741 member_descriptions: &[MemberDescription]) {
1742 // In some rare cases LLVM metadata uniquing would lead to an existing type
1743 // description being used instead of a new one created in
1744 // create_struct_stub. This would cause a hard to trace assertion in
1745 // DICompositeType::SetTypeArray(). The following check makes sure that we
1746 // get a better error message if this should happen again due to some
1749 let mut composite_types_completed =
1750 debug_context(cx).composite_types_completed.borrow_mut();
1751 if composite_types_completed.contains(&composite_type_metadata) {
1752 bug!("debuginfo::set_members_of_composite_type() - \
1753 Already completed forward declaration re-encountered.");
1755 composite_types_completed.insert(composite_type_metadata);
1759 let member_metadata: Vec<DIDescriptor> = member_descriptions
1762 .map(|(i, member_description)| {
1763 let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
1764 let member_offset = match member_description.offset {
1765 FixedMemberOffset { bytes } => bytes as u64,
1766 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
1769 let member_name = member_description.name.as_bytes();
1770 let member_name = CString::new(member_name).unwrap();
1772 llvm::LLVMRustDIBuilderCreateMemberType(
1774 composite_type_metadata,
1775 member_name.as_ptr(),
1776 unknown_file_metadata(cx),
1777 UNKNOWN_LINE_NUMBER,
1778 bytes_to_bits(member_size),
1779 bytes_to_bits(member_align),
1780 bytes_to_bits(member_offset),
1781 member_description.flags,
1782 member_description.type_metadata)
1788 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1789 llvm::LLVMRustDICompositeTypeSetTypeArray(
1790 DIB(cx), composite_type_metadata, type_array);
1794 // A convenience wrapper around LLVMRustDIBuilderCreateStructType(). Does not do
1795 // any caching, does not add any fields to the struct. This can be done later
1796 // with set_members_of_composite_type().
1797 fn create_struct_stub(cx: &CrateContext,
1798 struct_llvm_type: Type,
1799 struct_type_name: &str,
1800 unique_type_id: UniqueTypeId,
1801 containing_scope: DIScope)
1802 -> DICompositeType {
1803 let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
1805 let unique_type_id_str = debug_context(cx).type_map
1807 .get_unique_type_id_as_string(unique_type_id);
1808 let name = CString::new(struct_type_name).unwrap();
1809 let unique_type_id = CString::new(unique_type_id_str.as_bytes()).unwrap();
1810 let metadata_stub = unsafe {
1811 // LLVMRustDIBuilderCreateStructType() wants an empty array. A null
1812 // pointer will lead to hard to trace and debug LLVM assertions
1813 // later on in llvm/lib/IR/Value.cpp.
1814 let empty_array = create_DIArray(DIB(cx), &[]);
1816 llvm::LLVMRustDIBuilderCreateStructType(
1820 unknown_file_metadata(cx),
1821 UNKNOWN_LINE_NUMBER,
1822 bytes_to_bits(struct_size),
1823 bytes_to_bits(struct_align),
1829 unique_type_id.as_ptr())
1832 return metadata_stub;
1835 /// Creates debug information for the given global variable.
1837 /// Adds the created metadata nodes directly to the crate's IR.
1838 pub fn create_global_var_metadata(cx: &CrateContext,
1839 node_id: ast::NodeId,
1841 if cx.dbg_cx().is_none() {
1845 // Don't create debuginfo for globals inlined from other crates. The other
1846 // crate should already contain debuginfo for it. More importantly, the
1847 // global might not even exist in un-inlined form anywhere which would lead
1848 // to a linker errors.
1849 if cx.tcx().map.is_inlined_node_id(node_id) {
1853 let node_def_id = cx.tcx().map.local_def_id(node_id);
1854 let (var_scope, span) = get_namespace_and_span_for_item(cx, node_def_id);
1856 let (file_metadata, line_number) = if span != syntax_pos::DUMMY_SP {
1857 let loc = span_start(cx, span);
1858 (file_metadata(cx, &loc.file.name, &loc.file.abs_path), loc.line as c_uint)
1860 (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
1863 let is_local_to_unit = is_node_local_to_unit(cx, node_id);
1864 let variable_type = cx.tcx().node_id_to_type(node_id);
1865 let type_metadata = type_metadata(cx, variable_type, span);
1866 let var_name = cx.tcx().item_name(node_def_id).to_string();
1867 let linkage_name = mangled_name_of_item(cx, node_def_id, "");
1869 let var_name = CString::new(var_name).unwrap();
1870 let linkage_name = CString::new(linkage_name).unwrap();
1872 llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx),
1875 linkage_name.as_ptr(),
1885 /// Creates debug information for the given local variable.
1887 /// This function assumes that there's a datum for each pattern component of the
1888 /// local in `bcx.fcx.lllocals`.
1889 /// Adds the created metadata nodes directly to the crate's IR.
1890 pub fn create_local_var_metadata(bcx: Block, local: &hir::Local) {
1891 if bcx.unreachable.get() ||
1892 fn_should_be_ignored(bcx.fcx) ||
1893 bcx.sess().opts.debuginfo != FullDebugInfo {
1897 let locals = bcx.fcx.lllocals.borrow();
1898 pat_util::pat_bindings(&local.pat, |_, node_id, span, var_name| {
1899 let datum = match locals.get(&node_id) {
1900 Some(datum) => datum,
1903 "no entry in lllocals table for {}",
1908 if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
1909 span_bug!(span, "debuginfo::create_local_var_metadata() - \
1910 Referenced variable location is not an alloca!");
1913 let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
1919 VariableAccess::DirectVariable { alloca: datum.val },
1920 VariableKind::LocalVariable,
1925 /// Creates debug information for a variable captured in a closure.
1927 /// Adds the created metadata nodes directly to the crate's IR.
1928 pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1929 node_id: ast::NodeId,
1930 env_pointer: ValueRef,
1932 captured_by_ref: bool,
1934 if bcx.unreachable.get() ||
1935 fn_should_be_ignored(bcx.fcx) ||
1936 bcx.sess().opts.debuginfo != FullDebugInfo {
1942 let ast_item = cx.tcx().map.find(node_id);
1944 let variable_name = match ast_item {
1946 span_bug!(span, "debuginfo::create_captured_var_metadata: node not found");
1948 Some(hir_map::NodeLocal(pat)) => {
1950 PatKind::Binding(_, ref path1, _) => {
1955 "debuginfo::create_captured_var_metadata() - \
1956 Captured var-id refers to unexpected \
1957 hir_map variant: {:?}",
1964 "debuginfo::create_captured_var_metadata() - \
1965 Captured var-id refers to unexpected \
1966 hir_map variant: {:?}",
1971 let variable_type = common::node_id_type(bcx, node_id);
1972 let scope_metadata = bcx.fcx.debug_context.get_ref(span).fn_metadata;
1974 // env_pointer is the alloca containing the pointer to the environment,
1975 // so it's type is **EnvironmentType. In order to find out the type of
1976 // the environment we have to "dereference" two times.
1977 let llvm_env_data_type = common::val_ty(env_pointer).element_type()
1979 let byte_offset_of_var_in_env = machine::llelement_offset(cx,
1983 let address_operations = unsafe {
1984 [llvm::LLVMRustDIBuilderCreateOpDeref(),
1985 llvm::LLVMRustDIBuilderCreateOpPlus(),
1986 byte_offset_of_var_in_env as i64,
1987 llvm::LLVMRustDIBuilderCreateOpDeref()]
1990 let address_op_count = if captured_by_ref {
1991 address_operations.len()
1993 address_operations.len() - 1
1996 let variable_access = VariableAccess::IndirectVariable {
1997 alloca: env_pointer,
1998 address_operations: &address_operations[..address_op_count]
2006 VariableKind::CapturedVariable,
2010 /// Creates debug information for a local variable introduced in the head of a
2011 /// match-statement arm.
2013 /// Adds the created metadata nodes directly to the crate's IR.
2014 pub fn create_match_binding_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2015 variable_name: ast::Name,
2016 binding: BindingInfo<'tcx>) {
2017 if bcx.unreachable.get() ||
2018 fn_should_be_ignored(bcx.fcx) ||
2019 bcx.sess().opts.debuginfo != FullDebugInfo {
2023 let scope_metadata = scope_metadata(bcx.fcx, binding.id, binding.span);
2025 [llvm::LLVMRustDIBuilderCreateOpDeref()]
2027 // Regardless of the actual type (`T`) we're always passed the stack slot
2028 // (alloca) for the binding. For ByRef bindings that's a `T*` but for ByMove
2029 // bindings we actually have `T**`. So to get the actual variable we need to
2030 // dereference once more. For ByCopy we just use the stack slot we created
2032 let var_access = match binding.trmode {
2033 TransBindingMode::TrByCopy(llbinding) |
2034 TransBindingMode::TrByMoveIntoCopy(llbinding) => VariableAccess::DirectVariable {
2037 TransBindingMode::TrByMoveRef => VariableAccess::IndirectVariable {
2038 alloca: binding.llmatch,
2039 address_operations: &aops
2041 TransBindingMode::TrByRef => VariableAccess::DirectVariable {
2042 alloca: binding.llmatch
2051 VariableKind::LocalVariable,
2055 /// Creates debug information for the given function argument.
2057 /// This function assumes that there's a datum for each pattern component of the
2058 /// argument in `bcx.fcx.lllocals`.
2059 /// Adds the created metadata nodes directly to the crate's IR.
2060 pub fn create_argument_metadata(bcx: Block, arg: &hir::Arg) {
2061 if bcx.unreachable.get() ||
2062 fn_should_be_ignored(bcx.fcx) ||
2063 bcx.sess().opts.debuginfo != FullDebugInfo {
2067 let scope_metadata = bcx
2070 .get_ref(arg.pat.span)
2072 let locals = bcx.fcx.lllocals.borrow();
2074 pat_util::pat_bindings(&arg.pat, |_, node_id, span, var_name| {
2075 let datum = match locals.get(&node_id) {
2078 span_bug!(span, "no entry in lllocals table for {}", node_id);
2082 if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
2083 span_bug!(span, "debuginfo::create_argument_metadata() - \
2084 Referenced variable location is not an alloca!");
2087 let argument_index = {
2093 let argument_index = counter.get();
2094 counter.set(argument_index + 1);
2102 VariableAccess::DirectVariable { alloca: datum.val },
2103 VariableKind::ArgumentVariable(argument_index),