forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDWARFLinker.cpp
2634 lines (2331 loc) · 102 KB
/
DWARFLinker.cpp
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
//=== DWARFLinker.cpp -----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/DWARFLinker/DWARFLinker.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/CodeGen/NonRelocatableStringpool.h"
#include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
#include "llvm/DebugInfo/DWARF/DWARFDie.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/DebugInfo/DWARF/DWARFSection.h"
#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ThreadPool.h"
#include <vector>
namespace llvm {
/// Hold the input and output of the debug info size in bytes.
struct DebugInfoSize {
uint64_t Input;
uint64_t Output;
};
/// Compute the total size of the debug info.
static uint64_t getDebugInfoSize(DWARFContext &Dwarf) {
uint64_t Size = 0;
for (auto &Unit : Dwarf.compile_units()) {
Size += Unit->getLength();
}
return Size;
}
/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
/// CompileUnit object instead.
static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
auto CU = llvm::upper_bound(
Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
return LHS < RHS->getOrigUnit().getNextUnitOffset();
});
return CU != Units.end() ? CU->get() : nullptr;
}
/// Resolve the DIE attribute reference that has been extracted in \p RefValue.
/// The resulting DIE might be in another CompileUnit which is stored into \p
/// ReferencedCU. \returns null if resolving fails for any reason.
DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
const UnitListTy &Units,
const DWARFFormValue &RefValue,
const DWARFDie &DIE,
CompileUnit *&RefCU) {
assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
uint64_t RefOffset = *RefValue.getAsReference();
if ((RefCU = getUnitForOffset(Units, RefOffset)))
if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
// In a file with broken references, an attribute might point to a NULL
// DIE.
if (!RefDie.isNULL())
return RefDie;
}
reportWarning("could not find referenced DIE", File, &DIE);
return DWARFDie();
}
/// \returns whether the passed \a Attr type might contain a DIE reference
/// suitable for ODR uniquing.
static bool isODRAttribute(uint16_t Attr) {
switch (Attr) {
default:
return false;
case dwarf::DW_AT_type:
case dwarf::DW_AT_containing_type:
case dwarf::DW_AT_specification:
case dwarf::DW_AT_abstract_origin:
case dwarf::DW_AT_import:
return true;
}
llvm_unreachable("Improper attribute.");
}
static bool isTypeTag(uint16_t Tag) {
switch (Tag) {
case dwarf::DW_TAG_array_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_enumeration_type:
case dwarf::DW_TAG_pointer_type:
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_string_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_subroutine_type:
case dwarf::DW_TAG_typedef:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_ptr_to_member_type:
case dwarf::DW_TAG_set_type:
case dwarf::DW_TAG_subrange_type:
case dwarf::DW_TAG_base_type:
case dwarf::DW_TAG_const_type:
case dwarf::DW_TAG_constant:
case dwarf::DW_TAG_file_type:
case dwarf::DW_TAG_namelist:
case dwarf::DW_TAG_packed_type:
case dwarf::DW_TAG_volatile_type:
case dwarf::DW_TAG_restrict_type:
case dwarf::DW_TAG_atomic_type:
case dwarf::DW_TAG_interface_type:
case dwarf::DW_TAG_unspecified_type:
case dwarf::DW_TAG_shared_type:
case dwarf::DW_TAG_immutable_type:
return true;
default:
break;
}
return false;
}
AddressesMap::~AddressesMap() = default;
DwarfEmitter::~DwarfEmitter() = default;
static Optional<StringRef> StripTemplateParameters(StringRef Name) {
// We are looking for template parameters to strip from Name. e.g.
//
// operator<<B>
//
// We look for > at the end but if it does not contain any < then we
// have something like operator>>. We check for the operator<=> case.
if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>"))
return {};
// How many < until we have the start of the template parameters.
size_t NumLeftAnglesToSkip = 1;
// If we have operator<=> then we need to skip its < as well.
NumLeftAnglesToSkip += Name.count("<=>");
size_t RightAngleCount = Name.count('>');
size_t LeftAngleCount = Name.count('<');
// If we have more < than > we have operator< or operator<<
// we to account for their < as well.
if (LeftAngleCount > RightAngleCount)
NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
size_t StartOfTemplate = 0;
while (NumLeftAnglesToSkip--)
StartOfTemplate = Name.find('<', StartOfTemplate) + 1;
return Name.substr(0, StartOfTemplate - 1);
}
bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die,
AttributesInfo &Info,
OffsetsStringPool &StringPool,
bool StripTemplate) {
// This function will be called on DIEs having low_pcs and
// ranges. As getting the name might be more expansive, filter out
// blocks directly.
if (Die.getTag() == dwarf::DW_TAG_lexical_block)
return false;
if (!Info.MangledName)
if (const char *MangledName = Die.getLinkageName())
Info.MangledName = StringPool.getEntry(MangledName);
if (!Info.Name)
if (const char *Name = Die.getShortName())
Info.Name = StringPool.getEntry(Name);
if (!Info.MangledName)
Info.MangledName = Info.Name;
if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
StringRef Name = Info.Name.getString();
if (Optional<StringRef> StrippedName = StripTemplateParameters(Name))
Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
}
return Info.Name || Info.MangledName;
}
/// Resolve the relative path to a build artifact referenced by DWARF by
/// applying DW_AT_comp_dir.
static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
}
/// Collect references to parseable Swift interfaces in imported
/// DW_TAG_module blocks.
static void analyzeImportedModule(
const DWARFDie &DIE, CompileUnit &CU,
swiftInterfacesMap *ParseableSwiftInterfaces,
std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
if (CU.getLanguage() != dwarf::DW_LANG_Swift)
return;
if (!ParseableSwiftInterfaces)
return;
StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
if (!Path.endswith(".swiftinterface"))
return;
// Don't track interfaces that are part of the SDK.
StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
if (SysRoot.empty())
SysRoot = CU.getSysRoot();
if (!SysRoot.empty() && Path.startswith(SysRoot))
return;
Optional<const char*> Name = dwarf::toString(DIE.find(dwarf::DW_AT_name));
if (!Name)
return;
auto &Entry = (*ParseableSwiftInterfaces)[*Name];
// The prepend path is applied later when copying.
DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
SmallString<128> ResolvedPath;
if (sys::path::is_relative(Path))
resolveRelativeObjectPath(ResolvedPath, CUDie);
sys::path::append(ResolvedPath, Path);
if (!Entry.empty() && Entry != ResolvedPath)
ReportWarning(Twine("Conflicting parseable interfaces for Swift Module ") +
*Name + ": " + Entry + " and " + Path,
DIE);
Entry = std::string(ResolvedPath.str());
}
/// The distinct types of work performed by the work loop in
/// analyzeContextInfo.
enum class ContextWorklistItemType : uint8_t {
AnalyzeContextInfo,
UpdateChildPruning,
UpdatePruning,
};
/// This class represents an item in the work list. The type defines what kind
/// of work needs to be performed when processing the current item. Everything
/// but the Type and Die fields are optional based on the type.
struct ContextWorklistItem {
DWARFDie Die;
unsigned ParentIdx;
union {
CompileUnit::DIEInfo *OtherInfo;
DeclContext *Context;
};
ContextWorklistItemType Type;
bool InImportedModule;
ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T,
CompileUnit::DIEInfo *OtherInfo = nullptr)
: Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T),
InImportedModule(false) {}
ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx,
bool InImportedModule)
: Die(Die), ParentIdx(ParentIdx), Context(Context),
Type(ContextWorklistItemType::AnalyzeContextInfo),
InImportedModule(InImportedModule) {}
};
static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
uint64_t ModulesEndOffset) {
CompileUnit::DIEInfo &Info = CU.getInfo(Die);
// Prune this DIE if it is either a forward declaration inside a
// DW_TAG_module or a DW_TAG_module that contains nothing but
// forward declarations.
Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
(isTypeTag(Die.getTag()) &&
dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
// Only prune forward declarations inside a DW_TAG_module for which a
// definition exists elsewhere.
if (ModulesEndOffset == 0)
Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
else
Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
return Info.Prune;
}
static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
CompileUnit::DIEInfo &ChildInfo) {
CompileUnit::DIEInfo &Info = CU.getInfo(Die);
Info.Prune &= ChildInfo.Prune;
}
/// Recursive helper to build the global DeclContext information and
/// gather the child->parent relationships in the original compile unit.
///
/// This function uses the same work list approach as lookForDIEsToKeep.
///
/// \return true when this DIE and all of its children are only
/// forward declarations to types defined in external clang modules
/// (i.e., forward declarations that are children of a DW_TAG_module).
static bool analyzeContextInfo(
const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces,
std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
bool InImportedModule = false) {
// LIFO work list.
std::vector<ContextWorklistItem> Worklist;
Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule);
while (!Worklist.empty()) {
ContextWorklistItem Current = Worklist.back();
Worklist.pop_back();
switch (Current.Type) {
case ContextWorklistItemType::UpdatePruning:
updatePruning(Current.Die, CU, ModulesEndOffset);
continue;
case ContextWorklistItemType::UpdateChildPruning:
updateChildPruning(Current.Die, CU, *Current.OtherInfo);
continue;
case ContextWorklistItemType::AnalyzeContextInfo:
break;
}
unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
// Clang imposes an ODR on modules(!) regardless of the language:
// "The module-id should consist of only a single identifier,
// which provides the name of the module being defined. Each
// module shall have a single definition."
//
// This does not extend to the types inside the modules:
// "[I]n C, this implies that if two structs are defined in
// different submodules with the same name, those two types are
// distinct types (but may be compatible types if their
// definitions match)."
//
// We treat non-C++ modules like namespaces for this reason.
if (Current.Die.getTag() == dwarf::DW_TAG_module &&
Current.ParentIdx == 0 &&
dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
CU.getClangModuleName()) {
Current.InImportedModule = true;
analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
ReportWarning);
}
Info.ParentIdx = Current.ParentIdx;
bool InClangModule = CU.isClangModule() || Current.InImportedModule;
if (CU.hasODR() || InClangModule) {
if (Current.Context) {
auto PtrInvalidPair = Contexts.getChildDeclContext(
*Current.Context, Current.Die, CU, InClangModule);
Current.Context = PtrInvalidPair.getPointer();
Info.Ctxt =
PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
if (Info.Ctxt)
Info.Ctxt->setDefinedInClangModule(InClangModule);
} else
Info.Ctxt = Current.Context = nullptr;
}
Info.Prune = Current.InImportedModule;
// Add children in reverse order to the worklist to effectively process
// them in order.
Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
for (auto Child : reverse(Current.Die.children())) {
CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
Worklist.emplace_back(
Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo);
Worklist.emplace_back(Child, Current.Context, Idx,
Current.InImportedModule);
}
}
return CU.getInfo(DIE).Prune;
}
static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
switch (Tag) {
default:
return false;
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_common_block:
case dwarf::DW_TAG_lexical_block:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_subprogram:
case dwarf::DW_TAG_subroutine_type:
case dwarf::DW_TAG_union_type:
return true;
}
llvm_unreachable("Invalid Tag");
}
void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
Context.clear();
for (DIEBlock *I : DIEBlocks)
I->~DIEBlock();
for (DIELoc *I : DIELocs)
I->~DIELoc();
DIEBlocks.clear();
DIELocs.clear();
DIEAlloc.Reset();
}
/// Check if a variable describing DIE should be kept.
/// \returns updated TraversalFlags.
unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
const DWARFDie &DIE,
CompileUnit::DIEInfo &MyInfo,
unsigned Flags) {
const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
// Global variables with constant value can always be kept.
if (!(Flags & TF_InFunctionScope) &&
Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
MyInfo.InDebugMap = true;
return Flags | TF_Keep;
}
// See if there is a relocation to a valid debug map entry inside this
// variable's location. The order is important here. We want to always check
// if the variable has a valid relocation, so that the DIEInfo is filled.
// However, we don't want a static variable in a function to force us to keep
// the enclosing function, unless requested explicitly.
const bool HasLiveMemoryLocation =
RelocMgr.hasLiveMemoryLocation(DIE, MyInfo);
if (!HasLiveMemoryLocation || ((Flags & TF_InFunctionScope) &&
!LLVM_UNLIKELY(Options.KeepFunctionForStatic)))
return Flags;
if (Options.Verbose) {
outs() << "Keeping variable DIE:";
DIDumpOptions DumpOpts;
DumpOpts.ChildRecurseDepth = 0;
DumpOpts.Verbose = Options.Verbose;
DIE.dump(outs(), 8 /* Indent */, DumpOpts);
}
return Flags | TF_Keep;
}
/// Check if a function describing DIE should be kept.
/// \returns updated TraversalFlags.
unsigned DWARFLinker::shouldKeepSubprogramDIE(
AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
unsigned Flags) {
Flags |= TF_InFunctionScope;
auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
if (!LowPc)
return Flags;
assert(LowPc.hasValue() && "low_pc attribute is not an address.");
if (!RelocMgr.hasLiveAddressRange(DIE, MyInfo))
return Flags;
if (Options.Verbose) {
outs() << "Keeping subprogram DIE:";
DIDumpOptions DumpOpts;
DumpOpts.ChildRecurseDepth = 0;
DumpOpts.Verbose = Options.Verbose;
DIE.dump(outs(), 8 /* Indent */, DumpOpts);
}
if (DIE.getTag() == dwarf::DW_TAG_label) {
if (Unit.hasLabelAt(*LowPc))
return Flags;
DWARFUnit &OrigUnit = Unit.getOrigUnit();
// FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
// that don't fall into the CU's aranges. This is wrong IMO. Debug info
// generation bugs aside, this is really wrong in the case of labels, where
// a label marking the end of a function will have a PC == CU's high_pc.
if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
.getValueOr(UINT64_MAX) <= LowPc)
return Flags;
Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
return Flags | TF_Keep;
}
Flags |= TF_Keep;
Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
if (!HighPc) {
reportWarning("Function without high_pc. Range will be discarded.\n", File,
&DIE);
return Flags;
}
// Replace the debug map range with a more accurate one.
Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust);
Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
return Flags;
}
/// Check if a DIE should be kept.
/// \returns updated TraversalFlags.
unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
const DWARFDie &DIE, const DWARFFile &File,
CompileUnit &Unit,
CompileUnit::DIEInfo &MyInfo,
unsigned Flags) {
switch (DIE.getTag()) {
case dwarf::DW_TAG_constant:
case dwarf::DW_TAG_variable:
return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
case dwarf::DW_TAG_subprogram:
case dwarf::DW_TAG_label:
return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
Flags);
case dwarf::DW_TAG_base_type:
// DWARF Expressions may reference basic types, but scanning them
// is expensive. Basic types are tiny, so just keep all of them.
case dwarf::DW_TAG_imported_module:
case dwarf::DW_TAG_imported_declaration:
case dwarf::DW_TAG_imported_unit:
// We always want to keep these.
return Flags | TF_Keep;
default:
break;
}
return Flags;
}
/// Helper that updates the completeness of the current DIE based on the
/// completeness of one of its children. It depends on the incompleteness of
/// the children already being computed.
static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
CompileUnit::DIEInfo &ChildInfo) {
switch (Die.getTag()) {
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_union_type:
break;
default:
return;
}
CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
if (ChildInfo.Incomplete || ChildInfo.Prune)
MyInfo.Incomplete = true;
}
/// Helper that updates the completeness of the current DIE based on the
/// completeness of the DIEs it references. It depends on the incompleteness of
/// the referenced DIE already being computed.
static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
CompileUnit::DIEInfo &RefInfo) {
switch (Die.getTag()) {
case dwarf::DW_TAG_typedef:
case dwarf::DW_TAG_member:
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_ptr_to_member_type:
case dwarf::DW_TAG_pointer_type:
break;
default:
return;
}
CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
if (MyInfo.Incomplete)
return;
if (RefInfo.Incomplete)
MyInfo.Incomplete = true;
}
/// Look at the children of the given DIE and decide whether they should be
/// kept.
void DWARFLinker::lookForChildDIEsToKeep(
const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
SmallVectorImpl<WorklistItem> &Worklist) {
// The TF_ParentWalk flag tells us that we are currently walking up the
// parent chain of a required DIE, and we don't want to mark all the children
// of the parents as kept (consider for example a DW_TAG_namespace node in
// the parent chain). There are however a set of DIE types for which we want
// to ignore that directive and still walk their children.
if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
Flags &= ~DWARFLinker::TF_ParentWalk;
// We're finished if this DIE has no children or we're walking the parent
// chain.
if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
return;
// Add children in reverse order to the worklist to effectively process them
// in order.
for (auto Child : reverse(Die.children())) {
// Add a worklist item before every child to calculate incompleteness right
// after the current child is processed.
CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
&ChildInfo);
Worklist.emplace_back(Child, CU, Flags);
}
}
/// Look at DIEs referenced by the given DIE and decide whether they should be
/// kept. All DIEs referenced though attributes should be kept.
void DWARFLinker::lookForRefDIEsToKeep(
const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
const UnitListTy &Units, const DWARFFile &File,
SmallVectorImpl<WorklistItem> &Worklist) {
bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
? (Flags & DWARFLinker::TF_ODR)
: CU.hasODR();
DWARFUnit &Unit = CU.getOrigUnit();
DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
for (const auto &AttrSpec : Abbrev->attributes()) {
DWARFFormValue Val(AttrSpec.Form);
if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
AttrSpec.Attr == dwarf::DW_AT_sibling) {
DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
Unit.getFormParams());
continue;
}
Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
CompileUnit *ReferencedCU;
if (auto RefDie =
resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
Info.Ctxt->isDefinedInClangModule();
// If the referenced DIE has a DeclContext that has already been
// emitted, then do not keep the one in this CU. We'll link to
// the canonical DIE in cloneDieReferenceAttribute.
//
// FIXME: compatibility with dsymutil-classic. UseODR shouldn't
// be necessary and could be advantageously replaced by
// ReferencedCU->hasODR() && CU.hasODR().
//
// FIXME: compatibility with dsymutil-classic. There is no
// reason not to unique ref_addr references.
if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseOdr || IsModuleRef) &&
Info.Ctxt &&
Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
continue;
// Keep a module forward declaration if there is no definition.
if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
Info.Ctxt->getCanonicalDIEOffset()))
Info.Prune = false;
ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
}
}
unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
// Add referenced DIEs in reverse order to the worklist to effectively
// process them in order.
for (auto &P : reverse(ReferencedDIEs)) {
// Add a worklist item before every child to calculate incompleteness right
// after the current child is processed.
CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
&Info);
Worklist.emplace_back(P.first, P.second,
DWARFLinker::TF_Keep |
DWARFLinker::TF_DependencyWalk | ODRFlag);
}
}
/// Look at the parent of the given DIE and decide whether they should be kept.
void DWARFLinker::lookForParentDIEsToKeep(
unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
SmallVectorImpl<WorklistItem> &Worklist) {
// Stop if we encounter an ancestor that's already marked as kept.
if (CU.getInfo(AncestorIdx).Keep)
return;
DWARFUnit &Unit = CU.getOrigUnit();
DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
Worklist.emplace_back(ParentDIE, CU, Flags);
}
/// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
/// information in \p CU's DIEInfo.
///
/// This function is the entry point of the DIE selection algorithm. It is
/// expected to walk the DIE tree in file order and (though the mediation of
/// its helper) call hasValidRelocation() on each DIE that might be a 'root
/// DIE' (See DwarfLinker class comment).
///
/// While walking the dependencies of root DIEs, this function is also called,
/// but during these dependency walks the file order is not respected. The
/// TF_DependencyWalk flag tells us which kind of traversal we are currently
/// doing.
///
/// The recursive algorithm is implemented iteratively as a work list because
/// very deep recursion could exhaust the stack for large projects. The work
/// list acts as a scheduler for different types of work that need to be
/// performed.
///
/// The recursive nature of the algorithm is simulated by running the "main"
/// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
/// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
/// fixing up a computed property (UpdateChildIncompleteness,
/// UpdateRefIncompleteness).
///
/// The return value indicates whether the DIE is incomplete.
void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
RangesTy &Ranges, const UnitListTy &Units,
const DWARFDie &Die, const DWARFFile &File,
CompileUnit &Cu, unsigned Flags) {
// LIFO work list.
SmallVector<WorklistItem, 4> Worklist;
Worklist.emplace_back(Die, Cu, Flags);
while (!Worklist.empty()) {
WorklistItem Current = Worklist.pop_back_val();
// Look at the worklist type to decide what kind of work to perform.
switch (Current.Type) {
case WorklistItemType::UpdateChildIncompleteness:
updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
continue;
case WorklistItemType::UpdateRefIncompleteness:
updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
continue;
case WorklistItemType::LookForChildDIEsToKeep:
lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
continue;
case WorklistItemType::LookForRefDIEsToKeep:
lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
Worklist);
continue;
case WorklistItemType::LookForParentDIEsToKeep:
lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
Worklist);
continue;
case WorklistItemType::LookForDIEsToKeep:
break;
}
unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
if (MyInfo.Prune)
continue;
// If the Keep flag is set, we are marking a required DIE's dependencies.
// If our target is already marked as kept, we're all set.
bool AlreadyKept = MyInfo.Keep;
if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
continue;
// We must not call shouldKeepDIE while called from keepDIEAndDependencies,
// because it would screw up the relocation finding logic.
if (!(Current.Flags & TF_DependencyWalk))
Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
Current.CU, MyInfo, Current.Flags);
// Finish by looking for child DIEs. Because of the LIFO worklist we need
// to schedule that work before any subsequent items are added to the
// worklist.
Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
WorklistItemType::LookForChildDIEsToKeep);
if (AlreadyKept || !(Current.Flags & TF_Keep))
continue;
// If it is a newly kept DIE mark it as well as all its dependencies as
// kept.
MyInfo.Keep = true;
// We're looking for incomplete types.
MyInfo.Incomplete =
Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
Current.Die.getTag() != dwarf::DW_TAG_member &&
dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
// After looking at the parent chain, look for referenced DIEs. Because of
// the LIFO worklist we need to schedule that work before any subsequent
// items are added to the worklist.
Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
WorklistItemType::LookForRefDIEsToKeep);
bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
: Current.CU.hasODR();
unsigned ODRFlag = UseOdr ? TF_ODR : 0;
unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
// Now schedule the parent walk.
Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
}
}
/// Assign an abbreviation number to \p Abbrev.
///
/// Our DIEs get freed after every DebugMapObject has been processed,
/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
/// the instances hold by the DIEs. When we encounter an abbreviation
/// that we don't know, we create a permanent copy of it.
void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
// Check the set for priors.
FoldingSetNodeID ID;
Abbrev.Profile(ID);
void *InsertToken;
DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
// If it's newly added.
if (InSet) {
// Assign existing abbreviation number.
Abbrev.setNumber(InSet->getNumber());
} else {
// Add to abbreviation list.
Abbreviations.push_back(
std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
for (const auto &Attr : Abbrev.getData())
Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
// Assign the unique abbreviation number.
Abbrev.setNumber(Abbreviations.size());
Abbreviations.back()->setNumber(Abbreviations.size());
}
}
unsigned DWARFLinker::DIECloner::cloneStringAttribute(
DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
Optional<const char *> String = dwarf::toString(Val);
if (!String)
return 0;
// Switch everything to out of line strings.
auto StringEntry = StringPool.getEntry(*String);
// Update attributes info.
if (AttrSpec.Attr == dwarf::DW_AT_name)
Info.Name = StringEntry;
else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
AttrSpec.Attr == dwarf::DW_AT_linkage_name)
Info.MangledName = StringEntry;
Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
DIEInteger(StringEntry.getOffset()));
return 4;
}
unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
CompileUnit &Unit) {
const DWARFUnit &U = Unit.getOrigUnit();
uint64_t Ref = *Val.getAsReference();
DIE *NewRefDie = nullptr;
CompileUnit *RefUnit = nullptr;
DeclContext *Ctxt = nullptr;
DWARFDie RefDie =
Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
// If the referenced DIE is not found, drop the attribute.
if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
return 0;
CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
// If we already have emitted an equivalent DeclContext, just point
// at it.
if (isODRAttribute(AttrSpec.Attr)) {
Ctxt = RefInfo.Ctxt;
if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
dwarf::DW_FORM_ref_addr, Attr);
return U.getRefAddrByteSize();
}
}
if (!RefInfo.Clone) {
assert(Ref > InputDIE.getOffset());
// We haven't cloned this DIE yet. Just create an empty one and
// store it. It'll get really cloned when we process it.
RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
}
NewRefDie = RefInfo.Clone;
if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
(Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
// We cannot currently rely on a DIEEntry to emit ref_addr
// references, because the implementation calls back to DwarfDebug
// to find the unit offset. (We don't have a DwarfDebug)
// FIXME: we should be able to design DIEEntry reliance on
// DwarfDebug away.
uint64_t Attr;
if (Ref < InputDIE.getOffset()) {
// We must have already cloned that DIE.
uint32_t NewRefOffset =
RefUnit->getStartOffset() + NewRefDie->getOffset();
Attr = NewRefOffset;
Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
} else {
// A forward reference. Note and fixup later.
Attr = 0xBADDEF;
Unit.noteForwardReference(
NewRefDie, RefUnit, Ctxt,
Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
}
return U.getRefAddrByteSize();
}
Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
return AttrSize;
}
void DWARFLinker::DIECloner::cloneExpression(
DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
using Encoding = DWARFExpression::Operation::Encoding;
uint64_t OpOffset = 0;
for (auto &Op : Expression) {
auto Description = Op.getDescription();
// DW_OP_const_type is variable-length and has 3
// operands. DWARFExpression thus far only supports 2.
auto Op0 = Description.Op[0];
auto Op1 = Description.Op[1];
if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
(Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
Linker.reportWarning("Unsupported DW_OP encoding.", File);
if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
(Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
// This code assumes that the other non-typeref operand fits into 1 byte.
assert(OpOffset < Op.getEndOffset());
uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
assert(ULEBsize <= 16);
// Copy over the operation.
OutputBuffer.push_back(Op.getCode());
uint64_t RefOffset;
if (Op1 == Encoding::SizeNA) {
RefOffset = Op.getRawOperand(0);
} else {
OutputBuffer.push_back(Op.getRawOperand(0));
RefOffset = Op.getRawOperand(1);
}
uint32_t Offset = 0;
// Look up the base type. For DW_OP_convert, the operand may be 0 to
// instead indicate the generic type. The same holds for
// DW_OP_reinterpret, which is currently not supported.
if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
if (DIE *Clone = Info.Clone)
Offset = Clone->getOffset();
else
Linker.reportWarning(
"base type ref doesn't point to DW_TAG_base_type.", File);
}
uint8_t ULEB[16];
unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
if (RealSize > ULEBsize) {
// Emit the generic type as a fallback.
RealSize = encodeULEB128(0, ULEB, ULEBsize);
Linker.reportWarning("base type ref doesn't fit.", File);
}
assert(RealSize == ULEBsize && "padding failed");
ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
} else {
// Copy over everything else unmodified.
StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
OutputBuffer.append(Bytes.begin(), Bytes.end());
}