]> git.proxmox.com Git - rustc.git/blob - src/librustc_trans/trans/debuginfo/metadata.rs
Imported Upstream version 1.1.0+dfsg1
[rustc.git] / src / librustc_trans / trans / debuginfo / metadata.rs
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.
4 //
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.
10
11 use self::RecursiveTypeDescription::*;
12 use self::MemberOffset::*;
13 use self::MemberDescriptionFactory::*;
14 use self::EnumDiscriminantInfo::*;
15
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};
22
23 use llvm::{self, ValueRef};
24 use llvm::debuginfo::{DIType, DIFile, DIScope, DIDescriptor, DICompositeType};
25
26 use metadata::csearch;
27 use middle::pat_util;
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;
36 use util::ppaux;
37 use util::common::path2cstr;
38
39 use libc::{c_uint, c_longlong};
40 use std::ffi::CString;
41 use std::path::Path;
42 use std::ptr;
43 use std::rc::Rc;
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};
48
49
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;
61
62 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
63 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
64
65 // ptr::null() doesn't work :(
66 const UNKNOWN_FILE_METADATA: DIFile = (0 as DIFile);
67 const UNKNOWN_SCOPE_METADATA: DIScope = (0 as DIScope);
68
69 const FLAGS_NONE: c_uint = 0;
70
71 #[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
72 pub struct UniqueTypeId(ast::Name);
73
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
77 // UniqueTypeIds.
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>
87 }
88
89 impl<'tcx> TypeMap<'tcx> {
90 pub fn new() -> TypeMap<'tcx> {
91 TypeMap {
92 unique_id_interner: Interner::new(),
93 type_to_metadata: FnvHashMap(),
94 unique_id_to_metadata: FnvHashMap(),
95 type_to_unique_id: FnvHashMap(),
96 }
97 }
98
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>,
103 type_: Ty<'tcx>,
104 metadata: DIType) {
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_)));
108 }
109 }
110
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,
114 cx: &CrateContext,
115 unique_type_id: UniqueTypeId,
116 metadata: DIType) {
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[..]));
121 }
122 }
123
124 fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
125 self.type_to_metadata.get(&type_).cloned()
126 }
127
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()
130 }
131
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)
137 }
138
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 {
144
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:}
163
164 match self.type_to_unique_id.get(&type_).cloned() {
165 Some(unique_type_id) => return unique_type_id,
166 None => { /* generate one */}
167 };
168
169 let mut unique_type_id = String::with_capacity(256);
170 unique_type_id.push('{');
171
172 match type_.sty {
173 ty::ty_bool |
174 ty::ty_char |
175 ty::ty_str |
176 ty::ty_int(_) |
177 ty::ty_uint(_) |
178 ty::ty_float(_) => {
179 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
180 },
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);
184 },
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);
188 },
189 ty::ty_tup(ref component_types) if component_types.is_empty() => {
190 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
191 },
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[..]);
200 }
201 },
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[..]);
207 },
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");
212 }
213
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[..]);
217 },
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");
222 }
223
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[..]);
227 },
228 ty::ty_vec(inner_type, optional_length) => {
229 match optional_length {
230 Some(len) => {
231 unique_type_id.push_str(&format!("[{}]", len));
232 }
233 None => {
234 unique_type_id.push_str("[]");
235 }
236 };
237
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[..]);
241 },
242 ty::ty_trait(ref trait_data) => {
243 unique_type_id.push_str("trait ");
244
245 let principal =
246 ty::erase_late_bound_regions(cx.tcx(),
247 &trait_data.principal);
248
249 from_def_id_and_substs(self,
250 cx,
251 principal.def_id,
252 principal.substs,
253 &mut unique_type_id);
254 },
255 ty::ty_bare_fn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => {
256 if unsafety == ast::Unsafety::Unsafe {
257 unique_type_id.push_str("unsafe ");
258 }
259
260 unique_type_id.push_str(abi.name());
261
262 unique_type_id.push_str(" fn(");
263
264 let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
265
266 for &parameter_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(&parameter_type_id[..]);
272 unique_type_id.push(',');
273 }
274
275 if sig.variadic {
276 unique_type_id.push_str("...");
277 }
278
279 unique_type_id.push_str(")->");
280 match sig.output {
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[..]);
285 }
286 ty::FnDiverging => {
287 unique_type_id.push_str("!");
288 }
289 }
290 },
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,
295 closure_ty,
296 &mut unique_type_id);
297 },
298 _ => {
299 cx.sess().bug(&format!("get_unique_type_id_of_type() - unexpected type: {}, {:?}",
300 &ppaux::ty_to_string(cx.tcx(), type_),
301 type_.sty))
302 }
303 };
304
305 unique_type_id.push('}');
306
307 // Trim to size before storing permanently
308 unique_type_id.shrink_to_fit();
309
310 let key = self.unique_id_interner.intern(Rc::new(unique_type_id));
311 self.type_to_unique_id.insert(type_, UniqueTypeId(key));
312
313 return UniqueTypeId(key);
314
315 fn from_def_id_and_substs<'a, 'tcx>(type_map: &mut TypeMap<'tcx>,
316 cx: &CrateContext<'a, 'tcx>,
317 def_id: ast::DefId,
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.
327 source_def_id
328 }
329 None => def_id
330 }
331 } else {
332 def_id
333 };
334
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()
338 } else {
339 cx.sess().cstore.get_crate_hash(source_def_id.krate)
340 };
341
342 output.push_str(crate_hash.as_str());
343 output.push_str("/");
344 output.push_str(&format!("{:x}", def_id.node));
345
346 // Maybe check that there is no self type here.
347
348 let tps = substs.types.get_slice(subst::TypeSpace);
349 if !tps.is_empty() {
350 output.push('<');
351
352 for &type_parameter in tps {
353 let param_type_id =
354 type_map.get_unique_type_id_of_type(cx, type_parameter);
355 let param_type_id =
356 type_map.get_unique_type_id_as_string(param_type_id);
357 output.push_str(&param_type_id[..]);
358 output.push(',');
359 }
360
361 output.push('>');
362 }
363 }
364 }
365
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,
371 ref sig,
372 abi: _ } = closure_ty;
373
374 if unsafety == ast::Unsafety::Unsafe {
375 unique_type_id.push_str("unsafe ");
376 }
377
378 unique_type_id.push_str("|");
379
380 let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
381
382 for &parameter_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(&parameter_type_id[..]);
388 unique_type_id.push(',');
389 }
390
391 if sig.variadic {
392 unique_type_id.push_str("...");
393 }
394
395 unique_type_id.push_str("|->");
396
397 match sig.output {
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[..]);
402 }
403 ty::FnDiverging => {
404 unique_type_id.push_str("!");
405 }
406 }
407 }
408
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>,
414 enum_type: Ty<'tcx>,
415 variant_name: &str)
416 -> UniqueTypeId {
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),
420 variant_name);
421 let interner_key = self.unique_id_interner.intern(Rc::new(enum_variant_type_id));
422 UniqueTypeId(interner_key)
423 }
424 }
425
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
430 // information.
431 enum RecursiveTypeDescription<'tcx> {
432 UnfinishedMetadata {
433 unfinished_type: Ty<'tcx>,
434 unique_type_id: UniqueTypeId,
435 metadata_stub: DICompositeType,
436 llvm_type: Type,
437 member_description_factory: MemberDescriptionFactory<'tcx>,
438 },
439 FinalMetadata(DICompositeType)
440 }
441
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,
447 llvm_type: Type,
448 member_description_factory: MemberDescriptionFactory<'tcx>)
449 -> RecursiveTypeDescription<'tcx> {
450
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);
455
456 UnfinishedMetadata {
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,
462 }
463 }
464
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
468 // metadata.
469 fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
470 match *self {
471 FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
472 UnfinishedMetadata {
473 unfinished_type,
474 unique_type_id,
475 metadata_stub,
476 llvm_type,
477 ref member_description_factory,
478 ..
479 } => {
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()
485 // function.
486 {
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))
493 );
494 }
495 }
496
497 // ... then create the member descriptions ...
498 let member_descriptions =
499 member_description_factory.create_member_descriptions(cx);
500
501 // ... and attach them to the stub to complete it.
502 set_members_of_composite_type(cx,
503 metadata_stub,
504 llvm_type,
505 &member_descriptions[..]);
506 return MetadataCreationResult::new(metadata_stub, true);
507 }
508 }
509 }
510 }
511
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
517 .borrow()
518 .find_metadata_for_unique_id($unique_type_id) {
519 Some(metadata) => return MetadataCreationResult::new(metadata, true),
520 None => { /* proceed normally */ }
521 };
522 )
523 }
524
525 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
526 unique_type_id: UniqueTypeId,
527 element_type: Ty<'tcx>,
528 len: Option<u64>,
529 span: Span)
530 -> MetadataCreationResult {
531 let element_type_metadata = type_metadata(cx, element_type, span);
532
533 return_if_metadata_created_in_meantime!(cx, unique_type_id);
534
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);
537
538 let (array_size_in_bytes, upper_bound) = match len {
539 Some(len) => (element_type_size * len, len as c_longlong),
540 None => (0, -1)
541 };
542
543 let subrange = unsafe {
544 llvm::LLVMDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)
545 };
546
547 let subscripts = create_DIArray(DIB(cx), &[subrange]);
548 let metadata = unsafe {
549 llvm::LLVMDIBuilderCreateArrayType(
550 DIB(cx),
551 bytes_to_bits(array_size_in_bytes),
552 bytes_to_bits(element_type_align),
553 element_type_metadata,
554 subscripts)
555 };
556
557 return MetadataCreationResult::new(metadata, false);
558 }
559
560 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
561 vec_type: Ty<'tcx>,
562 element_type: Ty<'tcx>,
563 unique_type_id: UniqueTypeId,
564 span: Span)
565 -> MetadataCreationResult {
566 let data_ptr_type = ty::mk_ptr(cx.tcx(), ty::mt {
567 ty: element_type,
568 mutbl: ast::MutImmutable
569 });
570
571 let element_type_metadata = type_metadata(cx, data_ptr_type, span);
572
573 return_if_metadata_created_in_meantime!(cx, unique_type_id);
574
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);
577
578 let member_llvm_types = slice_llvm_type.field_types();
579 assert!(slice_layout_is_correct(cx,
580 &member_llvm_types[..],
581 element_type));
582 let member_descriptions = [
583 MemberDescription {
584 name: "data_ptr".to_string(),
585 llvm_type: member_llvm_types[0],
586 type_metadata: element_type_metadata,
587 offset: ComputedMemberOffset,
588 flags: FLAGS_NONE
589 },
590 MemberDescription {
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,
595 flags: FLAGS_NONE
596 },
597 ];
598
599 assert!(member_descriptions.len() == member_llvm_types.len());
600
601 let loc = span_start(cx, span);
602 let file_metadata = file_metadata(cx, &loc.file.name);
603
604 let metadata = composite_type_metadata(cx,
605 slice_llvm_type,
606 &slice_type_name[..],
607 unique_type_id,
608 &member_descriptions,
609 UNKNOWN_SCOPE_METADATA,
610 file_metadata,
611 span);
612 return MetadataCreationResult::new(metadata, false);
613
614 fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
615 member_llvm_types: &[Type],
616 element_type: Ty<'tcx>)
617 -> bool {
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()
621 }
622 }
623
624 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
625 unique_type_id: UniqueTypeId,
626 signature: &ty::PolyFnSig<'tcx>,
627 span: Span)
628 -> MetadataCreationResult
629 {
630 let signature = ty::erase_late_bound_regions(cx.tcx(), signature);
631
632 let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs.len() + 1);
633
634 // return type
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)
639 },
640 ty::FnDiverging => diverging_type_metadata(cx)
641 });
642
643 // regular arguments
644 for &argument_type in &signature.inputs {
645 signature_metadata.push(type_metadata(cx, argument_type, span));
646 }
647
648 return_if_metadata_created_in_meantime!(cx, unique_type_id);
649
650 return MetadataCreationResult::new(
651 unsafe {
652 llvm::LLVMDIBuilderCreateSubroutineType(
653 DIB(cx),
654 UNKNOWN_FILE_METADATA,
655 create_DIArray(DIB(cx), &signature_metadata[..]))
656 },
657 false);
658 }
659
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)
670 -> DIType {
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.
674
675 let def_id = match trait_type.sty {
676 ty::ty_trait(ref data) => data.principal_def_id(),
677 _ => {
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(): {}",
681 &pp_type_name[..]));
682 }
683 };
684
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);
688
689 let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
690
691 let trait_llvm_type = type_of::type_of(cx, trait_object_type);
692
693 composite_type_metadata(cx,
694 trait_llvm_type,
695 &trait_type_name[..],
696 unique_type_id,
697 &[],
698 containing_scope,
699 UNKNOWN_FILE_METADATA,
700 codemap::DUMMY_SP)
701 }
702
703 pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
704 t: Ty<'tcx>,
705 usage_site_span: Span)
706 -> DIType {
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) {
713 Some(metadata) => {
714 return metadata;
715 },
716 None => {
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
720 // that up.
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) {
723 Some(metadata) => {
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);
728 return metadata;
729 },
730 None => {
731 // There really is no type metadata for this type, so
732 // proceed by creating it.
733 unique_type_id
734 }
735 }
736 }
737 }
738 };
739
740 debug!("type_metadata: {:?}", t);
741
742 let sty = &t.sty;
743 let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
744 ty::ty_bool |
745 ty::ty_char |
746 ty::ty_int(_) |
747 ty::ty_uint(_) |
748 ty::ty_float(_) => {
749 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
750 }
751 ty::ty_tup(ref elements) if elements.is_empty() => {
752 MetadataCreationResult::new(basic_type_metadata(cx, t), false)
753 }
754 ty::ty_enum(def_id, _) => {
755 prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span).finalize(cx)
756 }
757 ty::ty_vec(typ, len) => {
758 fixed_vec_metadata(cx, unique_type_id, typ, len.map(|x| x as u64), usage_site_span)
759 }
760 ty::ty_str => {
761 fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, None, usage_site_span)
762 }
763 ty::ty_trait(..) => {
764 MetadataCreationResult::new(
765 trait_pointer_metadata(cx, t, None, unique_type_id),
766 false)
767 }
768 ty::ty_uniq(ty) | ty::ty_ptr(ty::mt{ty, ..}) | ty::ty_rptr(_, ty::mt{ty, ..}) => {
769 match ty.sty {
770 ty::ty_vec(typ, None) => {
771 vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
772 }
773 ty::ty_str => {
774 vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span)
775 }
776 ty::ty_trait(..) => {
777 MetadataCreationResult::new(
778 trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
779 false)
780 }
781 _ => {
782 let pointee_metadata = type_metadata(cx, ty, usage_site_span);
783
784 match debug_context(cx).type_map
785 .borrow()
786 .find_metadata_for_unique_id(unique_type_id) {
787 Some(metadata) => return metadata,
788 None => { /* proceed normally */ }
789 };
790
791 MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
792 false)
793 }
794 }
795 }
796 ty::ty_bare_fn(_, ref barefnty) => {
797 subroutine_type_metadata(cx, unique_type_id, &barefnty.sig, usage_site_span)
798 }
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)
803 }
804 ty::ty_struct(def_id, substs) => {
805 prepare_struct_metadata(cx,
806 t,
807 def_id,
808 substs,
809 unique_type_id,
810 usage_site_span).finalize(cx)
811 }
812 ty::ty_tup(ref elements) => {
813 prepare_tuple_metadata(cx,
814 t,
815 &elements[..],
816 unique_type_id,
817 usage_site_span).finalize(cx)
818 }
819 _ => {
820 cx.sess().bug(&format!("debuginfo: unexpected type in type_metadata: {:?}",
821 sty))
822 }
823 };
824
825 {
826 let mut type_map = debug_context(cx).type_map.borrow_mut();
827
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,
832 None => {
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 \
838 was not. (Ty = {})",
839 &unique_type_id_str[..],
840 ppaux::ty_to_string(cx.tcx(), t));
841 cx.sess().span_bug(usage_site_span, &error_message[..]);
842 }
843 };
844
845 match type_map.find_metadata_for_type(t) {
846 Some(metadata) => {
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[..]);
857 }
858 }
859 None => {
860 type_map.register_type_with_metadata(cx, t, metadata);
861 }
862 }
863 } else {
864 type_map.register_type_with_metadata(cx, t, metadata);
865 type_map.register_unique_id_with_metadata(cx, unique_type_id, metadata);
866 }
867 }
868
869 metadata
870 }
871
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,
875 None => ()
876 }
877
878 debug!("file_metadata: {}", full_path);
879
880 // FIXME (#9639): This needs to handle non-utf8 paths
881 let work_dir = cx.sess().working_dir.to_str().unwrap();
882 let file_name =
883 if full_path.starts_with(work_dir) {
884 &full_path[work_dir.len() + 1..full_path.len()]
885 } else {
886 full_path
887 };
888
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(),
893 work_dir.as_ptr())
894 };
895
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;
899 }
900
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)
905 -> DIScope {
906 let scope_map = &fcx.debug_context
907 .get_ref(fcx.ccx, error_reporting_span)
908 .scope_map;
909 match scope_map.borrow().get(&node_id).cloned() {
910 Some(scope_metadata) => scope_metadata,
911 None => {
912 let node = fcx.ccx.tcx().map.get(node_id);
913
914 fcx.ccx.sess().span_bug(error_reporting_span,
915 &format!("debuginfo: Could not find scope info for node {:?}",
916 node));
917 }
918 }
919 }
920
921 fn diverging_type_metadata(cx: &CrateContext) -> DIType {
922 unsafe {
923 llvm::LLVMDIBuilderCreateBasicType(
924 DIB(cx),
925 "!\0".as_ptr() as *const _,
926 bytes_to_bits(0),
927 bytes_to_bits(0),
928 DW_ATE_unsigned)
929 }
930 }
931
932 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
933 t: Ty<'tcx>) -> DIType {
934
935 debug!("basic_type_metadata: {:?}", t);
936
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)
948 },
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)
955 },
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),
959 },
960 _ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type")
961 };
962
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(
968 DIB(cx),
969 name.as_ptr(),
970 bytes_to_bits(size),
971 bytes_to_bits(align),
972 encoding)
973 };
974
975 return ty_metadata;
976 }
977
978 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
979 pointer_type: Ty<'tcx>,
980 pointee_type_metadata: DIType)
981 -> 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(
988 DIB(cx),
989 pointee_type_metadata,
990 bytes_to_bits(pointer_size),
991 bytes_to_bits(pointer_align),
992 name.as_ptr())
993 };
994 return ptr_metadata;
995 }
996
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!");
1004 fallback_path(cx)
1005 } else {
1006 match abs_path.relative_from(work_dir) {
1007 Some(ref p) if p.is_relative() => {
1008 if p.starts_with(Path::new("./")) {
1009 path2cstr(p)
1010 } else {
1011 path2cstr(&Path::new(".").join(p))
1012 }
1013 }
1014 _ => fallback_path(cx)
1015 }
1016 }
1017 }
1018 };
1019
1020 debug!("compile_unit_metadata: {:?}", compile_unit_name);
1021 let producer = format!("rustc version {}",
1022 (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
1023
1024 let compile_unit_name = compile_unit_name.as_ptr();
1025 let work_dir = path2cstr(&work_dir);
1026 let producer = CString::new(producer).unwrap();
1027 let flags = "\0";
1028 let split_name = "\0";
1029 return unsafe {
1030 llvm::LLVMDIBuilderCreateCompileUnit(
1031 debug_context(cx).builder,
1032 DW_LANG_RUST,
1033 compile_unit_name,
1034 work_dir.as_ptr(),
1035 producer.as_ptr(),
1036 cx.sess().opts.optimize != config::No,
1037 flags.as_ptr() as *const _,
1038 0,
1039 split_name.as_ptr() as *const _)
1040 };
1041
1042 fn fallback_path(cx: &CrateContext) -> CString {
1043 CString::new(cx.link_meta().crate_name.clone()).unwrap()
1044 }
1045 }
1046
1047 struct MetadataCreationResult {
1048 metadata: DIType,
1049 already_stored_in_typemap: bool
1050 }
1051
1052 impl MetadataCreationResult {
1053 fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
1054 MetadataCreationResult {
1055 metadata: metadata,
1056 already_stored_in_typemap: already_stored_in_typemap
1057 }
1058 }
1059 }
1060
1061 #[derive(Debug)]
1062 enum MemberOffset {
1063 FixedMemberOffset { bytes: usize },
1064 // For ComputedMemberOffset, the offset is read from the llvm type definition.
1065 ComputedMemberOffset
1066 }
1067
1068 // Description of a type member, which can either be a regular field (as in
1069 // structs or tuples) or an enum variant.
1070 #[derive(Debug)]
1071 struct MemberDescription {
1072 name: String,
1073 llvm_type: Type,
1074 type_metadata: DIType,
1075 offset: MemberOffset,
1076 flags: c_uint
1077 }
1078
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>)
1088 }
1089
1090 impl<'tcx> MemberDescriptionFactory<'tcx> {
1091 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1092 -> Vec<MemberDescription> {
1093 match *self {
1094 StructMDF(ref this) => {
1095 this.create_member_descriptions(cx)
1096 }
1097 TupleMDF(ref this) => {
1098 this.create_member_descriptions(cx)
1099 }
1100 EnumMDF(ref this) => {
1101 this.create_member_descriptions(cx)
1102 }
1103 VariantMDF(ref this) => {
1104 this.create_member_descriptions(cx)
1105 }
1106 }
1107 }
1108 }
1109
1110 //=-----------------------------------------------------------------------------
1111 // Structs
1112 //=-----------------------------------------------------------------------------
1113
1114 // Creates MemberDescriptions for the fields of a struct
1115 struct StructMemberDescriptionFactory<'tcx> {
1116 fields: Vec<ty::field<'tcx>>,
1117 is_simd: bool,
1118 span: Span,
1119 }
1120
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() {
1125 return Vec::new();
1126 }
1127
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
1130 } else {
1131 0xdeadbeef
1132 };
1133
1134 self.fields.iter().enumerate().map(|(i, field)| {
1135 let name = if field.name == special_idents::unnamed_field.name {
1136 format!("__{}", i)
1137 } else {
1138 token::get_name(field.name).to_string()
1139 };
1140
1141 let offset = if self.is_simd {
1142 assert!(field_size != 0xdeadbeef);
1143 FixedMemberOffset { bytes: i * field_size }
1144 } else {
1145 ComputedMemberOffset
1146 };
1147
1148 MemberDescription {
1149 name: name,
1150 llvm_type: type_of::type_of(cx, field.mt.ty),
1151 type_metadata: type_metadata(cx, field.mt.ty, self.span),
1152 offset: offset,
1153 flags: FLAGS_NONE,
1154 }
1155 }).collect()
1156 }
1157 }
1158
1159
1160 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1161 struct_type: Ty<'tcx>,
1162 def_id: ast::DefId,
1163 substs: &subst::Substs<'tcx>,
1164 unique_type_id: UniqueTypeId,
1165 span: Span)
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);
1169
1170 let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
1171
1172 let struct_metadata_stub = create_struct_stub(cx,
1173 struct_llvm_type,
1174 &struct_name,
1175 unique_type_id,
1176 containing_scope);
1177
1178 let mut fields = ty::struct_fields(cx.tcx(), def_id, substs);
1179
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);
1184 }
1185
1186 create_and_register_recursive_type_forward_declaration(
1187 cx,
1188 struct_type,
1189 unique_type_id,
1190 struct_metadata_stub,
1191 struct_llvm_type,
1192 StructMDF(StructMemberDescriptionFactory {
1193 fields: fields,
1194 is_simd: ty::type_is_simd(cx.tcx(), struct_type),
1195 span: span,
1196 })
1197 )
1198 }
1199
1200
1201 //=-----------------------------------------------------------------------------
1202 // Tuples
1203 //=-----------------------------------------------------------------------------
1204
1205 // Creates MemberDescriptions for the fields of a tuple
1206 struct TupleMemberDescriptionFactory<'tcx> {
1207 component_types: Vec<Ty<'tcx>>,
1208 span: Span,
1209 }
1210
1211 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1212 fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1213 -> Vec<MemberDescription> {
1214 self.component_types
1215 .iter()
1216 .enumerate()
1217 .map(|(i, &component_type)| {
1218 MemberDescription {
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,
1223 flags: FLAGS_NONE,
1224 }
1225 }).collect()
1226 }
1227 }
1228
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,
1233 span: Span)
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);
1237
1238 create_and_register_recursive_type_forward_declaration(
1239 cx,
1240 tuple_type,
1241 unique_type_id,
1242 create_struct_stub(cx,
1243 tuple_llvm_type,
1244 &tuple_name[..],
1245 unique_type_id,
1246 UNKNOWN_SCOPE_METADATA),
1247 tuple_llvm_type,
1248 TupleMDF(TupleMemberDescriptionFactory {
1249 component_types: component_types.to_vec(),
1250 span: span,
1251 })
1252 )
1253 }
1254
1255
1256 //=-----------------------------------------------------------------------------
1257 // Enums
1258 //=-----------------------------------------------------------------------------
1259
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,
1272 span: Span,
1273 }
1274
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
1281 .expect(""));
1282
1283 struct_defs
1284 .iter()
1285 .enumerate()
1286 .map(|(i, struct_def)| {
1287 let (variant_type_metadata,
1288 variant_llvm_type,
1289 member_desc_factory) =
1290 describe_enum_variant(cx,
1291 self.enum_type,
1292 struct_def,
1293 &*(*self.variants)[i],
1294 discriminant_info,
1295 self.containing_scope,
1296 self.span);
1297
1298 let member_descriptions = member_desc_factory
1299 .create_member_descriptions(cx);
1300
1301 set_members_of_composite_type(cx,
1302 variant_type_metadata,
1303 variant_llvm_type,
1304 &member_descriptions);
1305 MemberDescription {
1306 name: "".to_string(),
1307 llvm_type: variant_llvm_type,
1308 type_metadata: variant_type_metadata,
1309 offset: FixedMemberOffset { bytes: 0 },
1310 flags: FLAGS_NONE
1311 }
1312 }).collect()
1313 },
1314 adt::Univariant(ref struct_def, _) => {
1315 assert!(self.variants.len() <= 1);
1316
1317 if self.variants.is_empty() {
1318 vec![]
1319 } else {
1320 let (variant_type_metadata,
1321 variant_llvm_type,
1322 member_description_factory) =
1323 describe_enum_variant(cx,
1324 self.enum_type,
1325 struct_def,
1326 &*(*self.variants)[0],
1327 NoDiscriminant,
1328 self.containing_scope,
1329 self.span);
1330
1331 let member_descriptions =
1332 member_description_factory.create_member_descriptions(cx);
1333
1334 set_members_of_composite_type(cx,
1335 variant_type_metadata,
1336 variant_llvm_type,
1337 &member_descriptions[..]);
1338 vec![
1339 MemberDescription {
1340 name: "".to_string(),
1341 llvm_type: variant_llvm_type,
1342 type_metadata: variant_type_metadata,
1343 offset: FixedMemberOffset { bytes: 0 },
1344 flags: FLAGS_NONE
1345 }
1346 ]
1347 }
1348 }
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.
1353
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);
1357
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);
1361
1362 // The type of the artificial struct wrapping the pointer
1363 let artificial_struct_llvm_type = Type::struct_(cx,
1364 &[non_null_llvm_type],
1365 false);
1366
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()
1373 },
1374 llvm_type: non_null_llvm_type,
1375 type_metadata: non_null_type_metadata,
1376 offset: FixedMemberOffset { bytes: 0 },
1377 flags: FLAGS_NONE
1378 };
1379
1380 let unique_type_id = debug_context(cx).type_map
1381 .borrow_mut()
1382 .get_unique_type_id_of_enum_variant(
1383 cx,
1384 self.enum_type,
1385 &non_null_variant_name);
1386
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,
1392 unique_type_id,
1393 &[sole_struct_member_description],
1394 self.containing_scope,
1395 self.file_metadata,
1396 codemap::DUMMY_SP);
1397
1398 // Encode the information about the null variant in the union
1399 // member's name.
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${}${}",
1403 0,
1404 null_variant_name);
1405
1406 // Finally create the (singleton) list of descriptions of union
1407 // members.
1408 vec![
1409 MemberDescription {
1410 name: union_member_name,
1411 llvm_type: artificial_struct_llvm_type,
1412 type_metadata: artificial_struct_metadata,
1413 offset: FixedMemberOffset { bytes: 0 },
1414 flags: FLAGS_NONE
1415 }
1416 ]
1417 },
1418 adt::StructWrappedNullablePointer { nonnull: ref struct_def,
1419 nndiscr,
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,
1424 self.enum_type,
1425 struct_def,
1426 &*(*self.variants)[nndiscr as usize],
1427 OptimizedDiscriminant,
1428 self.containing_scope,
1429 self.span);
1430
1431 let variant_member_descriptions =
1432 member_description_factory.create_member_descriptions(cx);
1433
1434 set_members_of_composite_type(cx,
1435 variant_type_metadata,
1436 variant_llvm_type,
1437 &variant_member_descriptions[..]);
1438
1439 // Encode the information about the null variant in the union
1440 // member's name.
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()
1444 .skip(1)
1445 .map(|x| x.to_string())
1446 .collect::<Vec<_>>().connect("$");
1447 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
1448 discrfield,
1449 null_variant_name);
1450
1451 // Create the (singleton) list of descriptions of union members.
1452 vec![
1453 MemberDescription {
1454 name: union_member_name,
1455 llvm_type: variant_llvm_type,
1456 type_metadata: variant_type_metadata,
1457 offset: FixedMemberOffset { bytes: 0 },
1458 flags: FLAGS_NONE
1459 }
1460 ]
1461 },
1462 adt::CEnum(..) => cx.sess().span_bug(self.span, "This should be unreachable.")
1463 }
1464 }
1465 }
1466
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>,
1471 span: Span,
1472 }
1473
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))| {
1478 MemberDescription {
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)
1484 },
1485 offset: ComputedMemberOffset,
1486 flags: FLAGS_NONE
1487 }
1488 }).collect()
1489 }
1490 }
1491
1492 #[derive(Copy, Clone)]
1493 enum EnumDiscriminantInfo {
1494 RegularDiscriminant(DIType),
1495 OptimizedDiscriminant,
1496 NoDiscriminant
1497 }
1498
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,
1509 span: Span)
1510 -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
1511 let variant_llvm_type =
1512 Type::struct_(cx, &struct_def.fields
1513 .iter()
1514 .map(|&t| type_of::type_of(cx, t))
1515 .collect::<Vec<_>>()
1516 ,
1517 struct_def.packed);
1518 // Could do some consistency checks here: size, align, field count, discr type
1519
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
1523 .borrow_mut()
1524 .get_unique_type_id_of_enum_variant(
1525 cx,
1526 enum_type,
1527 variant_name);
1528
1529 let metadata_stub = create_struct_stub(cx,
1530 variant_llvm_type,
1531 variant_name,
1532 unique_type_id,
1533 containing_scope);
1534
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) => {
1538 names.iter()
1539 .map(|&name| token::get_name(name).to_string())
1540 .collect()
1541 }
1542 None => {
1543 variant_info.args
1544 .iter()
1545 .enumerate()
1546 .map(|(i, _)| format!("__{}", i))
1547 .collect()
1548 }
1549 };
1550
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 */ }
1555 };
1556
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))
1561 .collect();
1562
1563 let member_description_factory =
1564 VariantMDF(VariantMemberDescriptionFactory {
1565 args: args,
1566 discriminant_type_metadata: match discriminant_info {
1567 RegularDiscriminant(discriminant_type_metadata) => {
1568 Some(discriminant_type_metadata)
1569 }
1570 _ => None
1571 },
1572 span: span,
1573 });
1574
1575 (metadata_stub, variant_llvm_type, member_description_factory)
1576 }
1577
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,
1582 span: Span)
1583 -> RecursiveTypeDescription<'tcx> {
1584 let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
1585
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);
1589
1590 let variants = ty::enum_variants(cx.tcx(), enum_def_id);
1591
1592 let enumerators_metadata: Vec<DIDescriptor> = variants
1593 .iter()
1594 .map(|v| {
1595 let token = token::get_name(v.name);
1596 let name = CString::new(token.as_bytes()).unwrap();
1597 unsafe {
1598 llvm::LLVMDIBuilderCreateEnumerator(
1599 DIB(cx),
1600 name.as_ptr(),
1601 v.disr_val as u64)
1602 }
1603 })
1604 .collect();
1605
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
1612 .borrow()
1613 .get(&enum_def_id).cloned();
1614 match cached_discriminant_type_metadata {
1615 Some(discriminant_type_metadata) => discriminant_type_metadata,
1616 None => {
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 =
1621 type_metadata(cx,
1622 adt::ty_of_inttype(cx.tcx(), inttype),
1623 codemap::DUMMY_SP);
1624 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
1625
1626 let name = CString::new(discriminant_name.as_bytes()).unwrap();
1627 let discriminant_type_metadata = unsafe {
1628 llvm::LLVMDIBuilderCreateEnumerationType(
1629 DIB(cx),
1630 containing_scope,
1631 name.as_ptr(),
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)
1638 };
1639
1640 debug_context(cx).created_enum_disr_types
1641 .borrow_mut()
1642 .insert(enum_def_id, discriminant_type_metadata);
1643
1644 discriminant_type_metadata
1645 }
1646 }
1647 };
1648
1649 let type_rep = adt::represent_type(cx, enum_type);
1650
1651 let discriminant_type_metadata = match *type_rep {
1652 adt::CEnum(inttype, _, _) => {
1653 return FinalMetadata(discriminant_type_metadata(inttype))
1654 },
1655 adt::RawNullablePointer { .. } |
1656 adt::StructWrappedNullablePointer { .. } |
1657 adt::Univariant(..) => None,
1658 adt::General(inttype, _, _) => Some(discriminant_type_metadata(inttype)),
1659 };
1660
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);
1663
1664 let unique_type_id_str = debug_context(cx)
1665 .type_map
1666 .borrow()
1667 .get_unique_type_id_as_string(unique_type_id);
1668
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(
1673 DIB(cx),
1674 containing_scope,
1675 enum_name.as_ptr(),
1676 UNKNOWN_FILE_METADATA,
1677 UNKNOWN_LINE_NUMBER,
1678 bytes_to_bits(enum_type_size),
1679 bytes_to_bits(enum_type_align),
1680 0, // Flags
1681 ptr::null_mut(),
1682 0, // RuntimeLang
1683 unique_type_id_str.as_ptr())
1684 };
1685
1686 return create_and_register_recursive_type_forward_declaration(
1687 cx,
1688 enum_type,
1689 unique_type_id,
1690 enum_metadata,
1691 enum_llvm_type,
1692 EnumMDF(EnumMemberDescriptionFactory {
1693 enum_type: enum_type,
1694 type_rep: type_rep.clone(),
1695 variants: variants,
1696 discriminant_type_metadata: discriminant_type_metadata,
1697 containing_scope: containing_scope,
1698 file_metadata: file_metadata,
1699 span: span,
1700 }),
1701 );
1702
1703 fn get_enum_discriminant_name(cx: &CrateContext,
1704 def_id: ast::DefId)
1705 -> token::InternedString {
1706 let name = if def_id.krate == ast::LOCAL_CRATE {
1707 cx.tcx().map.get_path_elem(def_id.node).name()
1708 } else {
1709 csearch::get_item_path(cx.tcx(), def_id).last().unwrap().name()
1710 };
1711
1712 token::get_name(name)
1713 }
1714 }
1715
1716 /// Creates debug information for a composite type, that is, anything that
1717 /// results in a LLVM struct.
1718 ///
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,
1726
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,
1737 containing_scope);
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);
1743
1744 return composite_type_metadata;
1745 }
1746
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
1756 // regression.
1757 {
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.");
1763 } else {
1764 composite_types_completed.insert(composite_type_metadata);
1765 }
1766 }
1767
1768 let member_metadata: Vec<DIDescriptor> = member_descriptions
1769 .iter()
1770 .enumerate()
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)
1776 };
1777
1778 let member_name = member_description.name.as_bytes();
1779 let member_name = CString::new(member_name).unwrap();
1780 unsafe {
1781 llvm::LLVMDIBuilderCreateMemberType(
1782 DIB(cx),
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)
1792 }
1793 })
1794 .collect();
1795
1796 unsafe {
1797 let type_array = create_DIArray(DIB(cx), &member_metadata[..]);
1798 llvm::LLVMDICompositeTypeSetTypeArray(DIB(cx), composite_type_metadata, type_array);
1799 }
1800 }
1801
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);
1812
1813 let unique_type_id_str = debug_context(cx).type_map
1814 .borrow()
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), &[]);
1823
1824 llvm::LLVMDIBuilderCreateStructType(
1825 DIB(cx),
1826 containing_scope,
1827 name.as_ptr(),
1828 UNKNOWN_FILE_METADATA,
1829 UNKNOWN_LINE_NUMBER,
1830 bytes_to_bits(struct_size),
1831 bytes_to_bits(struct_align),
1832 0,
1833 ptr::null_mut(),
1834 empty_array,
1835 0,
1836 ptr::null_mut(),
1837 unique_type_id.as_ptr())
1838 };
1839
1840 return metadata_stub;
1841 }
1842
1843 /// Creates debug information for the given global variable.
1844 ///
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,
1848 global: ValueRef) {
1849 if cx.dbg_cx().is_none() {
1850 return;
1851 }
1852
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) {
1858 return;
1859 }
1860
1861 let var_item = cx.tcx().map.get(node_id);
1862
1863 let (name, span) = match var_item {
1864 ast_map::NodeItem(item) => {
1865 match item.node {
1866 ast::ItemStatic(..) => (item.ident.name, item.span),
1867 ast::ItemConst(..) => (item.ident.name, item.span),
1868 _ => {
1869 cx.sess()
1870 .span_bug(item.span,
1871 &format!("debuginfo::\
1872 create_global_var_metadata() -
1873 Captured var-id refers to \
1874 unexpected ast_item variant: {:?}",
1875 var_item))
1876 }
1877 }
1878 },
1879 _ => cx.sess().bug(&format!("debuginfo::create_global_var_metadata() \
1880 - Captured var-id refers to unexpected \
1881 ast_map variant: {:?}",
1882 var_item))
1883 };
1884
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)
1888 } else {
1889 (UNKNOWN_FILE_METADATA, UNKNOWN_LINE_NUMBER)
1890 };
1891
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();
1897 let linkage_name =
1898 namespace_node.mangled_name_of_contained_item(&var_name[..]);
1899 let var_scope = namespace_node.scope;
1900
1901 let var_name = CString::new(var_name).unwrap();
1902 let linkage_name = CString::new(linkage_name).unwrap();
1903 unsafe {
1904 llvm::LLVMDIBuilderCreateStaticVariable(DIB(cx),
1905 var_scope,
1906 var_name.as_ptr(),
1907 linkage_name.as_ptr(),
1908 file_metadata,
1909 line_number,
1910 type_metadata,
1911 is_local_to_unit,
1912 global,
1913 ptr::null_mut());
1914 }
1915 }
1916
1917 /// Creates debug information for the given local variable.
1918 ///
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 {
1926 return;
1927 }
1928
1929 let cx = bcx.ccx();
1930 let def_map = &cx.tcx().def_map;
1931 let locals = bcx.fcx.lllocals.borrow();
1932
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,
1936 None => {
1937 bcx.sess().span_bug(span,
1938 &format!("no entry in lllocals table for {}",
1939 node_id));
1940 }
1941 };
1942
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!");
1946 }
1947
1948 let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
1949
1950 declare_local(bcx,
1951 var_ident.node.name,
1952 datum.ty,
1953 scope_metadata,
1954 VariableAccess::DirectVariable { alloca: datum.val },
1955 VariableKind::LocalVariable,
1956 span);
1957 })
1958 }
1959
1960 /// Creates debug information for a variable captured in a closure.
1961 ///
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,
1966 env_index: usize,
1967 captured_by_ref: bool,
1968 span: Span) {
1969 if bcx.unreachable.get() ||
1970 fn_should_be_ignored(bcx.fcx) ||
1971 bcx.sess().opts.debuginfo != FullDebugInfo {
1972 return;
1973 }
1974
1975 let cx = bcx.ccx();
1976
1977 let ast_item = cx.tcx().map.find(node_id);
1978
1979 let variable_name = match ast_item {
1980 None => {
1981 cx.sess().span_bug(span, "debuginfo::create_captured_var_metadata: node not found");
1982 }
1983 Some(ast_map::NodeLocal(pat)) | Some(ast_map::NodeArg(pat)) => {
1984 match pat.node {
1985 ast::PatIdent(_, ref path1, _) => {
1986 path1.node.name
1987 }
1988 _ => {
1989 cx.sess()
1990 .span_bug(span,
1991 &format!(
1992 "debuginfo::create_captured_var_metadata() - \
1993 Captured var-id refers to unexpected \
1994 ast_map variant: {:?}",
1995 ast_item));
1996 }
1997 }
1998 }
1999 _ => {
2000 cx.sess()
2001 .span_bug(span,
2002 &format!("debuginfo::create_captured_var_metadata() - \
2003 Captured var-id refers to unexpected \
2004 ast_map variant: {:?}",
2005 ast_item));
2006 }
2007 };
2008
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;
2011
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()
2016 .element_type();
2017 let byte_offset_of_var_in_env = machine::llelement_offset(cx,
2018 llvm_env_data_type,
2019 env_index);
2020
2021 let address_operations = unsafe {
2022 [llvm::LLVMDIBuilderCreateOpDeref(),
2023 llvm::LLVMDIBuilderCreateOpPlus(),
2024 byte_offset_of_var_in_env as i64,
2025 llvm::LLVMDIBuilderCreateOpDeref()]
2026 };
2027
2028 let address_op_count = if captured_by_ref {
2029 address_operations.len()
2030 } else {
2031 address_operations.len() - 1
2032 };
2033
2034 let variable_access = VariableAccess::IndirectVariable {
2035 alloca: env_pointer,
2036 address_operations: &address_operations[..address_op_count]
2037 };
2038
2039 declare_local(bcx,
2040 variable_name,
2041 variable_type,
2042 scope_metadata,
2043 variable_access,
2044 VariableKind::CapturedVariable,
2045 span);
2046 }
2047
2048 /// Creates debug information for a local variable introduced in the head of a
2049 /// match-statement arm.
2050 ///
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 {
2058 return;
2059 }
2060
2061 let scope_metadata = scope_metadata(bcx.fcx, binding.id, binding.span);
2062 let aops = unsafe {
2063 [llvm::LLVMDIBuilderCreateOpDeref()]
2064 };
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
2069 // for the binding.
2070 let var_access = match binding.trmode {
2071 TrByCopy(llbinding) => VariableAccess::DirectVariable {
2072 alloca: llbinding
2073 },
2074 TrByMove => VariableAccess::IndirectVariable {
2075 alloca: binding.llmatch,
2076 address_operations: &aops
2077 },
2078 TrByRef => VariableAccess::DirectVariable {
2079 alloca: binding.llmatch
2080 }
2081 };
2082
2083 declare_local(bcx,
2084 variable_name,
2085 binding.ty,
2086 scope_metadata,
2087 var_access,
2088 VariableKind::LocalVariable,
2089 binding.span);
2090 }
2091
2092 /// Creates debug information for the given function argument.
2093 ///
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 {
2101 return;
2102 }
2103
2104 let def_map = &bcx.tcx().def_map;
2105 let scope_metadata = bcx
2106 .fcx
2107 .debug_context
2108 .get_ref(bcx.ccx(), arg.pat.span)
2109 .fn_metadata;
2110 let locals = bcx.fcx.lllocals.borrow();
2111
2112 pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, span, var_ident| {
2113 let datum = match locals.get(&node_id) {
2114 Some(v) => v,
2115 None => {
2116 bcx.sess().span_bug(span,
2117 &format!("no entry in lllocals table for {}",
2118 node_id));
2119 }
2120 };
2121
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!");
2125 }
2126
2127 let argument_index = {
2128 let counter = &bcx
2129 .fcx
2130 .debug_context
2131 .get_ref(bcx.ccx(), span)
2132 .argument_counter;
2133 let argument_index = counter.get();
2134 counter.set(argument_index + 1);
2135 argument_index
2136 };
2137
2138 declare_local(bcx,
2139 var_ident.node.name,
2140 datum.ty,
2141 scope_metadata,
2142 VariableAccess::DirectVariable { alloca: datum.val },
2143 VariableKind::ArgumentVariable(argument_index),
2144 span);
2145 })
2146 }