-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
metadata.rs
2340 lines (2116 loc) · 88.8 KB
/
metadata.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use self::RecursiveTypeDescription::*;
use self::MemberDescriptionFactory::*;
use self::EnumDiscriminantInfo::*;
use super::utils::{debug_context, DIB, span_start,
get_namespace_for_item, create_DIArray, is_node_local_to_unit};
use super::namespace::mangled_name_of_instance;
use super::type_names::compute_debuginfo_type_name;
use super::{CrateDebugContext};
use crate::abi;
use crate::value::Value;
use rustc_codegen_ssa::traits::*;
use crate::llvm;
use crate::llvm::debuginfo::{DIArray, DIType, DIFile, DIScope, DIDescriptor,
DICompositeType, DILexicalBlock, DIFlags, DebugEmissionKind};
use crate::llvm_util;
use crate::common::CodegenCx;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc::hir::CodegenFnAttrFlags;
use rustc::hir::def::CtorKind;
use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
use rustc::ich::NodeIdHashingMode;
use rustc::mir::Field;
use rustc::mir::GeneratorLayout;
use rustc::mir::interpret::truncate;
use rustc_data_structures::fingerprint::Fingerprint;
use rustc::ty::Instance;
use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
use rustc::ty::layout::{self, Align, Integer, IntegerExt, LayoutOf,
PrimitiveExt, Size, TyLayout, VariantIdx};
use rustc::ty::subst::UnpackedKind;
use rustc::session::config::{self, DebugInfo};
use rustc::util::nodemap::FxHashMap;
use rustc_fs_util::path_to_c_string;
use rustc_data_structures::small_c_str::SmallCStr;
use rustc_target::abi::HasDataLayout;
use libc::{c_uint, c_longlong};
use std::collections::hash_map::Entry;
use std::ffi::CString;
use std::fmt::{self, Write};
use std::hash::{Hash, Hasher};
use std::iter;
use std::ptr;
use std::path::{Path, PathBuf};
use syntax::ast;
use syntax::symbol::{Interner, InternedString};
use syntax_pos::{self, Span, FileName};
impl PartialEq for llvm::Metadata {
fn eq(&self, other: &Self) -> bool {
ptr::eq(self, other)
}
}
impl Eq for llvm::Metadata {}
impl Hash for llvm::Metadata {
fn hash<H: Hasher>(&self, hasher: &mut H) {
(self as *const Self).hash(hasher);
}
}
impl fmt::Debug for llvm::Metadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(self as *const Self).fmt(f)
}
}
// From DWARF 5.
// See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1
const DW_LANG_RUST: c_uint = 0x1c;
#[allow(non_upper_case_globals)]
const DW_ATE_boolean: c_uint = 0x02;
#[allow(non_upper_case_globals)]
const DW_ATE_float: c_uint = 0x04;
#[allow(non_upper_case_globals)]
const DW_ATE_signed: c_uint = 0x05;
#[allow(non_upper_case_globals)]
const DW_ATE_unsigned: c_uint = 0x07;
#[allow(non_upper_case_globals)]
const DW_ATE_unsigned_char: c_uint = 0x08;
pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
#[derive(Copy, Debug, Hash, Eq, PartialEq, Clone)]
pub struct UniqueTypeId(ast::Name);
// The TypeMap is where the CrateDebugContext holds the type metadata nodes
// created so far. The metadata nodes are indexed by UniqueTypeId, and, for
// faster lookup, also by Ty. The TypeMap is responsible for creating
// UniqueTypeIds.
#[derive(Default)]
pub struct TypeMap<'ll, 'tcx> {
// The UniqueTypeIds created so far
unique_id_interner: Interner,
// A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
// A map from types to debuginfo metadata. This is a N:1 mapping.
type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
// A map from types to UniqueTypeId. This is a N:1 mapping.
type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>
}
impl TypeMap<'ll, 'tcx> {
// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
// the mapping already exists.
fn register_type_with_metadata(
&mut self,
type_: Ty<'tcx>,
metadata: &'ll DIType,
) {
if self.type_to_metadata.insert(type_, metadata).is_some() {
bug!("Type metadata for Ty '{}' is already in the TypeMap!", type_);
}
}
// Removes a Ty to metadata mapping
// This is useful when computing the metadata for a potentially
// recursive type (e.g. a function ptr of the form:
//
// fn foo() -> impl Copy { foo }
//
// This kind of type cannot be properly represented
// via LLVM debuginfo. As a workaround,
// we register a temporary Ty to metadata mapping
// for the function before we compute its actual metadata.
// If the metadata computation ends up recursing back to the
// original function, it will use the temporary mapping
// for the inner self-reference, preventing us from
// recursing forever.
//
// This function is used to remove the temporary metadata
// mapping after we've computed the actual metadata
fn remove_type(
&mut self,
type_: Ty<'tcx>,
) {
if self.type_to_metadata.remove(type_).is_none() {
bug!("Type metadata Ty '{}' is not in the TypeMap!", type_);
}
}
// Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
// fail if the mapping already exists.
fn register_unique_id_with_metadata(
&mut self,
unique_type_id: UniqueTypeId,
metadata: &'ll DIType,
) {
if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
bug!("Type metadata for unique id '{}' is already in the TypeMap!",
self.get_unique_type_id_as_string(unique_type_id));
}
}
fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
self.type_to_metadata.get(&type_).cloned()
}
fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
self.unique_id_to_metadata.get(&unique_type_id).cloned()
}
// Get the string representation of a UniqueTypeId. This method will fail if
// the id is unknown.
fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
let UniqueTypeId(interner_key) = unique_type_id;
self.unique_id_interner.get(interner_key)
}
// Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
// type has been requested before, this is just a table lookup. Otherwise an
// ID will be generated and stored for later lookup.
fn get_unique_type_id_of_type<'a>(&mut self, cx: &CodegenCx<'a, 'tcx>,
type_: Ty<'tcx>) -> UniqueTypeId {
// Let's see if we already have something in the cache
if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
return unique_type_id;
}
// if not, generate one
// The hasher we are using to generate the UniqueTypeId. We want
// something that provides more than the 64 bits of the DefaultHasher.
let mut hasher = StableHasher::<Fingerprint>::new();
let mut hcx = cx.tcx.create_stable_hashing_context();
let type_ = cx.tcx.erase_regions(&type_);
hcx.while_hashing_spans(false, |hcx| {
hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
type_.hash_stable(hcx, &mut hasher);
});
});
let unique_type_id = hasher.finish().to_hex();
let key = self.unique_id_interner.intern(&unique_type_id);
self.type_to_unique_id.insert(type_, UniqueTypeId(key));
return UniqueTypeId(key);
}
// Get the UniqueTypeId for an enum variant. Enum variants are not really
// types of their own, so they need special handling. We still need a
// UniqueTypeId for them, since to debuginfo they *are* real types.
fn get_unique_type_id_of_enum_variant<'a>(&mut self,
cx: &CodegenCx<'a, 'tcx>,
enum_type: Ty<'tcx>,
variant_name: &str)
-> UniqueTypeId {
let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
let enum_variant_type_id = format!("{}::{}",
self.get_unique_type_id_as_string(enum_type_id),
variant_name);
let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
UniqueTypeId(interner_key)
}
// Get the unique type id string for an enum variant part.
// Variant parts are not types and shouldn't really have their own id,
// but it makes set_members_of_composite_type() simpler.
fn get_unique_type_id_str_of_enum_variant_part(&mut self, enum_type_id: UniqueTypeId) -> &str {
let variant_part_type_id = format!("{}_variant_part",
self.get_unique_type_id_as_string(enum_type_id));
let interner_key = self.unique_id_interner.intern(&variant_part_type_id);
self.unique_id_interner.get(interner_key)
}
}
// A description of some recursive type. It can either be already finished (as
// with FinalMetadata) or it is not yet finished, but contains all information
// needed to generate the missing parts of the description. See the
// documentation section on Recursive Types at the top of this file for more
// information.
enum RecursiveTypeDescription<'ll, 'tcx> {
UnfinishedMetadata {
unfinished_type: Ty<'tcx>,
unique_type_id: UniqueTypeId,
metadata_stub: &'ll DICompositeType,
member_holding_stub: &'ll DICompositeType,
member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
},
FinalMetadata(&'ll DICompositeType)
}
fn create_and_register_recursive_type_forward_declaration(
cx: &CodegenCx<'ll, 'tcx>,
unfinished_type: Ty<'tcx>,
unique_type_id: UniqueTypeId,
metadata_stub: &'ll DICompositeType,
member_holding_stub: &'ll DICompositeType,
member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
) -> RecursiveTypeDescription<'ll, 'tcx> {
// Insert the stub into the TypeMap in order to allow for recursive references
let mut type_map = debug_context(cx).type_map.borrow_mut();
type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
type_map.register_type_with_metadata(unfinished_type, metadata_stub);
UnfinishedMetadata {
unfinished_type,
unique_type_id,
metadata_stub,
member_holding_stub,
member_description_factory,
}
}
impl RecursiveTypeDescription<'ll, 'tcx> {
// Finishes up the description of the type in question (mostly by providing
// descriptions of the fields of the given type) and returns the final type
// metadata.
fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
match *self {
FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
UnfinishedMetadata {
unfinished_type,
unique_type_id,
metadata_stub,
member_holding_stub,
ref member_description_factory,
} => {
// Make sure that we have a forward declaration of the type in
// the TypeMap so that recursive references are possible. This
// will always be the case if the RecursiveTypeDescription has
// been properly created through the
// create_and_register_recursive_type_forward_declaration()
// function.
{
let type_map = debug_context(cx).type_map.borrow();
if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
type_map.find_metadata_for_type(unfinished_type).is_none() {
bug!("Forward declaration of potentially recursive type \
'{:?}' was not found in TypeMap!",
unfinished_type);
}
}
// ... then create the member descriptions ...
let member_descriptions =
member_description_factory.create_member_descriptions(cx);
// ... and attach them to the stub to complete it.
set_members_of_composite_type(cx,
unfinished_type,
member_holding_stub,
member_descriptions);
return MetadataCreationResult::new(metadata_stub, true);
}
}
}
}
// Returns from the enclosing function if the type metadata with the given
// unique id can be found in the type map
macro_rules! return_if_metadata_created_in_meantime {
($cx: expr, $unique_type_id: expr) => (
if let Some(metadata) = debug_context($cx).type_map
.borrow()
.find_metadata_for_unique_id($unique_type_id)
{
return MetadataCreationResult::new(metadata, true);
}
)
}
fn fixed_vec_metadata(
cx: &CodegenCx<'ll, 'tcx>,
unique_type_id: UniqueTypeId,
array_or_slice_type: Ty<'tcx>,
element_type: Ty<'tcx>,
span: Span,
) -> MetadataCreationResult<'ll> {
let element_type_metadata = type_metadata(cx, element_type, span);
return_if_metadata_created_in_meantime!(cx, unique_type_id);
let (size, align) = cx.size_and_align_of(array_or_slice_type);
let upper_bound = match array_or_slice_type.sty {
ty::Array(_, len) => len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong,
_ => -1
};
let subrange = unsafe {
Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound))
};
let subscripts = create_DIArray(DIB(cx), &[subrange]);
let metadata = unsafe {
llvm::LLVMRustDIBuilderCreateArrayType(
DIB(cx),
size.bits(),
align.bits() as u32,
element_type_metadata,
subscripts)
};
return MetadataCreationResult::new(metadata, false);
}
fn vec_slice_metadata(
cx: &CodegenCx<'ll, 'tcx>,
slice_ptr_type: Ty<'tcx>,
element_type: Ty<'tcx>,
unique_type_id: UniqueTypeId,
span: Span,
) -> MetadataCreationResult<'ll> {
let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
return_if_metadata_created_in_meantime!(cx, unique_type_id);
let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
let member_descriptions = vec![
MemberDescription {
name: "data_ptr".to_owned(),
type_metadata: data_ptr_metadata,
offset: Size::ZERO,
size: pointer_size,
align: pointer_align,
flags: DIFlags::FlagZero,
discriminant: None,
},
MemberDescription {
name: "length".to_owned(),
type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
offset: pointer_size,
size: usize_size,
align: usize_align,
flags: DIFlags::FlagZero,
discriminant: None,
},
];
let file_metadata = unknown_file_metadata(cx);
let metadata = composite_type_metadata(cx,
slice_ptr_type,
&slice_type_name[..],
unique_type_id,
member_descriptions,
NO_SCOPE_METADATA,
file_metadata,
span);
MetadataCreationResult::new(metadata, false)
}
fn subroutine_type_metadata(
cx: &CodegenCx<'ll, 'tcx>,
unique_type_id: UniqueTypeId,
signature: ty::PolyFnSig<'tcx>,
span: Span,
) -> MetadataCreationResult<'ll> {
let signature = cx.tcx.normalize_erasing_late_bound_regions(
ty::ParamEnv::reveal_all(),
&signature,
);
let signature_metadata: Vec<_> = iter::once(
// return type
match signature.output().sty {
ty::Tuple(ref tys) if tys.is_empty() => None,
_ => Some(type_metadata(cx, signature.output(), span))
}
).chain(
// regular arguments
signature.inputs().iter().map(|argument_type| {
Some(type_metadata(cx, argument_type, span))
})
).collect();
return_if_metadata_created_in_meantime!(cx, unique_type_id);
return MetadataCreationResult::new(
unsafe {
llvm::LLVMRustDIBuilderCreateSubroutineType(
DIB(cx),
unknown_file_metadata(cx),
create_DIArray(DIB(cx), &signature_metadata[..]))
},
false);
}
// FIXME(1563): This is all a bit of a hack because 'trait pointer' is an ill-
// defined concept. For the case of an actual trait pointer (i.e., `Box<Trait>`,
// `&Trait`), `trait_object_type` should be the whole thing (e.g, `Box<Trait>`) and
// `trait_type` should be the actual trait (e.g., `Trait`). Where the trait is part
// of a DST struct, there is no `trait_object_type` and the results of this
// function will be a little bit weird.
fn trait_pointer_metadata(
cx: &CodegenCx<'ll, 'tcx>,
trait_type: Ty<'tcx>,
trait_object_type: Option<Ty<'tcx>>,
unique_type_id: UniqueTypeId,
) -> &'ll DIType {
// The implementation provided here is a stub. It makes sure that the trait
// type is assigned the correct name, size, namespace, and source location.
// However, it does not describe the trait's methods.
let containing_scope = match trait_type.sty {
ty::Dynamic(ref data, ..) =>
data.principal_def_id().map(|did| get_namespace_for_item(cx, did)),
_ => {
bug!("debuginfo: unexpected trait-object type in \
trait_pointer_metadata(): {:?}",
trait_type);
}
};
let trait_object_type = trait_object_type.unwrap_or(trait_type);
let trait_type_name =
compute_debuginfo_type_name(cx.tcx, trait_object_type, false);
let file_metadata = unknown_file_metadata(cx);
let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
assert_eq!(abi::FAT_PTR_ADDR, 0);
assert_eq!(abi::FAT_PTR_EXTRA, 1);
let data_ptr_field = layout.field(cx, 0);
let vtable_field = layout.field(cx, 1);
let member_descriptions = vec![
MemberDescription {
name: "pointer".to_owned(),
type_metadata: type_metadata(cx,
cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
syntax_pos::DUMMY_SP),
offset: layout.fields.offset(0),
size: data_ptr_field.size,
align: data_ptr_field.align.abi,
flags: DIFlags::FlagArtificial,
discriminant: None,
},
MemberDescription {
name: "vtable".to_owned(),
type_metadata: type_metadata(cx, vtable_field.ty, syntax_pos::DUMMY_SP),
offset: layout.fields.offset(1),
size: vtable_field.size,
align: vtable_field.align.abi,
flags: DIFlags::FlagArtificial,
discriminant: None,
},
];
composite_type_metadata(cx,
trait_object_type,
&trait_type_name[..],
unique_type_id,
member_descriptions,
containing_scope,
file_metadata,
syntax_pos::DUMMY_SP)
}
pub fn type_metadata(
cx: &CodegenCx<'ll, 'tcx>,
t: Ty<'tcx>,
usage_site_span: Span,
) -> &'ll DIType {
// Get the unique type id of this type.
let unique_type_id = {
let mut type_map = debug_context(cx).type_map.borrow_mut();
// First, try to find the type in TypeMap. If we have seen it before, we
// can exit early here.
match type_map.find_metadata_for_type(t) {
Some(metadata) => {
return metadata;
},
None => {
// The Ty is not in the TypeMap but maybe we have already seen
// an equivalent type (e.g., only differing in region arguments).
// In order to find out, generate the unique type id and look
// that up.
let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
match type_map.find_metadata_for_unique_id(unique_type_id) {
Some(metadata) => {
// There is already an equivalent type in the TypeMap.
// Register this Ty as an alias in the cache and
// return the cached metadata.
type_map.register_type_with_metadata(t, metadata);
return metadata;
},
None => {
// There really is no type metadata for this type, so
// proceed by creating it.
unique_type_id
}
}
}
}
};
debug!("type_metadata: {:?}", t);
let ptr_metadata = |ty: Ty<'tcx>| {
match ty.sty {
ty::Slice(typ) => {
Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span))
}
ty::Str => {
Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span))
}
ty::Dynamic(..) => {
Ok(MetadataCreationResult::new(
trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
false))
}
_ => {
let pointee_metadata = type_metadata(cx, ty, usage_site_span);
if let Some(metadata) = debug_context(cx).type_map
.borrow()
.find_metadata_for_unique_id(unique_type_id)
{
return Err(metadata);
}
Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
false))
}
}
};
let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.sty {
ty::Never |
ty::Bool |
ty::Char |
ty::Int(_) |
ty::Uint(_) |
ty::Float(_) => {
MetadataCreationResult::new(basic_type_metadata(cx, t), false)
}
ty::Tuple(ref elements) if elements.is_empty() => {
MetadataCreationResult::new(basic_type_metadata(cx, t), false)
}
ty::Array(typ, _) |
ty::Slice(typ) => {
fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
}
ty::Str => {
fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span)
}
ty::Dynamic(..) => {
MetadataCreationResult::new(
trait_pointer_metadata(cx, t, None, unique_type_id),
false)
}
ty::Foreign(..) => {
MetadataCreationResult::new(
foreign_type_metadata(cx, t, unique_type_id),
false)
}
ty::RawPtr(ty::TypeAndMut{ty, ..}) |
ty::Ref(_, ty, _) => {
match ptr_metadata(ty) {
Ok(res) => res,
Err(metadata) => return metadata,
}
}
ty::Adt(def, _) if def.is_box() => {
match ptr_metadata(t.boxed_ty()) {
Ok(res) => res,
Err(metadata) => return metadata,
}
}
ty::FnDef(..) | ty::FnPtr(_) => {
if let Some(metadata) = debug_context(cx).type_map
.borrow()
.find_metadata_for_unique_id(unique_type_id)
{
return metadata;
}
// It's possible to create a self-referential
// type in Rust by using 'impl trait':
//
// fn foo() -> impl Copy { foo }
//
// See TypeMap::remove_type for more detals
// about the workaround
let temp_type = {
unsafe {
// The choice of type here is pretty arbitrary -
// anything reading the debuginfo for a recursive
// type is going to see *somthing* weird - the only
// question is what exactly it will see
let (size, align) = cx.size_and_align_of(t);
llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx),
SmallCStr::new("<recur_type>").as_ptr(),
size.bits(),
align.bits() as u32,
DW_ATE_unsigned)
}
};
let type_map = &debug_context(cx).type_map;
type_map.borrow_mut().register_type_with_metadata(t, temp_type);
let fn_metadata = subroutine_type_metadata(cx,
unique_type_id,
t.fn_sig(cx.tcx),
usage_site_span).metadata;
type_map.borrow_mut().remove_type(t);
// This is actually a function pointer, so wrap it in pointer DI
MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
}
ty::Closure(def_id, substs) => {
let upvar_tys : Vec<_> = substs.upvar_tys(def_id, cx.tcx).collect();
prepare_tuple_metadata(cx,
t,
&upvar_tys,
unique_type_id,
usage_site_span).finalize(cx)
}
ty::Generator(def_id, substs, _) => {
let upvar_tys : Vec<_> = substs.prefix_tys(def_id, cx.tcx).map(|t| {
cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)
}).collect();
prepare_enum_metadata(cx,
t,
def_id,
unique_type_id,
usage_site_span,
upvar_tys).finalize(cx)
}
ty::Adt(def, ..) => match def.adt_kind() {
AdtKind::Struct => {
prepare_struct_metadata(cx,
t,
unique_type_id,
usage_site_span).finalize(cx)
}
AdtKind::Union => {
prepare_union_metadata(cx,
t,
unique_type_id,
usage_site_span).finalize(cx)
}
AdtKind::Enum => {
prepare_enum_metadata(cx,
t,
def.did,
unique_type_id,
usage_site_span,
vec![]).finalize(cx)
}
},
ty::Tuple(ref elements) => {
let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
prepare_tuple_metadata(cx,
t,
&tys,
unique_type_id,
usage_site_span).finalize(cx)
}
_ => {
bug!("debuginfo: unexpected type in type_metadata: {:?}", t)
}
};
{
let mut type_map = debug_context(cx).type_map.borrow_mut();
if already_stored_in_typemap {
// Also make sure that we already have a TypeMap entry for the unique type id.
let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
Some(metadata) => metadata,
None => {
span_bug!(usage_site_span,
"Expected type metadata for unique \
type id '{}' to already be in \
the debuginfo::TypeMap but it \
was not. (Ty = {})",
type_map.get_unique_type_id_as_string(unique_type_id),
t);
}
};
match type_map.find_metadata_for_type(t) {
Some(metadata) => {
if metadata != metadata_for_uid {
span_bug!(usage_site_span,
"Mismatch between Ty and \
UniqueTypeId maps in \
debuginfo::TypeMap. \
UniqueTypeId={}, Ty={}",
type_map.get_unique_type_id_as_string(unique_type_id),
t);
}
}
None => {
type_map.register_type_with_metadata(t, metadata);
}
}
} else {
type_map.register_type_with_metadata(t, metadata);
type_map.register_unique_id_with_metadata(unique_type_id, metadata);
}
}
metadata
}
pub fn file_metadata(cx: &CodegenCx<'ll, '_>,
file_name: &FileName,
defining_crate: CrateNum) -> &'ll DIFile {
debug!("file_metadata: file_name: {}, defining_crate: {}",
file_name,
defining_crate);
let file_name = Some(file_name.to_string());
let directory = if defining_crate == LOCAL_CRATE {
Some(cx.sess().working_dir.0.to_string_lossy().to_string())
} else {
// If the path comes from an upstream crate we assume it has been made
// independent of the compiler's working directory one way or another.
None
};
file_metadata_raw(cx, file_name, directory)
}
pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
file_metadata_raw(cx, None, None)
}
fn file_metadata_raw(cx: &CodegenCx<'ll, '_>,
file_name: Option<String>,
directory: Option<String>)
-> &'ll DIFile {
let key = (file_name, directory);
match debug_context(cx).created_files.borrow_mut().entry(key) {
Entry::Occupied(o) => return o.get(),
Entry::Vacant(v) => {
let (file_name, directory) = v.key();
debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
let file_name = SmallCStr::new(
if let Some(file_name) = file_name { &file_name } else { "<unknown>" });
let directory = SmallCStr::new(
if let Some(directory) = directory { &directory } else { "" });
let file_metadata = unsafe {
llvm::LLVMRustDIBuilderCreateFile(DIB(cx),
file_name.as_ptr(),
directory.as_ptr())
};
v.insert(file_metadata);
file_metadata
}
}
}
fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
debug!("basic_type_metadata: {:?}", t);
let (name, encoding) = match t.sty {
ty::Never => ("!", DW_ATE_unsigned),
ty::Tuple(ref elements) if elements.is_empty() =>
("()", DW_ATE_unsigned),
ty::Bool => ("bool", DW_ATE_boolean),
ty::Char => ("char", DW_ATE_unsigned_char),
ty::Int(int_ty) => {
(int_ty.ty_to_string(), DW_ATE_signed)
},
ty::Uint(uint_ty) => {
(uint_ty.ty_to_string(), DW_ATE_unsigned)
},
ty::Float(float_ty) => {
(float_ty.ty_to_string(), DW_ATE_float)
},
_ => bug!("debuginfo::basic_type_metadata - t is invalid type")
};
let (size, align) = cx.size_and_align_of(t);
let name = SmallCStr::new(name);
let ty_metadata = unsafe {
llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx),
name.as_ptr(),
size.bits(),
align.bits() as u32,
encoding)
};
return ty_metadata;
}
fn foreign_type_metadata(
cx: &CodegenCx<'ll, 'tcx>,
t: Ty<'tcx>,
unique_type_id: UniqueTypeId,
) -> &'ll DIType {
debug!("foreign_type_metadata: {:?}", t);
let name = compute_debuginfo_type_name(cx.tcx, t, false);
create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA)
}
fn pointer_type_metadata(
cx: &CodegenCx<'ll, 'tcx>,
pointer_type: Ty<'tcx>,
pointee_type_metadata: &'ll DIType,
) -> &'ll DIType {
let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
let name = SmallCStr::new(&name);
unsafe {
llvm::LLVMRustDIBuilderCreatePointerType(
DIB(cx),
pointee_type_metadata,
pointer_size.bits(),
pointer_align.bits() as u32,
name.as_ptr())
}
}
pub fn compile_unit_metadata(
tcx: TyCtxt<'_>,
codegen_unit_name: &str,
debug_context: &CrateDebugContext<'ll, '_>,
) -> &'ll DIDescriptor {
let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
Some(ref path) => path.clone(),
None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
};
// The OSX linker has an idiosyncrasy where it will ignore some debuginfo
// if multiple object files with the same DW_AT_name are linked together.
// As a workaround we generate unique names for each object file. Those do
// not correspond to an actual source file but that should be harmless.
if tcx.sess.target.target.options.is_like_osx {
name_in_debuginfo.push("@");
name_in_debuginfo.push(codegen_unit_name);
}
debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
let rustc_producer = format!(
"rustc version {}",
option_env!("CFG_VERSION").expect("CFG_VERSION"),
);
// FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
let producer = format!("clang LLVM ({})", rustc_producer);
let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
let name_in_debuginfo = SmallCStr::new(&name_in_debuginfo);
let work_dir = SmallCStr::new(&tcx.sess.working_dir.0.to_string_lossy());
let producer = CString::new(producer).unwrap();
let flags = "\0";
let split_name = "\0";
// FIXME(#60020):
//
// This should actually be
//
// ```
// let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
// ```
//
// that is, we should set LLVM's emission kind to `LineTablesOnly` if
// we are compiling with "limited" debuginfo. However, some of the
// existing tools relied on slightly more debuginfo being generated than
// would be the case with `LineTablesOnly`, and we did not want to break
// these tools in a "drive-by fix", without a good idea or plan about
// what limited debuginfo should exactly look like. So for now we keep
// the emission kind as `FullDebug`.
//
// See https://github.com/rust-lang/rust/issues/60020 for details.
let kind = DebugEmissionKind::FullDebug;
assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
unsafe {
let file_metadata = llvm::LLVMRustDIBuilderCreateFile(
debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr());
let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
debug_context.builder,
DW_LANG_RUST,
file_metadata,
producer.as_ptr(),
tcx.sess.opts.optimize != config::OptLevel::No,
flags.as_ptr() as *const _,
0,
split_name.as_ptr() as *const _,
kind);
if tcx.sess.opts.debugging_opts.profile {
let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext,
unit_metadata);
let gcov_cu_info = [
path_to_mdstring(debug_context.llcontext,
&tcx.output_filenames(LOCAL_CRATE).with_extension("gcno")),
path_to_mdstring(debug_context.llcontext,
&tcx.output_filenames(LOCAL_CRATE).with_extension("gcda")),
cu_desc_metadata,
];
let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext,
gcov_cu_info.as_ptr(),
gcov_cu_info.len() as c_uint);
let llvm_gcov_ident = const_cstr!("llvm.gcov");
llvm::LLVMAddNamedMetadataOperand(debug_context.llmod,
llvm_gcov_ident.as_ptr(),
gcov_metadata);
}
// Insert `llvm.ident` metadata on the wasm32 targets since that will
// get hooked up to the "producer" sections `processed-by` information.
if tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
let name_metadata = llvm::LLVMMDStringInContext(
debug_context.llcontext,
rustc_producer.as_ptr() as *const _,
rustc_producer.as_bytes().len() as c_uint,
);
llvm::LLVMAddNamedMetadataOperand(
debug_context.llmod,
const_cstr!("llvm.ident").as_ptr(),
llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
);
}