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::namespace_for_item;
20 use super::type_names::{compute_debuginfo_type_name, push_debuginfo_type_name};
21 use super::{declare_local, VariableKind, VariableAccess};
23 use llvm::{self, ValueRef};
24 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor, DICompositeType};
26 use metadata::csearch;
28 use middle::subst::{self, Substs};
31 use trans::{type_of, adt, machine, monomorphize};
32 use trans::common::{self, CrateContext, FunctionContext, Block};
33 use trans::_match::{BindingInfo, TrByCopy, TrByMove, TrByRef};
34 use trans::type_::Type;
35 use middle::ty::{self, Ty};
36 use session::config::{self, FullDebugInfo};
37 use util::nodemap::FnvHashMap;
38 use util::common::path2cstr;
40 use libc::{c_uint, c_longlong};
41 use std::ffi::CString;
45 use syntax::util::interner::Interner;
46 use syntax::codemap::Span;
47 use syntax::{ast, codemap, ast_util};
48 use syntax::parse::token::{self, special_idents};
51 const DW_LANG_RUST: c_uint = 0x9000;
52 #[allow(non_upper_case_globals)]
53 const DW_ATE_boolean: c_uint = 0x02;
54 #[allow(non_upper_case_globals)]
55 const DW_ATE_float: c_uint = 0x04;
56 #[allow(non_upper_case_globals)]
57 const DW_ATE_signed: c_uint = 0x05;
58 #[allow(non_upper_case_globals)]
59 const DW_ATE_unsigned: c_uint = 0x07;
60 #[allow(non_upper_case_globals)]
61 const DW_ATE_unsigned_char: c_uint = 0x08;
63 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
64 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
66 // ptr::null() doesn't work :(
67 const UNKNOWN_FILE_METADATA: DIFile = (0 as DIFile);
68 const UNKNOWN_SCOPE_METADATA: DIScope = (0 as DIScope);
70 const FLAGS_NONE: c_uint = 0;
72 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
73 pub struct UniqueTypeId(ast::Name);
75 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
76 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
77 // faster lookup, also by Ty. The TypeMap is responsible for creating
79 pub struct TypeMap<'tcx> {
80 // The UniqueTypeIds created so far
81 unique_id_interner: Interner<Rc<String>>,
82 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
83 unique_id_to_metadata: FnvHashMap<UniqueTypeId, DIType>,
84 // A map from types to debuginfo metadata. This is a N:1 mapping.
85 type_to_metadata: FnvHashMap<Ty<'tcx>, DIType>,
86 // A map from types to UniqueTypeId. This is a N:1 mapping.
87 type_to_unique_id: FnvHashMap<Ty<'tcx>, UniqueTypeId>
90 impl<'tcx> TypeMap<'tcx> {
91 pub fn new() -> TypeMap<'tcx> {
93 unique_id_interner: Interner::new(),
94 type_to_metadata: FnvHashMap(),
95 unique_id_to_metadata: FnvHashMap(),
96 type_to_unique_id: FnvHashMap(),
100 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
101 // the mapping already exists.
102 fn register_type_with_metadata<'a>(&mut self,
103 cx: &CrateContext<'a, 'tcx>,
106 if self.type_to_metadata.insert(type_, metadata).is_some() {
107 cx.sess().bug(&format!("Type metadata for Ty '{}' is already in the TypeMap!",
112 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
113 // fail if the mapping already exists.
114 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 cx.sess().bug(&format!("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_id, substs) => {
183 unique_type_id.push_str("enum ");
184 from_def_id_and_substs(self, cx, def_id, substs, &mut unique_type_id);
186 ty::TyStruct(def_id, substs) => {
187 unique_type_id.push_str("struct ");
188 from_def_id_and_substs(self, cx, def_id, substs, &mut unique_type_id);
190 ty::TyTuple(ref component_types) if component_types.is_empty() => {
191 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
193 ty::TyTuple(ref 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::mt { ty: inner_type, mutbl } ) => {
210 unique_type_id.push('*');
211 if mutbl == ast::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::mt { ty: inner_type, mutbl }) => {
220 unique_type_id.push('&');
221 if mutbl == ast::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::TyBareFn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => {
255 if unsafety == ast::Unsafety::Unsafe {
256 unique_type_id.push_str("unsafe ");
259 unique_type_id.push_str(abi.name());
261 unique_type_id.push_str(" fn(");
263 let sig = cx.tcx().erase_late_bound_regions(sig);
265 for ¶meter_type in &sig.inputs {
266 let parameter_type_id =
267 self.get_unique_type_id_of_type(cx, parameter_type);
268 let parameter_type_id =
269 self.get_unique_type_id_as_string(parameter_type_id);
270 unique_type_id.push_str(¶meter_type_id[..]);
271 unique_type_id.push(',');
275 unique_type_id.push_str("...");
278 unique_type_id.push_str(")->");
280 ty::FnConverging(ret_ty) => {
281 let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
282 let return_type_id = self.get_unique_type_id_as_string(return_type_id);
283 unique_type_id.push_str(&return_type_id[..]);
286 unique_type_id.push_str("!");
290 ty::TyClosure(def_id, substs) => {
291 let infcx = infer::normalizing_infer_ctxt(cx.tcx(), &cx.tcx().tables);
292 let closure_ty = infcx.closure_type(def_id, substs);
293 self.get_unique_type_id_of_closure_type(cx,
295 &mut unique_type_id);
298 cx.sess().bug(&format!("get_unique_type_id_of_type() - unexpected type: {:?}",
303 unique_type_id.push('}');
305 // Trim to size before storing permanently
306 unique_type_id.shrink_to_fit();
308 let key = self.unique_id_interner.intern(Rc::new(unique_type_id));
309 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
311 return UniqueTypeId(key);
313 fn from_def_id_and_substs<'a, 'tcx>(type_map: &mut TypeMap<'tcx>,
314 cx: &CrateContext<'a, 'tcx>,
316 substs: &subst::Substs<'tcx>,
317 output: &mut String) {
318 // First, find out the 'real' def_id of the type. Items inlined from
319 // other crates have to be mapped back to their source.
320 let source_def_id = if def_id.krate == ast::LOCAL_CRATE {
321 match cx.external_srcs().borrow().get(&def_id.node).cloned() {
322 Some(source_def_id) => {
323 // The given def_id identifies the inlined copy of a
324 // type definition, let's take the source of the copy.
333 // Get the crate hash as first part of the identifier.
334 let crate_hash = if source_def_id.krate == ast::LOCAL_CRATE {
335 cx.link_meta().crate_hash.clone()
337 cx.sess().cstore.get_crate_hash(source_def_id.krate)
340 output.push_str(crate_hash.as_str());
341 output.push_str("/");
342 output.push_str(&format!("{:x}", def_id.node));
344 // Maybe check that there is no self type here.
346 let tps = substs.types.get_slice(subst::TypeSpace);
350 for &type_parameter in tps {
352 type_map.get_unique_type_id_of_type(cx, type_parameter);
354 type_map.get_unique_type_id_as_string(param_type_id);
355 output.push_str(¶m_type_id[..]);
364 fn get_unique_type_id_of_closure_type<'a>(&mut self,
365 cx: &CrateContext<'a, 'tcx>,
366 closure_ty: ty::ClosureTy<'tcx>,
367 unique_type_id: &mut String) {
368 let ty::ClosureTy { unsafety,
370 abi: _ } = closure_ty;
372 if unsafety == ast::Unsafety::Unsafe {
373 unique_type_id.push_str("unsafe ");
376 unique_type_id.push_str("|");
378 let sig = cx.tcx().erase_late_bound_regions(sig);
380 for ¶meter_type in &sig.inputs {
381 let parameter_type_id =
382 self.get_unique_type_id_of_type(cx, parameter_type);
383 let parameter_type_id =
384 self.get_unique_type_id_as_string(parameter_type_id);
385 unique_type_id.push_str(¶meter_type_id[..]);
386 unique_type_id.push(',');
390 unique_type_id.push_str("...");
393 unique_type_id.push_str("|->");
396 ty::FnConverging(ret_ty) => {
397 let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
398 let return_type_id = self.get_unique_type_id_as_string(return_type_id);
399 unique_type_id.push_str(&return_type_id[..]);
402 unique_type_id.push_str("!");
407 // Get the UniqueTypeId for an enum variant. Enum variants are not really
408 // types of their own, so they need special handling. We still need a
409 // UniqueTypeId for them, since to debuginfo they *are* real types.
410 fn get_unique_type_id_of_enum_variant<'a>(&mut self,
411 cx: &CrateContext<'a, 'tcx>,
415 let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
416 let enum_variant_type_id = format!("{}::{}",
417 &self.get_unique_type_id_as_string(enum_type_id),
419 let interner_key = self.unique_id_interner.intern(Rc::new(enum_variant_type_id));
420 UniqueTypeId(interner_key)
424 // A description of some recursive type. It can either be already finished (as
425 // with FinalMetadata) or it is not yet finished, but contains all information
426 // needed to generate the missing parts of the description. See the
427 // documentation section on Recursive Types at the top of this file for more
429 enum RecursiveTypeDescription<'tcx> {
431 unfinished_type: Ty<'tcx>,
432 unique_type_id: UniqueTypeId,
433 metadata_stub: DICompositeType,
435 member_description_factory: MemberDescriptionFactory<'tcx>,
437 FinalMetadata(DICompositeType)
440 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
441 cx: &CrateContext<'a, 'tcx>,
442 unfinished_type: Ty<'tcx>,
443 unique_type_id: UniqueTypeId,
444 metadata_stub: DICompositeType,
446 member_description_factory: MemberDescriptionFactory<'tcx>)
447 -> RecursiveTypeDescription<'tcx> {
449 // Insert the stub into the TypeMap in order to allow for recursive references
450 let mut type_map = debug_context(cx).type_map.borrow_mut();
451 type_map.register_unique_id_with_metadata(cx, unique_type_id, metadata_stub);
452 type_map.register_type_with_metadata(cx, unfinished_type, metadata_stub);
455 unfinished_type: unfinished_type,
456 unique_type_id: unique_type_id,
457 metadata_stub: metadata_stub,
458 llvm_type: llvm_type,
459 member_description_factory: member_description_factory,
463 impl<'tcx> RecursiveTypeDescription<'tcx> {
464 // Finishes up the description of the type in question (mostly by providing
465 // descriptions of the fields of the given type) and returns the final type
467 fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
469 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
475 ref member_description_factory,
478 // Make sure that we have a forward declaration of the type in
479 // the TypeMap so that recursive references are possible. This
480 // will always be the case if the RecursiveTypeDescription has
481 // been properly created through the
482 // create_and_register_recursive_type_forward_declaration()
485 let type_map = debug_context(cx).type_map.borrow();
486 if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
487 type_map.find_metadata_for_type(unfinished_type).is_none() {
488 cx.sess().bug(&format!("Forward declaration of potentially recursive type \
489 '{:?}' was not found in TypeMap!",
495 // ... then create the member descriptions ...
496 let member_descriptions =
497 member_description_factory.create_member_descriptions(cx);
499 // ... and attach them to the stub to complete it.
500 set_members_of_composite_type(cx,
503 &member_descriptions[..]);
504 return MetadataCreationResult::new(metadata_stub, true);
510 // Returns from the enclosing function if the type metadata with the given
511 // unique id can be found in the type map
512 macro_rules! return_if_metadata_created_in_meantime {
513 ($cx: expr, $unique_type_id: expr) => (
514 match debug_context($cx).type_map
516 .find_metadata_for_unique_id($unique_type_id) {
517 Some(metadata) => return MetadataCreationResult::new(metadata, true),
518 None => { /* proceed normally */ }
523 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
524 unique_type_id: UniqueTypeId,
525 element_type: Ty<'tcx>,
528 -> MetadataCreationResult {
529 let element_type_metadata = type_metadata(cx, element_type, span);
531 return_if_metadata_created_in_meantime!(cx, unique_type_id);
533 let element_llvm_type = type_of::type_of(cx, element_type);
534 let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
536 let (array_size_in_bytes, upper_bound) = match len {
537 Some(len) => (element_type_size * len, len as c_longlong),
541 let subrange = unsafe {
542 llvm::LLVMDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
545 let subscripts = create_DIArray(DIB(cx), &[subrange]);
546 let metadata = unsafe {
547 llvm::LLVMDIBuilderCreateArrayType(
549 bytes_to_bits(array_size_in_bytes),
550 bytes_to_bits(element_type_align),
551 element_type_metadata,
555 return MetadataCreationResult::new(metadata, false);
558 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
560 element_type: Ty<'tcx>,
561 unique_type_id: UniqueTypeId,
563 -> MetadataCreationResult {
564 let data_ptr_type = cx.tcx().mk_ptr(ty::mt {
566 mutbl: ast::MutImmutable
569 let element_type_metadata = type_metadata(cx, data_ptr_type, span);
571 return_if_metadata_created_in_meantime!(cx, unique_type_id);
573 let slice_llvm_type = type_of::type_of(cx, vec_type);
574 let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
576 let member_llvm_types = slice_llvm_type.field_types();
577 assert!(slice_layout_is_correct(cx,
578 &member_llvm_types[..],
580 let member_descriptions = [
582 name: "data_ptr".to_string(),
583 llvm_type: member_llvm_types[0],
584 type_metadata: element_type_metadata,
585 offset: ComputedMemberOffset,
589 name: "length".to_string(),
590 llvm_type: member_llvm_types[1],
591 type_metadata: type_metadata(cx, cx.tcx().types.usize, span),
592 offset: ComputedMemberOffset,
597 assert!(member_descriptions.len() == member_llvm_types.len());
599 let loc = span_start(cx, span);
600 let file_metadata = file_metadata(cx, &loc.file.name);
602 let metadata = composite_type_metadata(cx,
604 &slice_type_name[..],
606 &member_descriptions,
607 UNKNOWN_SCOPE_METADATA,
610 return MetadataCreationResult::new(metadata, false);
612 fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
613 member_llvm_types: &[Type],
614 element_type: Ty<'tcx>)
616 member_llvm_types.len() == 2 &&
617 member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
618 member_llvm_types[1] == cx.int_type()
622 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
623 unique_type_id: UniqueTypeId,
624 signature: &ty::PolyFnSig<'tcx>,
626 -> MetadataCreationResult
628 let signature = cx.tcx().erase_late_bound_regions(signature);
630 let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs.len() + 1);
633 signature_metadata.push(match signature.output {
634 ty::FnConverging(ret_ty) => match ret_ty.sty {
635 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
636 _ => type_metadata(cx, ret_ty, span)
638 ty::FnDiverging => diverging_type_metadata(cx)
642 for &argument_type in &signature.inputs {
643 signature_metadata.push(type_metadata(cx, argument_type, span));
646 return_if_metadata_created_in_meantime!(cx, unique_type_id);
648 return MetadataCreationResult::new(
650 llvm::LLVMDIBuilderCreateSubroutineType(
652 UNKNOWN_FILE_METADATA,
653 create_DIArray(DIB(cx), &signature_metadata[..]))
658 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
659 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
660 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
661 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
662 // of a DST struct, there is no trait_object_type and the results of this
663 // function will be a little bit weird.
664 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
665 trait_type: Ty<'tcx>,
666 trait_object_type: Option<Ty<'tcx>>,
667 unique_type_id: UniqueTypeId)
669 // The implementation provided here is a stub. It makes sure that the trait
670 // type is assigned the correct name, size, namespace, and source location.
671 // But it does not describe the trait's methods.
673 let def_id = match trait_type.sty {
674 ty::TyTrait(ref data) => data.principal_def_id(),
676 cx.sess().bug(&format!("debuginfo: Unexpected trait-object type in \
677 trait_pointer_metadata(): {:?}",
682 let trait_object_type = trait_object_type.unwrap_or(trait_type);
683 let trait_type_name =
684 compute_debuginfo_type_name(cx, trait_object_type, false);
686 let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
688 let trait_llvm_type = type_of::type_of(cx, trait_object_type);
690 composite_type_metadata(cx,
692 &trait_type_name[..],
696 UNKNOWN_FILE_METADATA,
700 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
702 usage_site_span: Span)
704 // Get the unique type id of this type.
705 let unique_type_id = {
706 let mut type_map = debug_context(cx).type_map.borrow_mut();
707 // First, try to find the type in TypeMap. If we have seen it before, we
708 // can exit early here.
709 match type_map.find_metadata_for_type(t) {
714 // The Ty is not in the TypeMap but maybe we have already seen
715 // an equivalent type (e.g. only differing in region arguments).
716 // In order to find out, generate the unique type id and look
718 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
719 match type_map.find_metadata_for_unique_id(unique_type_id) {
721 // There is already an equivalent type in the TypeMap.
722 // Register this Ty as an alias in the cache and
723 // return the cached metadata.
724 type_map.register_type_with_metadata(cx, t, metadata);
728 // There really is no type metadata for this type, so
729 // proceed by creating it.
737 debug!("type_metadata: {:?}", t);
740 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
746 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
748 ty::TyTuple(ref elements) if elements.is_empty() => {
749 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
751 ty::TyEnum(def_id, _) => {
752 prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span).finalize(cx)
754 ty::TyArray(typ, len) => {
755 fixed_vec_metadata(cx, unique_type_id, typ, Some(len as u64), usage_site_span)
757 ty::TySlice(typ) => {
758 fixed_vec_metadata(cx, unique_type_id, typ, None, usage_site_span)
761 fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
764 MetadataCreationResult::new(
765 trait_pointer_metadata(cx, t, None, unique_type_id),
768 ty::TyBox(ty) | ty::TyRawPtr(ty::mt{ty, ..}) | ty::TyRef(_, ty::mt{ty, ..}) => {
770 ty::TySlice(typ) => {
771 vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
774 vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span)
777 MetadataCreationResult::new(
778 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
782 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
784 match debug_context(cx).type_map
786 .find_metadata_for_unique_id(unique_type_id) {
787 Some(metadata) => return metadata,
788 None => { /* proceed normally */ }
791 MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
796 ty::TyBareFn(_, ref barefnty) => {
797 subroutine_type_metadata(cx, unique_type_id, &barefnty.sig, usage_site_span)
799 ty::TyClosure(def_id, substs) => {
800 let infcx = infer::normalizing_infer_ctxt(cx.tcx(), &cx.tcx().tables);
801 let sig = infcx.closure_type(def_id, substs).sig;
802 subroutine_type_metadata(cx, unique_type_id, &sig, usage_site_span)
804 ty::TyStruct(def_id, substs) => {
805 prepare_struct_metadata(cx,
810 usage_site_span).finalize(cx)
812 ty::TyTuple(ref elements) => {
813 prepare_tuple_metadata(cx,
817 usage_site_span).finalize(cx)
820 cx.sess().bug(&format!("debuginfo: unexpected type in type_metadata: {:?}",
826 let mut type_map = debug_context(cx).type_map.borrow_mut();
828 if already_stored_in_typemap {
829 // Also make sure that we already have a TypeMap entry entry for the unique type id.
830 let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
831 Some(metadata) => metadata,
833 let unique_type_id_str =
834 type_map.get_unique_type_id_as_string(unique_type_id);
835 let error_message = format!("Expected type metadata for unique \
836 type id '{}' to already be in \
837 the debuginfo::TypeMap but it \
839 &unique_type_id_str[..],
841 cx.sess().span_bug(usage_site_span, &error_message[..]);
845 match type_map.find_metadata_for_type(t) {
847 if metadata != metadata_for_uid {
848 let unique_type_id_str =
849 type_map.get_unique_type_id_as_string(unique_type_id);
850 let error_message = format!("Mismatch between Ty and \
851 UniqueTypeId maps in \
852 debuginfo::TypeMap. \
853 UniqueTypeId={}, Ty={}",
854 &unique_type_id_str[..],
856 cx.sess().span_bug(usage_site_span, &error_message[..]);
860 type_map.register_type_with_metadata(cx, t, metadata);
864 type_map.register_type_with_metadata(cx, t, metadata);
865 type_map.register_unique_id_with_metadata(cx, unique_type_id, metadata);
872 pub fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile {
873 match debug_context(cx).created_files.borrow().get(full_path) {
874 Some(file_metadata) => return *file_metadata,
878 debug!("file_metadata: {}", full_path);
880 // FIXME (#9639): This needs to handle non-utf8 paths
881 let work_dir = cx.sess().working_dir.to_str().unwrap();
883 if full_path.starts_with(work_dir) {
884 &full_path[work_dir.len() + 1..full_path.len()]
889 let file_name = CString::new(file_name).unwrap();
890 let work_dir = CString::new(work_dir).unwrap();
891 let file_metadata = unsafe {
892 llvm::LLVMDIBuilderCreateFile(DIB(cx), file_name.as_ptr(),
896 let mut created_files = debug_context(cx).created_files.borrow_mut();
897 created_files.insert(full_path.to_string(), file_metadata);
898 return file_metadata;
901 /// Finds the scope metadata node for the given AST node.
902 pub fn scope_metadata(fcx: &FunctionContext,
903 node_id: ast::NodeId,
904 error_reporting_span: Span)
906 let scope_map = &fcx.debug_context
907 .get_ref(fcx.ccx, error_reporting_span)
909 match scope_map.borrow().get(&node_id).cloned() {
910 Some(scope_metadata) => scope_metadata,
912 let node = fcx.ccx.tcx().map.get(node_id);
914 fcx.ccx.sess().span_bug(error_reporting_span,
915 &format!("debuginfo: Could not find scope info for node {:?}",
921 fn diverging_type_metadata(cx: &CrateContext) -> DIType {
923 llvm::LLVMDIBuilderCreateBasicType(
925 "!\0".as_ptr() as *const _,
932 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
933 t: Ty<'tcx>) -> DIType {
935 debug!("basic_type_metadata: {:?}", t);
937 let (name, encoding) = match t.sty {
938 ty::TyTuple(ref elements) if elements.is_empty() =>
939 ("()".to_string(), DW_ATE_unsigned),
940 ty::TyBool => ("bool".to_string(), DW_ATE_boolean),
941 ty::TyChar => ("char".to_string(), DW_ATE_unsigned_char),
942 ty::TyInt(int_ty) => match int_ty {
943 ast::TyIs => ("isize".to_string(), DW_ATE_signed),
944 ast::TyI8 => ("i8".to_string(), DW_ATE_signed),
945 ast::TyI16 => ("i16".to_string(), DW_ATE_signed),
946 ast::TyI32 => ("i32".to_string(), DW_ATE_signed),
947 ast::TyI64 => ("i64".to_string(), DW_ATE_signed)
949 ty::TyUint(uint_ty) => match uint_ty {
950 ast::TyUs => ("usize".to_string(), DW_ATE_unsigned),
951 ast::TyU8 => ("u8".to_string(), DW_ATE_unsigned),
952 ast::TyU16 => ("u16".to_string(), DW_ATE_unsigned),
953 ast::TyU32 => ("u32".to_string(), DW_ATE_unsigned),
954 ast::TyU64 => ("u64".to_string(), DW_ATE_unsigned)
956 ty::TyFloat(float_ty) => match float_ty {
957 ast::TyF32 => ("f32".to_string(), DW_ATE_float),
958 ast::TyF64 => ("f64".to_string(), DW_ATE_float),
960 _ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type")
963 let llvm_type = type_of::type_of(cx, t);
964 let (size, align) = size_and_align_of(cx, llvm_type);
965 let name = CString::new(name).unwrap();
966 let ty_metadata = unsafe {
967 llvm::LLVMDIBuilderCreateBasicType(
971 bytes_to_bits(align),
978 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
979 pointer_type: Ty<'tcx>,
980 pointee_type_metadata: DIType)
982 let pointer_llvm_type = type_of::type_of(cx, pointer_type);
983 let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
984 let name = compute_debuginfo_type_name(cx, pointer_type, false);
985 let name = CString::new(name).unwrap();
986 let ptr_metadata = unsafe {
987 llvm::LLVMDIBuilderCreatePointerType(
989 pointee_type_metadata,
990 bytes_to_bits(pointer_size),
991 bytes_to_bits(pointer_align),
997 pub fn compile_unit_metadata(cx: &CrateContext) -> DIDescriptor {
998 let work_dir = &cx.sess().working_dir;
999 let compile_unit_name = match cx.sess().local_crate_source_file {
1000 None => fallback_path(cx),
1001 Some(ref abs_path) => {
1002 if abs_path.is_relative() {
1003 cx.sess().warn("debuginfo: Invalid path to crate's local root source file!");
1006 match abs_path.relative_from(work_dir) {
1007 Some(ref p) if p.is_relative() => {
1008 if p.starts_with(Path::new("./")) {
1011 path2cstr(&Path::new(".").join(p))
1014 _ => fallback_path(cx)
1020 debug!("compile_unit_metadata: {:?}", compile_unit_name);
1021 let producer = format!("rustc version {}",
1022 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
1024 let compile_unit_name = compile_unit_name.as_ptr();
1025 let work_dir = path2cstr(&work_dir);
1026 let producer = CString::new(producer).unwrap();
1028 let split_name = "\0";
1030 llvm::LLVMDIBuilderCreateCompileUnit(
1031 debug_context(cx).builder,
1036 cx.sess().opts.optimize != config::No,
1037 flags.as_ptr() as *const _,
1039 split_name.as_ptr() as *const _)
1042 fn fallback_path(cx: &CrateContext) -> CString {
1043 CString::new(cx.link_meta().crate_name.clone()).unwrap()
1047 struct MetadataCreationResult {
1049 already_stored_in_typemap: bool
1052 impl MetadataCreationResult {
1053 fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
1054 MetadataCreationResult {
1056 already_stored_in_typemap: already_stored_in_typemap
1063 FixedMemberOffset { bytes: usize },
1064 // For ComputedMemberOffset, the offset is read from the llvm type definition.
1065 ComputedMemberOffset
1068 // Description of a type member, which can either be a regular field (as in
1069 // structs or tuples) or an enum variant.
1071 struct MemberDescription {
1074 type_metadata: DIType,
1075 offset: MemberOffset,
1079 // A factory for MemberDescriptions. It produces a list of member descriptions
1080 // for some record-like type. MemberDescriptionFactories are used to defer the
1081 // creation of type member descriptions in order to break cycles arising from
1082 // recursive type definitions.
1083 enum MemberDescriptionFactory<'tcx> {
1084 StructMDF(StructMemberDescriptionFactory<'tcx>),
1085 TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1086 EnumMDF(EnumMemberDescriptionFactory<'tcx>),
1087 VariantMDF(VariantMemberDescriptionFactory<'tcx>)
1090 impl<'tcx> MemberDescriptionFactory<'tcx> {
1091 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1092 -> Vec<MemberDescription> {
1094 StructMDF(ref this) => {
1095 this.create_member_descriptions(cx)
1097 TupleMDF(ref this) => {
1098 this.create_member_descriptions(cx)
1100 EnumMDF(ref this) => {
1101 this.create_member_descriptions(cx)
1103 VariantMDF(ref this) => {
1104 this.create_member_descriptions(cx)
1110 //=-----------------------------------------------------------------------------
1112 //=-----------------------------------------------------------------------------
1114 // Creates MemberDescriptions for the fields of a struct
1115 struct StructMemberDescriptionFactory<'tcx> {
1116 fields: Vec<ty::field<'tcx>>,
1121 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1122 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1123 -> Vec<MemberDescription> {
1124 if self.fields.is_empty() {
1128 let field_size = if self.is_simd {
1129 machine::llsize_of_alloc(cx, type_of::type_of(cx, self.fields[0].mt.ty)) as usize
1134 self.fields.iter().enumerate().map(|(i, field)| {
1135 let name = if field.name == special_idents::unnamed_field.name {
1138 token::get_name(field.name).to_string()
1141 let offset = if self.is_simd {
1142 assert!(field_size != 0xdeadbeef);
1143 FixedMemberOffset { bytes: i * field_size }
1145 ComputedMemberOffset
1150 llvm_type: type_of::type_of(cx, field.mt.ty),
1151 type_metadata: type_metadata(cx, field.mt.ty, self.span),
1160 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1161 struct_type: Ty<'tcx>,
1163 substs: &subst::Substs<'tcx>,
1164 unique_type_id: UniqueTypeId,
1166 -> RecursiveTypeDescription<'tcx> {
1167 let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
1168 let struct_llvm_type = type_of::in_memory_type_of(cx, struct_type);
1170 let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
1172 let struct_metadata_stub = create_struct_stub(cx,
1178 let mut fields = cx.tcx().struct_fields(def_id, substs);
1180 // The `Ty` values returned by `ty::struct_fields` can still contain
1181 // `TyProjection` variants, so normalize those away.
1182 for field in &mut fields {
1183 field.mt.ty = monomorphize::normalize_associated_type(cx.tcx(), &field.mt.ty);
1186 create_and_register_recursive_type_forward_declaration(
1190 struct_metadata_stub,
1192 StructMDF(StructMemberDescriptionFactory {
1194 is_simd: struct_type.is_simd(cx.tcx()),
1201 //=-----------------------------------------------------------------------------
1203 //=-----------------------------------------------------------------------------
1205 // Creates MemberDescriptions for the fields of a tuple
1206 struct TupleMemberDescriptionFactory<'tcx> {
1207 component_types: Vec<Ty<'tcx>>,
1211 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1212 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1213 -> Vec<MemberDescription> {
1214 self.component_types
1217 .map(|(i, &component_type)| {
1219 name: format!("__{}", i),
1220 llvm_type: type_of::type_of(cx, component_type),
1221 type_metadata: type_metadata(cx, component_type, self.span),
1222 offset: ComputedMemberOffset,
1229 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1230 tuple_type: Ty<'tcx>,
1231 component_types: &[Ty<'tcx>],
1232 unique_type_id: UniqueTypeId,
1234 -> RecursiveTypeDescription<'tcx> {
1235 let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
1236 let tuple_llvm_type = type_of::type_of(cx, tuple_type);
1238 create_and_register_recursive_type_forward_declaration(
1242 create_struct_stub(cx,
1246 UNKNOWN_SCOPE_METADATA),
1248 TupleMDF(TupleMemberDescriptionFactory {
1249 component_types: component_types.to_vec(),
1256 //=-----------------------------------------------------------------------------
1258 //=-----------------------------------------------------------------------------
1260 // Describes the members of an enum value: An enum is described as a union of
1261 // structs in DWARF. This MemberDescriptionFactory provides the description for
1262 // the members of this union; so for every variant of the given enum, this
1263 // factory will produce one MemberDescription (all with no name and a fixed
1264 // offset of zero bytes).
1265 struct EnumMemberDescriptionFactory<'tcx> {
1266 enum_type: Ty<'tcx>,
1267 type_rep: Rc<adt::Repr<'tcx>>,
1268 variants: Rc<Vec<Rc<ty::VariantInfo<'tcx>>>>,
1269 discriminant_type_metadata: Option<DIType>,
1270 containing_scope: DIScope,
1271 file_metadata: DIFile,
1275 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
1276 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1277 -> Vec<MemberDescription> {
1278 match *self.type_rep {
1279 adt::General(_, ref struct_defs, _) => {
1280 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
1286 .map(|(i, struct_def)| {
1287 let (variant_type_metadata,
1289 member_desc_factory) =
1290 describe_enum_variant(cx,
1293 &*(*self.variants)[i],
1295 self.containing_scope,
1298 let member_descriptions = member_desc_factory
1299 .create_member_descriptions(cx);
1301 set_members_of_composite_type(cx,
1302 variant_type_metadata,
1304 &member_descriptions);
1306 name: "".to_string(),
1307 llvm_type: variant_llvm_type,
1308 type_metadata: variant_type_metadata,
1309 offset: FixedMemberOffset { bytes: 0 },
1314 adt::Univariant(ref struct_def, _) => {
1315 assert!(self.variants.len() <= 1);
1317 if self.variants.is_empty() {
1320 let (variant_type_metadata,
1322 member_description_factory) =
1323 describe_enum_variant(cx,
1326 &*(*self.variants)[0],
1328 self.containing_scope,
1331 let member_descriptions =
1332 member_description_factory.create_member_descriptions(cx);
1334 set_members_of_composite_type(cx,
1335 variant_type_metadata,
1337 &member_descriptions[..]);
1340 name: "".to_string(),
1341 llvm_type: variant_llvm_type,
1342 type_metadata: variant_type_metadata,
1343 offset: FixedMemberOffset { bytes: 0 },
1349 adt::RawNullablePointer { nndiscr: non_null_variant_index, nnty, .. } => {
1350 // As far as debuginfo is concerned, the pointer this enum
1351 // represents is still wrapped in a struct. This is to make the
1352 // DWARF representation of enums uniform.
1354 // First create a description of the artificial wrapper struct:
1355 let non_null_variant = &(*self.variants)[non_null_variant_index as usize];
1356 let non_null_variant_name = token::get_name(non_null_variant.name);
1358 // The llvm type and metadata of the pointer
1359 let non_null_llvm_type = type_of::type_of(cx, nnty);
1360 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
1362 // The type of the artificial struct wrapping the pointer
1363 let artificial_struct_llvm_type = Type::struct_(cx,
1364 &[non_null_llvm_type],
1367 // For the metadata of the wrapper struct, we need to create a
1368 // MemberDescription of the struct's single field.
1369 let sole_struct_member_description = MemberDescription {
1370 name: match non_null_variant.arg_names {
1371 Some(ref names) => token::get_name(names[0]).to_string(),
1372 None => "__0".to_string()
1374 llvm_type: non_null_llvm_type,
1375 type_metadata: non_null_type_metadata,
1376 offset: FixedMemberOffset { bytes: 0 },
1380 let unique_type_id = debug_context(cx).type_map
1382 .get_unique_type_id_of_enum_variant(
1385 &non_null_variant_name);
1387 // Now we can create the metadata of the artificial struct
1388 let artificial_struct_metadata =
1389 composite_type_metadata(cx,
1390 artificial_struct_llvm_type,
1391 &non_null_variant_name,
1393 &[sole_struct_member_description],
1394 self.containing_scope,
1398 // Encode the information about the null variant in the union
1400 let null_variant_index = (1 - non_null_variant_index) as usize;
1401 let null_variant_name = token::get_name((*self.variants)[null_variant_index].name);
1402 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1406 // Finally create the (singleton) list of descriptions of union
1410 name: union_member_name,
1411 llvm_type: artificial_struct_llvm_type,
1412 type_metadata: artificial_struct_metadata,
1413 offset: FixedMemberOffset { bytes: 0 },
1418 adt::StructWrappedNullablePointer { nonnull: ref struct_def,
1420 ref discrfield, ..} => {
1421 // Create a description of the non-null variant
1422 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
1423 describe_enum_variant(cx,
1426 &*(*self.variants)[nndiscr as usize],
1427 OptimizedDiscriminant,
1428 self.containing_scope,
1431 let variant_member_descriptions =
1432 member_description_factory.create_member_descriptions(cx);
1434 set_members_of_composite_type(cx,
1435 variant_type_metadata,
1437 &variant_member_descriptions[..]);
1439 // Encode the information about the null variant in the union
1441 let null_variant_index = (1 - nndiscr) as usize;
1442 let null_variant_name = token::get_name((*self.variants)[null_variant_index].name);
1443 let discrfield = discrfield.iter()
1445 .map(|x| x.to_string())
1446 .collect::<Vec<_>>().join("$");
1447 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1451 // Create the (singleton) list of descriptions of union members.
1454 name: union_member_name,
1455 llvm_type: variant_llvm_type,
1456 type_metadata: variant_type_metadata,
1457 offset: FixedMemberOffset { bytes: 0 },
1462 adt::CEnum(..) => cx.sess().span_bug(self.span, "This should be unreachable.")
1467 // Creates MemberDescriptions for the fields of a single enum variant.
1468 struct VariantMemberDescriptionFactory<'tcx> {
1469 args: Vec<(String, Ty<'tcx>)>,
1470 discriminant_type_metadata: Option<DIType>,
1474 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1475 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1476 -> Vec<MemberDescription> {
1477 self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
1479 name: name.to_string(),
1480 llvm_type: type_of::type_of(cx, ty),
1481 type_metadata: match self.discriminant_type_metadata {
1482 Some(metadata) if i == 0 => metadata,
1483 _ => type_metadata(cx, ty, self.span)
1485 offset: ComputedMemberOffset,
1492 #[derive(Copy, Clone)]
1493 enum EnumDiscriminantInfo {
1494 RegularDiscriminant(DIType),
1495 OptimizedDiscriminant,
1499 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
1500 // of the variant, and (3) a MemberDescriptionFactory for producing the
1501 // descriptions of the fields of the variant. This is a rudimentary version of a
1502 // full RecursiveTypeDescription.
1503 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1504 enum_type: Ty<'tcx>,
1505 struct_def: &adt::Struct<'tcx>,
1506 variant_info: &ty::VariantInfo<'tcx>,
1507 discriminant_info: EnumDiscriminantInfo,
1508 containing_scope: DIScope,
1510 -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1511 let variant_llvm_type =
1512 Type::struct_(cx, &struct_def.fields
1514 .map(|&t| type_of::type_of(cx, t))
1515 .collect::<Vec<_>>()
1518 // Could do some consistency checks here: size, align, field count, discr type
1520 let variant_name = token::get_name(variant_info.name);
1521 let variant_name = &variant_name;
1522 let unique_type_id = debug_context(cx).type_map
1524 .get_unique_type_id_of_enum_variant(
1529 let metadata_stub = create_struct_stub(cx,
1535 // Get the argument names from the enum variant info
1536 let mut arg_names: Vec<_> = match variant_info.arg_names {
1537 Some(ref names) => {
1539 .map(|&name| token::get_name(name).to_string())
1546 .map(|(i, _)| format!("__{}", i))
1551 // If this is not a univariant enum, there is also the discriminant field.
1552 match discriminant_info {
1553 RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
1554 _ => { /* do nothing */ }
1557 // Build an array of (field name, field type) pairs to be captured in the factory closure.
1558 let args: Vec<(String, Ty)> = arg_names.iter()
1559 .zip(&struct_def.fields)
1560 .map(|(s, &t)| (s.to_string(), t))
1563 let member_description_factory =
1564 VariantMDF(VariantMemberDescriptionFactory {
1566 discriminant_type_metadata: match discriminant_info {
1567 RegularDiscriminant(discriminant_type_metadata) => {
1568 Some(discriminant_type_metadata)
1575 (metadata_stub, variant_llvm_type, member_description_factory)
1578 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1579 enum_type: Ty<'tcx>,
1580 enum_def_id: ast::DefId,
1581 unique_type_id: UniqueTypeId,
1583 -> RecursiveTypeDescription<'tcx> {
1584 let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1586 let (containing_scope, definition_span) = get_namespace_and_span_for_item(cx, enum_def_id);
1587 let loc = span_start(cx, definition_span);
1588 let file_metadata = file_metadata(cx, &loc.file.name);
1590 let variants = cx.tcx().enum_variants(enum_def_id);
1592 let enumerators_metadata: Vec<DIDescriptor> = variants
1595 let token = token::get_name(v.name);
1596 let name = CString::new(token.as_bytes()).unwrap();
1598 llvm::LLVMDIBuilderCreateEnumerator(
1606 let discriminant_type_metadata = |inttype| {
1607 // We can reuse the type of the discriminant for all monomorphized
1608 // instances of an enum because it doesn't depend on any type
1609 // parameters. The def_id, uniquely identifying the enum's polytype acts
1610 // as key in this cache.
1611 let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
1613 .get(&enum_def_id).cloned();
1614 match cached_discriminant_type_metadata {
1615 Some(discriminant_type_metadata) => discriminant_type_metadata,
1617 let discriminant_llvm_type = adt::ll_inttype(cx, inttype);
1618 let (discriminant_size, discriminant_align) =
1619 size_and_align_of(cx, discriminant_llvm_type);
1620 let discriminant_base_type_metadata =
1622 adt::ty_of_inttype(cx.tcx(), inttype),
1624 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1626 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1627 let discriminant_type_metadata = unsafe {
1628 llvm::LLVMDIBuilderCreateEnumerationType(
1632 UNKNOWN_FILE_METADATA,
1633 UNKNOWN_LINE_NUMBER,
1634 bytes_to_bits(discriminant_size),
1635 bytes_to_bits(discriminant_align),
1636 create_DIArray(DIB(cx), &enumerators_metadata),
1637 discriminant_base_type_metadata)
1640 debug_context(cx).created_enum_disr_types
1642 .insert(enum_def_id, discriminant_type_metadata);
1644 discriminant_type_metadata
1649 let type_rep = adt::represent_type(cx, enum_type);
1651 let discriminant_type_metadata = match *type_rep {
1652 adt::CEnum(inttype, _, _) => {
1653 return FinalMetadata(discriminant_type_metadata(inttype))
1655 adt::RawNullablePointer { .. } |
1656 adt::StructWrappedNullablePointer { .. } |
1657 adt::Univariant(..) => None,
1658 adt::General(inttype, _, _) => Some(discriminant_type_metadata(inttype)),
1661 let enum_llvm_type = type_of::type_of(cx, enum_type);
1662 let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
1664 let unique_type_id_str = debug_context(cx)
1667 .get_unique_type_id_as_string(unique_type_id);
1669 let enum_name = CString::new(enum_name).unwrap();
1670 let unique_type_id_str = CString::new(unique_type_id_str.as_bytes()).unwrap();
1671 let enum_metadata = unsafe {
1672 llvm::LLVMDIBuilderCreateUnionType(
1677 UNKNOWN_LINE_NUMBER,
1678 bytes_to_bits(enum_type_size),
1679 bytes_to_bits(enum_type_align),
1683 unique_type_id_str.as_ptr())
1686 return create_and_register_recursive_type_forward_declaration(
1692 EnumMDF(EnumMemberDescriptionFactory {
1693 enum_type: enum_type,
1694 type_rep: type_rep.clone(),
1696 discriminant_type_metadata: discriminant_type_metadata,
1697 containing_scope: containing_scope,
1698 file_metadata: file_metadata,
1703 fn get_enum_discriminant_name(cx: &CrateContext,
1705 -> token::InternedString {
1706 let name = if def_id.krate == ast::LOCAL_CRATE {
1707 cx.tcx().map.get_path_elem(def_id.node).name()
1709 csearch::get_item_path(cx.tcx(), def_id).last().unwrap().name()
1712 token::get_name(name)
1716 /// Creates debug information for a composite type, that is, anything that
1717 /// results in a LLVM struct.
1719 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
1720 fn composite_type_metadata(cx: &CrateContext,
1721 composite_llvm_type: Type,
1722 composite_type_name: &str,
1723 composite_type_unique_id: UniqueTypeId,
1724 member_descriptions: &[MemberDescription],
1725 containing_scope: DIScope,
1727 // Ignore source location information as long as it
1728 // can't be reconstructed for non-local crates.
1729 _file_metadata: DIFile,
1730 _definition_span: Span)
1731 -> DICompositeType {
1732 // Create the (empty) struct metadata node ...
1733 let composite_type_metadata = create_struct_stub(cx,
1734 composite_llvm_type,
1735 composite_type_name,
1736 composite_type_unique_id,
1738 // ... and immediately create and add the member descriptions.
1739 set_members_of_composite_type(cx,
1740 composite_type_metadata,
1741 composite_llvm_type,
1742 member_descriptions);
1744 return composite_type_metadata;
1747 fn set_members_of_composite_type(cx: &CrateContext,
1748 composite_type_metadata: DICompositeType,
1749 composite_llvm_type: Type,
1750 member_descriptions: &[MemberDescription]) {
1751 // In some rare cases LLVM metadata uniquing would lead to an existing type
1752 // description being used instead of a new one created in
1753 // create_struct_stub. This would cause a hard to trace assertion in
1754 // DICompositeType::SetTypeArray(). The following check makes sure that we
1755 // get a better error message if this should happen again due to some
1758 let mut composite_types_completed =
1759 debug_context(cx).composite_types_completed.borrow_mut();
1760 if composite_types_completed.contains(&composite_type_metadata) {
1761 cx.sess().bug("debuginfo::set_members_of_composite_type() - \
1762 Already completed forward declaration re-encountered.");
1764 composite_types_completed.insert(composite_type_metadata);
1768 let member_metadata: Vec<DIDescriptor> = member_descriptions
1771 .map(|(i, member_description)| {
1772 let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
1773 let member_offset = match member_description.offset {
1774 FixedMemberOffset { bytes } => bytes as u64,
1775 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
1778 let member_name = member_description.name.as_bytes();
1779 let member_name = CString::new(member_name).unwrap();
1781 llvm::LLVMDIBuilderCreateMemberType(
1783 composite_type_metadata,
1784 member_name.as_ptr(),
1785 UNKNOWN_FILE_METADATA,
1786 UNKNOWN_LINE_NUMBER,
1787 bytes_to_bits(member_size),
1788 bytes_to_bits(member_align),
1789 bytes_to_bits(member_offset),
1790 member_description.flags,
1791 member_description.type_metadata)
1797 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1798 llvm::LLVMDICompositeTypeSetTypeArray(DIB(cx), composite_type_metadata, type_array);
1802 // A convenience wrapper around LLVMDIBuilderCreateStructType(). Does not do any
1803 // caching, does not add any fields to the struct. This can be done later with
1804 // set_members_of_composite_type().
1805 fn create_struct_stub(cx: &CrateContext,
1806 struct_llvm_type: Type,
1807 struct_type_name: &str,
1808 unique_type_id: UniqueTypeId,
1809 containing_scope: DIScope)
1810 -> DICompositeType {
1811 let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
1813 let unique_type_id_str = debug_context(cx).type_map
1815 .get_unique_type_id_as_string(unique_type_id);
1816 let name = CString::new(struct_type_name).unwrap();
1817 let unique_type_id = CString::new(unique_type_id_str.as_bytes()).unwrap();
1818 let metadata_stub = unsafe {
1819 // LLVMDIBuilderCreateStructType() wants an empty array. A null
1820 // pointer will lead to hard to trace and debug LLVM assertions
1821 // later on in llvm/lib/IR/Value.cpp.
1822 let empty_array = create_DIArray(DIB(cx), &[]);
1824 llvm::LLVMDIBuilderCreateStructType(
1828 UNKNOWN_FILE_METADATA,
1829 UNKNOWN_LINE_NUMBER,
1830 bytes_to_bits(struct_size),
1831 bytes_to_bits(struct_align),
1837 unique_type_id.as_ptr())
1840 return metadata_stub;
1843 /// Creates debug information for the given global variable.
1845 /// Adds the created metadata nodes directly to the crate's IR.
1846 pub fn create_global_var_metadata(cx: &CrateContext,
1847 node_id: ast::NodeId,
1849 if cx.dbg_cx().is_none() {
1853 // Don't create debuginfo for globals inlined from other crates. The other
1854 // crate should already contain debuginfo for it. More importantly, the
1855 // global might not even exist in un-inlined form anywhere which would lead
1856 // to a linker errors.
1857 if cx.external_srcs().borrow().contains_key(&node_id) {
1861 let var_item = cx.tcx().map.get(node_id);
1863 let (name, span) = match var_item {
1864 ast_map::NodeItem(item) => {
1866 ast::ItemStatic(..) => (item.ident.name, item.span),
1867 ast::ItemConst(..) => (item.ident.name, item.span),
1870 .span_bug(item.span,
1871 &format!("debuginfo::\
1872 create_global_var_metadata() -
1873 Captured var-id refers to \
1874 unexpected ast_item variant: {:?}",
1879 _ => cx.sess().bug(&format!("debuginfo::create_global_var_metadata() \
1880 - Captured var-id refers to unexpected \
1881 ast_map variant: {:?}",
1885 let (file_metadata, line_number) = if span != codemap::DUMMY_SP {
1886 let loc = span_start(cx, span);
1887 (file_metadata(cx, &loc.file.name), loc.line as c_uint)
1889 (UNKNOWN_FILE_METADATA, UNKNOWN_LINE_NUMBER)
1892 let is_local_to_unit = is_node_local_to_unit(cx, node_id);
1893 let variable_type = cx.tcx().node_id_to_type(node_id);
1894 let type_metadata = type_metadata(cx, variable_type, span);
1895 let namespace_node = namespace_for_item(cx, ast_util::local_def(node_id));
1896 let var_name = token::get_name(name).to_string();
1898 namespace_node.mangled_name_of_contained_item(&var_name[..]);
1899 let var_scope = namespace_node.scope;
1901 let var_name = CString::new(var_name).unwrap();
1902 let linkage_name = CString::new(linkage_name).unwrap();
1904 llvm::LLVMDIBuilderCreateStaticVariable(DIB(cx),
1907 linkage_name.as_ptr(),
1917 /// Creates debug information for the given local variable.
1919 /// This function assumes that there's a datum for each pattern component of the
1920 /// local in `bcx.fcx.lllocals`.
1921 /// Adds the created metadata nodes directly to the crate's IR.
1922 pub fn create_local_var_metadata(bcx: Block, local: &ast::Local) {
1923 if bcx.unreachable.get() ||
1924 fn_should_be_ignored(bcx.fcx) ||
1925 bcx.sess().opts.debuginfo != FullDebugInfo {
1930 let def_map = &cx.tcx().def_map;
1931 let locals = bcx.fcx.lllocals.borrow();
1933 pat_util::pat_bindings(def_map, &*local.pat, |_, node_id, span, var_ident| {
1934 let datum = match locals.get(&node_id) {
1935 Some(datum) => datum,
1937 bcx.sess().span_bug(span,
1938 &format!("no entry in lllocals table for {}",
1943 if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
1944 cx.sess().span_bug(span, "debuginfo::create_local_var_metadata() - \
1945 Referenced variable location is not an alloca!");
1948 let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
1951 var_ident.node.name,
1954 VariableAccess::DirectVariable { alloca: datum.val },
1955 VariableKind::LocalVariable,
1960 /// Creates debug information for a variable captured in a closure.
1962 /// Adds the created metadata nodes directly to the crate's IR.
1963 pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1964 node_id: ast::NodeId,
1965 env_pointer: ValueRef,
1967 captured_by_ref: bool,
1969 if bcx.unreachable.get() ||
1970 fn_should_be_ignored(bcx.fcx) ||
1971 bcx.sess().opts.debuginfo != FullDebugInfo {
1977 let ast_item = cx.tcx().map.find(node_id);
1979 let variable_name = match ast_item {
1981 cx.sess().span_bug(span, "debuginfo::create_captured_var_metadata: node not found");
1983 Some(ast_map::NodeLocal(pat)) | Some(ast_map::NodeArg(pat)) => {
1985 ast::PatIdent(_, ref path1, _) => {
1992 "debuginfo::create_captured_var_metadata() - \
1993 Captured var-id refers to unexpected \
1994 ast_map variant: {:?}",
2002 &format!("debuginfo::create_captured_var_metadata() - \
2003 Captured var-id refers to unexpected \
2004 ast_map variant: {:?}",
2009 let variable_type = common::node_id_type(bcx, node_id);
2010 let scope_metadata = bcx.fcx.debug_context.get_ref(cx, span).fn_metadata;
2012 // env_pointer is the alloca containing the pointer to the environment,
2013 // so it's type is **EnvironmentType. In order to find out the type of
2014 // the environment we have to "dereference" two times.
2015 let llvm_env_data_type = common::val_ty(env_pointer).element_type()
2017 let byte_offset_of_var_in_env = machine::llelement_offset(cx,
2021 let address_operations = unsafe {
2022 [llvm::LLVMDIBuilderCreateOpDeref(),
2023 llvm::LLVMDIBuilderCreateOpPlus(),
2024 byte_offset_of_var_in_env as i64,
2025 llvm::LLVMDIBuilderCreateOpDeref()]
2028 let address_op_count = if captured_by_ref {
2029 address_operations.len()
2031 address_operations.len() - 1
2034 let variable_access = VariableAccess::IndirectVariable {
2035 alloca: env_pointer,
2036 address_operations: &address_operations[..address_op_count]
2044 VariableKind::CapturedVariable,
2048 /// Creates debug information for a local variable introduced in the head of a
2049 /// match-statement arm.
2051 /// Adds the created metadata nodes directly to the crate's IR.
2052 pub fn create_match_binding_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2053 variable_name: ast::Name,
2054 binding: BindingInfo<'tcx>) {
2055 if bcx.unreachable.get() ||
2056 fn_should_be_ignored(bcx.fcx) ||
2057 bcx.sess().opts.debuginfo != FullDebugInfo {
2061 let scope_metadata = scope_metadata(bcx.fcx, binding.id, binding.span);
2063 [llvm::LLVMDIBuilderCreateOpDeref()]
2065 // Regardless of the actual type (`T`) we're always passed the stack slot
2066 // (alloca) for the binding. For ByRef bindings that's a `T*` but for ByMove
2067 // bindings we actually have `T**`. So to get the actual variable we need to
2068 // dereference once more. For ByCopy we just use the stack slot we created
2070 let var_access = match binding.trmode {
2071 TrByCopy(llbinding) => VariableAccess::DirectVariable {
2074 TrByMove => VariableAccess::IndirectVariable {
2075 alloca: binding.llmatch,
2076 address_operations: &aops
2078 TrByRef => VariableAccess::DirectVariable {
2079 alloca: binding.llmatch
2088 VariableKind::LocalVariable,
2092 /// Creates debug information for the given function argument.
2094 /// This function assumes that there's a datum for each pattern component of the
2095 /// argument in `bcx.fcx.lllocals`.
2096 /// Adds the created metadata nodes directly to the crate's IR.
2097 pub fn create_argument_metadata(bcx: Block, arg: &ast::Arg) {
2098 if bcx.unreachable.get() ||
2099 fn_should_be_ignored(bcx.fcx) ||
2100 bcx.sess().opts.debuginfo != FullDebugInfo {
2104 let def_map = &bcx.tcx().def_map;
2105 let scope_metadata = bcx
2108 .get_ref(bcx.ccx(), arg.pat.span)
2110 let locals = bcx.fcx.lllocals.borrow();
2112 pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, span, var_ident| {
2113 let datum = match locals.get(&node_id) {
2116 bcx.sess().span_bug(span,
2117 &format!("no entry in lllocals table for {}",
2122 if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
2123 bcx.sess().span_bug(span, "debuginfo::create_argument_metadata() - \
2124 Referenced variable location is not an alloca!");
2127 let argument_index = {
2131 .get_ref(bcx.ccx(), span)
2133 let argument_index = counter.get();
2134 counter.set(argument_index + 1);
2139 var_ident.node.name,
2142 VariableAccess::DirectVariable { alloca: datum.val },
2143 VariableKind::ArgumentVariable(argument_index),