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}
;
29 use trans
::{type_of, adt, machine, monomorphize}
;
30 use trans
::common
::{self, CrateContext, FunctionContext, NormalizingClosureTyper, Block}
;
31 use trans
::_match
::{BindingInfo, TrByCopy, TrByMove, TrByRef}
;
32 use trans
::type_
::Type
;
33 use middle
::ty
::{self, Ty, ClosureTyper}
;
34 use session
::config
::{self, FullDebugInfo}
;
35 use util
::nodemap
::FnvHashMap
;
37 use util
::common
::path2cstr
;
39 use libc
::{c_uint, c_longlong}
;
40 use std
::ffi
::CString
;
44 use syntax
::util
::interner
::Interner
;
45 use syntax
::codemap
::Span
;
46 use syntax
::{ast, codemap, ast_util, ast_map}
;
47 use syntax
::parse
::token
::{self, special_idents}
;
50 const DW_LANG_RUST
: c_uint
= 0x9000;
51 #[allow(non_upper_case_globals)]
52 const DW_ATE_boolean
: c_uint
= 0x02;
53 #[allow(non_upper_case_globals)]
54 const DW_ATE_float
: c_uint
= 0x04;
55 #[allow(non_upper_case_globals)]
56 const DW_ATE_signed
: c_uint
= 0x05;
57 #[allow(non_upper_case_globals)]
58 const DW_ATE_unsigned
: c_uint
= 0x07;
59 #[allow(non_upper_case_globals)]
60 const DW_ATE_unsigned_char
: c_uint
= 0x08;
62 pub const UNKNOWN_LINE_NUMBER
: c_uint
= 0;
63 pub const UNKNOWN_COLUMN_NUMBER
: c_uint
= 0;
65 // ptr::null() doesn't work :(
66 const UNKNOWN_FILE_METADATA
: DIFile
= (0 as DIFile
);
67 const UNKNOWN_SCOPE_METADATA
: DIScope
= (0 as DIScope
);
69 const FLAGS_NONE
: c_uint
= 0;
71 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
72 pub struct UniqueTypeId(ast
::Name
);
74 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
75 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
76 // faster lookup, also by Ty. The TypeMap is responsible for creating
78 pub struct TypeMap
<'tcx
> {
79 // The UniqueTypeIds created so far
80 unique_id_interner
: Interner
<Rc
<String
>>,
81 // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
82 unique_id_to_metadata
: FnvHashMap
<UniqueTypeId
, DIType
>,
83 // A map from types to debuginfo metadata. This is a N:1 mapping.
84 type_to_metadata
: FnvHashMap
<Ty
<'tcx
>, DIType
>,
85 // A map from types to UniqueTypeId. This is a N:1 mapping.
86 type_to_unique_id
: FnvHashMap
<Ty
<'tcx
>, UniqueTypeId
>
89 impl<'tcx
> TypeMap
<'tcx
> {
90 pub fn new() -> TypeMap
<'tcx
> {
92 unique_id_interner
: Interner
::new(),
93 type_to_metadata
: FnvHashMap(),
94 unique_id_to_metadata
: FnvHashMap(),
95 type_to_unique_id
: FnvHashMap(),
99 // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
100 // the mapping already exists.
101 fn register_type_with_metadata
<'a
>(&mut self,
102 cx
: &CrateContext
<'a
, 'tcx
>,
105 if self.type_to_metadata
.insert(type_
, metadata
).is_some() {
106 cx
.sess().bug(&format
!("Type metadata for Ty '{}' is already in the TypeMap!",
107 ppaux
::ty_to_string(cx
.tcx(), type_
)));
111 // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
112 // fail if the mapping already exists.
113 fn register_unique_id_with_metadata(&mut self,
115 unique_type_id
: UniqueTypeId
,
117 if self.unique_id_to_metadata
.insert(unique_type_id
, metadata
).is_some() {
118 let unique_type_id_str
= self.get_unique_type_id_as_string(unique_type_id
);
119 cx
.sess().bug(&format
!("Type metadata for unique id '{}' is already in the TypeMap!",
120 &unique_type_id_str
[..]));
124 fn find_metadata_for_type(&self, type_
: Ty
<'tcx
>) -> Option
<DIType
> {
125 self.type_to_metadata
.get(&type_
).cloned()
128 fn find_metadata_for_unique_id(&self, unique_type_id
: UniqueTypeId
) -> Option
<DIType
> {
129 self.unique_id_to_metadata
.get(&unique_type_id
).cloned()
132 // Get the string representation of a UniqueTypeId. This method will fail if
133 // the id is unknown.
134 fn get_unique_type_id_as_string(&self, unique_type_id
: UniqueTypeId
) -> Rc
<String
> {
135 let UniqueTypeId(interner_key
) = unique_type_id
;
136 self.unique_id_interner
.get(interner_key
)
139 // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
140 // type has been requested before, this is just a table lookup. Otherwise an
141 // ID will be generated and stored for later lookup.
142 fn get_unique_type_id_of_type
<'a
>(&mut self, cx
: &CrateContext
<'a
, 'tcx
>,
143 type_
: Ty
<'tcx
>) -> UniqueTypeId
{
145 // basic type -> {:name of the type:}
146 // tuple -> {tuple_(:param-uid:)*}
147 // struct -> {struct_:svh: / :node-id:_<(:param-uid:),*> }
148 // enum -> {enum_:svh: / :node-id:_<(:param-uid:),*> }
149 // enum variant -> {variant_:variant-name:_:enum-uid:}
150 // reference (&) -> {& :pointee-uid:}
151 // mut reference (&mut) -> {&mut :pointee-uid:}
152 // ptr (*) -> {* :pointee-uid:}
153 // mut ptr (*mut) -> {*mut :pointee-uid:}
154 // unique ptr (box) -> {box :pointee-uid:}
155 // @-ptr (@) -> {@ :pointee-uid:}
156 // sized vec ([T; x]) -> {[:size:] :element-uid:}
157 // unsized vec ([T]) -> {[] :element-uid:}
158 // trait (T) -> {trait_:svh: / :node-id:_<(:param-uid:),*> }
159 // closure -> {<unsafe_> <once_> :store-sigil: |(:param-uid:),* <,_...>| -> \
160 // :return-type-uid: : (:bounds:)*}
161 // function -> {<unsafe_> <abi_> fn( (:param-uid:)* <,_...> ) -> \
162 // :return-type-uid:}
164 match self.type_to_unique_id
.get(&type_
).cloned() {
165 Some(unique_type_id
) => return unique_type_id
,
166 None
=> { /* generate one */}
169 let mut unique_type_id
= String
::with_capacity(256);
170 unique_type_id
.push('
{'
);
179 push_debuginfo_type_name(cx
, type_
, false, &mut unique_type_id
);
181 ty
::ty_enum(def_id
, substs
) => {
182 unique_type_id
.push_str("enum ");
183 from_def_id_and_substs(self, cx
, def_id
, substs
, &mut unique_type_id
);
185 ty
::ty_struct(def_id
, substs
) => {
186 unique_type_id
.push_str("struct ");
187 from_def_id_and_substs(self, cx
, def_id
, substs
, &mut unique_type_id
);
189 ty
::ty_tup(ref component_types
) if component_types
.is_empty() => {
190 push_debuginfo_type_name(cx
, type_
, false, &mut unique_type_id
);
192 ty
::ty_tup(ref component_types
) => {
193 unique_type_id
.push_str("tuple ");
194 for &component_type
in component_types
{
195 let component_type_id
=
196 self.get_unique_type_id_of_type(cx
, component_type
);
197 let component_type_id
=
198 self.get_unique_type_id_as_string(component_type_id
);
199 unique_type_id
.push_str(&component_type_id
[..]);
202 ty
::ty_uniq(inner_type
) => {
203 unique_type_id
.push_str("box ");
204 let inner_type_id
= self.get_unique_type_id_of_type(cx
, inner_type
);
205 let inner_type_id
= self.get_unique_type_id_as_string(inner_type_id
);
206 unique_type_id
.push_str(&inner_type_id
[..]);
208 ty
::ty_ptr(ty
::mt { ty: inner_type, mutbl }
) => {
209 unique_type_id
.push('
*'
);
210 if mutbl
== ast
::MutMutable
{
211 unique_type_id
.push_str("mut");
214 let inner_type_id
= self.get_unique_type_id_of_type(cx
, inner_type
);
215 let inner_type_id
= self.get_unique_type_id_as_string(inner_type_id
);
216 unique_type_id
.push_str(&inner_type_id
[..]);
218 ty
::ty_rptr(_
, ty
::mt { ty: inner_type, mutbl }
) => {
219 unique_type_id
.push('
&'
);
220 if mutbl
== ast
::MutMutable
{
221 unique_type_id
.push_str("mut");
224 let inner_type_id
= self.get_unique_type_id_of_type(cx
, inner_type
);
225 let inner_type_id
= self.get_unique_type_id_as_string(inner_type_id
);
226 unique_type_id
.push_str(&inner_type_id
[..]);
228 ty
::ty_vec(inner_type
, optional_length
) => {
229 match optional_length
{
231 unique_type_id
.push_str(&format
!("[{}]", len
));
234 unique_type_id
.push_str("[]");
238 let inner_type_id
= self.get_unique_type_id_of_type(cx
, inner_type
);
239 let inner_type_id
= self.get_unique_type_id_as_string(inner_type_id
);
240 unique_type_id
.push_str(&inner_type_id
[..]);
242 ty
::ty_trait(ref trait_data
) => {
243 unique_type_id
.push_str("trait ");
246 ty
::erase_late_bound_regions(cx
.tcx(),
247 &trait_data
.principal
);
249 from_def_id_and_substs(self,
253 &mut unique_type_id
);
255 ty
::ty_bare_fn(_
, &ty
::BareFnTy{ unsafety, abi, ref sig }
) => {
256 if unsafety
== ast
::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
= ty
::erase_late_bound_regions(cx
.tcx(), sig
);
266 for ¶meter_type
in &sig
.inputs
{
267 let parameter_type_id
=
268 self.get_unique_type_id_of_type(cx
, parameter_type
);
269 let parameter_type_id
=
270 self.get_unique_type_id_as_string(parameter_type_id
);
271 unique_type_id
.push_str(¶meter_type_id
[..]);
272 unique_type_id
.push('
,'
);
276 unique_type_id
.push_str("...");
279 unique_type_id
.push_str(")->");
281 ty
::FnConverging(ret_ty
) => {
282 let return_type_id
= self.get_unique_type_id_of_type(cx
, ret_ty
);
283 let return_type_id
= self.get_unique_type_id_as_string(return_type_id
);
284 unique_type_id
.push_str(&return_type_id
[..]);
287 unique_type_id
.push_str("!");
291 ty
::ty_closure(def_id
, substs
) => {
292 let typer
= NormalizingClosureTyper
::new(cx
.tcx());
293 let closure_ty
= typer
.closure_type(def_id
, substs
);
294 self.get_unique_type_id_of_closure_type(cx
,
296 &mut unique_type_id
);
299 cx
.sess().bug(&format
!("get_unique_type_id_of_type() - unexpected type: {}, {:?}",
300 &ppaux
::ty_to_string(cx
.tcx(), type_
),
305 unique_type_id
.push('
}'
);
307 // Trim to size before storing permanently
308 unique_type_id
.shrink_to_fit();
310 let key
= self.unique_id_interner
.intern(Rc
::new(unique_type_id
));
311 self.type_to_unique_id
.insert(type_
, UniqueTypeId(key
));
313 return UniqueTypeId(key
);
315 fn from_def_id_and_substs
<'a
, 'tcx
>(type_map
: &mut TypeMap
<'tcx
>,
316 cx
: &CrateContext
<'a
, 'tcx
>,
318 substs
: &subst
::Substs
<'tcx
>,
319 output
: &mut String
) {
320 // First, find out the 'real' def_id of the type. Items inlined from
321 // other crates have to be mapped back to their source.
322 let source_def_id
= if def_id
.krate
== ast
::LOCAL_CRATE
{
323 match cx
.external_srcs().borrow().get(&def_id
.node
).cloned() {
324 Some(source_def_id
) => {
325 // The given def_id identifies the inlined copy of a
326 // type definition, let's take the source of the copy.
335 // Get the crate hash as first part of the identifier.
336 let crate_hash
= if source_def_id
.krate
== ast
::LOCAL_CRATE
{
337 cx
.link_meta().crate_hash
.clone()
339 cx
.sess().cstore
.get_crate_hash(source_def_id
.krate
)
342 output
.push_str(crate_hash
.as_str());
343 output
.push_str("/");
344 output
.push_str(&format
!("{:x}", def_id
.node
));
346 // Maybe check that there is no self type here.
348 let tps
= substs
.types
.get_slice(subst
::TypeSpace
);
352 for &type_parameter
in tps
{
354 type_map
.get_unique_type_id_of_type(cx
, type_parameter
);
356 type_map
.get_unique_type_id_as_string(param_type_id
);
357 output
.push_str(¶m_type_id
[..]);
366 fn get_unique_type_id_of_closure_type
<'a
>(&mut self,
367 cx
: &CrateContext
<'a
, 'tcx
>,
368 closure_ty
: ty
::ClosureTy
<'tcx
>,
369 unique_type_id
: &mut String
) {
370 let ty
::ClosureTy
{ unsafety
,
372 abi
: _
} = closure_ty
;
374 if unsafety
== ast
::Unsafety
::Unsafe
{
375 unique_type_id
.push_str("unsafe ");
378 unique_type_id
.push_str("|");
380 let sig
= ty
::erase_late_bound_regions(cx
.tcx(), sig
);
382 for ¶meter_type
in &sig
.inputs
{
383 let parameter_type_id
=
384 self.get_unique_type_id_of_type(cx
, parameter_type
);
385 let parameter_type_id
=
386 self.get_unique_type_id_as_string(parameter_type_id
);
387 unique_type_id
.push_str(¶meter_type_id
[..]);
388 unique_type_id
.push('
,'
);
392 unique_type_id
.push_str("...");
395 unique_type_id
.push_str("|->");
398 ty
::FnConverging(ret_ty
) => {
399 let return_type_id
= self.get_unique_type_id_of_type(cx
, ret_ty
);
400 let return_type_id
= self.get_unique_type_id_as_string(return_type_id
);
401 unique_type_id
.push_str(&return_type_id
[..]);
404 unique_type_id
.push_str("!");
409 // Get the UniqueTypeId for an enum variant. Enum variants are not really
410 // types of their own, so they need special handling. We still need a
411 // UniqueTypeId for them, since to debuginfo they *are* real types.
412 fn get_unique_type_id_of_enum_variant
<'a
>(&mut self,
413 cx
: &CrateContext
<'a
, 'tcx
>,
417 let enum_type_id
= self.get_unique_type_id_of_type(cx
, enum_type
);
418 let enum_variant_type_id
= format
!("{}::{}",
419 &self.get_unique_type_id_as_string(enum_type_id
),
421 let interner_key
= self.unique_id_interner
.intern(Rc
::new(enum_variant_type_id
));
422 UniqueTypeId(interner_key
)
426 // A description of some recursive type. It can either be already finished (as
427 // with FinalMetadata) or it is not yet finished, but contains all information
428 // needed to generate the missing parts of the description. See the
429 // documentation section on Recursive Types at the top of this file for more
431 enum RecursiveTypeDescription
<'tcx
> {
433 unfinished_type
: Ty
<'tcx
>,
434 unique_type_id
: UniqueTypeId
,
435 metadata_stub
: DICompositeType
,
437 member_description_factory
: MemberDescriptionFactory
<'tcx
>,
439 FinalMetadata(DICompositeType
)
442 fn create_and_register_recursive_type_forward_declaration
<'a
, 'tcx
>(
443 cx
: &CrateContext
<'a
, 'tcx
>,
444 unfinished_type
: Ty
<'tcx
>,
445 unique_type_id
: UniqueTypeId
,
446 metadata_stub
: DICompositeType
,
448 member_description_factory
: MemberDescriptionFactory
<'tcx
>)
449 -> RecursiveTypeDescription
<'tcx
> {
451 // Insert the stub into the TypeMap in order to allow for recursive references
452 let mut type_map
= debug_context(cx
).type_map
.borrow_mut();
453 type_map
.register_unique_id_with_metadata(cx
, unique_type_id
, metadata_stub
);
454 type_map
.register_type_with_metadata(cx
, unfinished_type
, metadata_stub
);
457 unfinished_type
: unfinished_type
,
458 unique_type_id
: unique_type_id
,
459 metadata_stub
: metadata_stub
,
460 llvm_type
: llvm_type
,
461 member_description_factory
: member_description_factory
,
465 impl<'tcx
> RecursiveTypeDescription
<'tcx
> {
466 // Finishes up the description of the type in question (mostly by providing
467 // descriptions of the fields of the given type) and returns the final type
469 fn finalize
<'a
>(&self, cx
: &CrateContext
<'a
, 'tcx
>) -> MetadataCreationResult
{
471 FinalMetadata(metadata
) => MetadataCreationResult
::new(metadata
, false),
477 ref member_description_factory
,
480 // Make sure that we have a forward declaration of the type in
481 // the TypeMap so that recursive references are possible. This
482 // will always be the case if the RecursiveTypeDescription has
483 // been properly created through the
484 // create_and_register_recursive_type_forward_declaration()
487 let type_map
= debug_context(cx
).type_map
.borrow();
488 if type_map
.find_metadata_for_unique_id(unique_type_id
).is_none() ||
489 type_map
.find_metadata_for_type(unfinished_type
).is_none() {
490 cx
.sess().bug(&format
!("Forward declaration of potentially recursive type \
491 '{}' was not found in TypeMap!",
492 ppaux
::ty_to_string(cx
.tcx(), unfinished_type
))
497 // ... then create the member descriptions ...
498 let member_descriptions
=
499 member_description_factory
.create_member_descriptions(cx
);
501 // ... and attach them to the stub to complete it.
502 set_members_of_composite_type(cx
,
505 &member_descriptions
[..]);
506 return MetadataCreationResult
::new(metadata_stub
, true);
512 // Returns from the enclosing function if the type metadata with the given
513 // unique id can be found in the type map
514 macro_rules
! return_if_metadata_created_in_meantime
{
515 ($cx
: expr
, $unique_type_id
: expr
) => (
516 match debug_context($cx
).type_map
518 .find_metadata_for_unique_id($unique_type_id
) {
519 Some(metadata
) => return MetadataCreationResult
::new(metadata
, true),
520 None
=> { /* proceed normally */ }
525 fn fixed_vec_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
526 unique_type_id
: UniqueTypeId
,
527 element_type
: Ty
<'tcx
>,
530 -> MetadataCreationResult
{
531 let element_type_metadata
= type_metadata(cx
, element_type
, span
);
533 return_if_metadata_created_in_meantime
!(cx
, unique_type_id
);
535 let element_llvm_type
= type_of
::type_of(cx
, element_type
);
536 let (element_type_size
, element_type_align
) = size_and_align_of(cx
, element_llvm_type
);
538 let (array_size_in_bytes
, upper_bound
) = match len
{
539 Some(len
) => (element_type_size
* len
, len
as c_longlong
),
543 let subrange
= unsafe {
544 llvm
::LLVMDIBuilderGetOrCreateSubrange(DIB(cx
), 0, upper_bound
)
547 let subscripts
= create_DIArray(DIB(cx
), &[subrange
]);
548 let metadata
= unsafe {
549 llvm
::LLVMDIBuilderCreateArrayType(
551 bytes_to_bits(array_size_in_bytes
),
552 bytes_to_bits(element_type_align
),
553 element_type_metadata
,
557 return MetadataCreationResult
::new(metadata
, false);
560 fn vec_slice_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
562 element_type
: Ty
<'tcx
>,
563 unique_type_id
: UniqueTypeId
,
565 -> MetadataCreationResult
{
566 let data_ptr_type
= ty
::mk_ptr(cx
.tcx(), ty
::mt
{
568 mutbl
: ast
::MutImmutable
571 let element_type_metadata
= type_metadata(cx
, data_ptr_type
, span
);
573 return_if_metadata_created_in_meantime
!(cx
, unique_type_id
);
575 let slice_llvm_type
= type_of
::type_of(cx
, vec_type
);
576 let slice_type_name
= compute_debuginfo_type_name(cx
, vec_type
, true);
578 let member_llvm_types
= slice_llvm_type
.field_types();
579 assert
!(slice_layout_is_correct(cx
,
580 &member_llvm_types
[..],
582 let member_descriptions
= [
584 name
: "data_ptr".to_string(),
585 llvm_type
: member_llvm_types
[0],
586 type_metadata
: element_type_metadata
,
587 offset
: ComputedMemberOffset
,
591 name
: "length".to_string(),
592 llvm_type
: member_llvm_types
[1],
593 type_metadata
: type_metadata(cx
, cx
.tcx().types
.usize, span
),
594 offset
: ComputedMemberOffset
,
599 assert
!(member_descriptions
.len() == member_llvm_types
.len());
601 let loc
= span_start(cx
, span
);
602 let file_metadata
= file_metadata(cx
, &loc
.file
.name
);
604 let metadata
= composite_type_metadata(cx
,
606 &slice_type_name
[..],
608 &member_descriptions
,
609 UNKNOWN_SCOPE_METADATA
,
612 return MetadataCreationResult
::new(metadata
, false);
614 fn slice_layout_is_correct
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
615 member_llvm_types
: &[Type
],
616 element_type
: Ty
<'tcx
>)
618 member_llvm_types
.len() == 2 &&
619 member_llvm_types
[0] == type_of
::type_of(cx
, element_type
).ptr_to() &&
620 member_llvm_types
[1] == cx
.int_type()
624 fn subroutine_type_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
625 unique_type_id
: UniqueTypeId
,
626 signature
: &ty
::PolyFnSig
<'tcx
>,
628 -> MetadataCreationResult
630 let signature
= ty
::erase_late_bound_regions(cx
.tcx(), signature
);
632 let mut signature_metadata
: Vec
<DIType
> = Vec
::with_capacity(signature
.inputs
.len() + 1);
635 signature_metadata
.push(match signature
.output
{
636 ty
::FnConverging(ret_ty
) => match ret_ty
.sty
{
637 ty
::ty_tup(ref tys
) if tys
.is_empty() => ptr
::null_mut(),
638 _
=> type_metadata(cx
, ret_ty
, span
)
640 ty
::FnDiverging
=> diverging_type_metadata(cx
)
644 for &argument_type
in &signature
.inputs
{
645 signature_metadata
.push(type_metadata(cx
, argument_type
, span
));
648 return_if_metadata_created_in_meantime
!(cx
, unique_type_id
);
650 return MetadataCreationResult
::new(
652 llvm
::LLVMDIBuilderCreateSubroutineType(
654 UNKNOWN_FILE_METADATA
,
655 create_DIArray(DIB(cx
), &signature_metadata
[..]))
660 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
661 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
662 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
663 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
664 // of a DST struct, there is no trait_object_type and the results of this
665 // function will be a little bit weird.
666 fn trait_pointer_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
667 trait_type
: Ty
<'tcx
>,
668 trait_object_type
: Option
<Ty
<'tcx
>>,
669 unique_type_id
: UniqueTypeId
)
671 // The implementation provided here is a stub. It makes sure that the trait
672 // type is assigned the correct name, size, namespace, and source location.
673 // But it does not describe the trait's methods.
675 let def_id
= match trait_type
.sty
{
676 ty
::ty_trait(ref data
) => data
.principal_def_id(),
678 let pp_type_name
= ppaux
::ty_to_string(cx
.tcx(), trait_type
);
679 cx
.sess().bug(&format
!("debuginfo: Unexpected trait-object type in \
680 trait_pointer_metadata(): {}",
685 let trait_object_type
= trait_object_type
.unwrap_or(trait_type
);
686 let trait_type_name
=
687 compute_debuginfo_type_name(cx
, trait_object_type
, false);
689 let (containing_scope
, _
) = get_namespace_and_span_for_item(cx
, def_id
);
691 let trait_llvm_type
= type_of
::type_of(cx
, trait_object_type
);
693 composite_type_metadata(cx
,
695 &trait_type_name
[..],
699 UNKNOWN_FILE_METADATA
,
703 pub fn type_metadata
<'a
, 'tcx
>(cx
: &CrateContext
<'a
, 'tcx
>,
705 usage_site_span
: Span
)
707 // Get the unique type id of this type.
708 let unique_type_id
= {
709 let mut type_map
= debug_context(cx
).type_map
.borrow_mut();
710 // First, try to find the type in TypeMap. If we have seen it before, we
711 // can exit early here.
712 match type_map
.find_metadata_for_type(t
) {
717 // The Ty is not in the TypeMap but maybe we have already seen
718 // an equivalent type (e.g. only differing in region arguments).
719 // In order to find out, generate the unique type id and look
721 let unique_type_id
= type_map
.get_unique_type_id_of_type(cx
, t
);
722 match type_map
.find_metadata_for_unique_id(unique_type_id
) {
724 // There is already an equivalent type in the TypeMap.
725 // Register this Ty as an alias in the cache and
726 // return the cached metadata.
727 type_map
.register_type_with_metadata(cx
, t
, metadata
);
731 // There really is no type metadata for this type, so
732 // proceed by creating it.
740 debug
!("type_metadata: {:?}", t
);
743 let MetadataCreationResult { metadata, already_stored_in_typemap }
= match *sty
{
749 MetadataCreationResult
::new(basic_type_metadata(cx
, t
), false)
751 ty
::ty_tup(ref elements
) if elements
.is_empty() => {
752 MetadataCreationResult
::new(basic_type_metadata(cx
, t
), false)
754 ty
::ty_enum(def_id
, _
) => {
755 prepare_enum_metadata(cx
, t
, def_id
, unique_type_id
, usage_site_span
).finalize(cx
)
757 ty
::ty_vec(typ
, len
) => {
758 fixed_vec_metadata(cx
, unique_type_id
, typ
, len
.map(|x
| x
as u64), usage_site_span
)
761 fixed_vec_metadata(cx
, unique_type_id
, cx
.tcx().types
.i8, None
, usage_site_span
)
763 ty
::ty_trait(..) => {
764 MetadataCreationResult
::new(
765 trait_pointer_metadata(cx
, t
, None
, unique_type_id
),
768 ty
::ty_uniq(ty
) | ty
::ty_ptr(ty
::mt{ty, ..}
) | ty
::ty_rptr(_
, ty
::mt{ty, ..}
) => {
770 ty
::ty_vec(typ
, None
) => {
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
)
776 ty
::ty_trait(..) => {
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
::ty_bare_fn(_
, ref barefnty
) => {
797 subroutine_type_metadata(cx
, unique_type_id
, &barefnty
.sig
, usage_site_span
)
799 ty
::ty_closure(def_id
, substs
) => {
800 let typer
= NormalizingClosureTyper
::new(cx
.tcx());
801 let sig
= typer
.closure_type(def_id
, substs
).sig
;
802 subroutine_type_metadata(cx
, unique_type_id
, &sig
, usage_site_span
)
804 ty
::ty_struct(def_id
, substs
) => {
805 prepare_struct_metadata(cx
,
810 usage_site_span
).finalize(cx
)
812 ty
::ty_tup(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
[..],
840 ppaux
::ty_to_string(cx
.tcx(), t
));
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
[..],
855 ppaux
::ty_to_string(cx
.tcx(), t
));
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
::ty_tup(ref elements
) if elements
.is_empty() =>
939 ("()".to_string(), DW_ATE_unsigned
),
940 ty
::ty_bool
=> ("bool".to_string(), DW_ATE_boolean
),
941 ty
::ty_char
=> ("char".to_string(), DW_ATE_unsigned_char
),
942 ty
::ty_int(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
::ty_uint(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
::ty_float(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
= ty
::struct_fields(cx
.tcx(), def_id
, substs
);
1180 // The `Ty` values returned by `ty::struct_fields` can still contain
1181 // `ty_projection` 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
: ty
::type_is_simd(cx
.tcx(), struct_type
),
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
<_
>>().connect("$");
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
.iter())
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
= ty
::enum_variants(cx
.tcx(), 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(
1676 UNKNOWN_FILE_METADATA
,
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
= ty
::node_id_to_type(cx
.tcx(), 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
),