1//===- DWARFLinkerCompileUnit.h ---------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_LIB_DWARFLINKER_PARALLEL_DWARFLINKERCOMPILEUNIT_H
10#define LLVM_LIB_DWARFLINKER_PARALLEL_DWARFLINKERCOMPILEUNIT_H
11
12#include "DWARFLinkerUnit.h"
13#include "llvm/DWARFLinker/DWARFFile.h"
14#include <limits>
15#include <optional>
16
17namespace llvm {
18namespace dwarf_linker {
19namespace parallel {
20
21using OffsetToUnitTy = function_ref<CompileUnit *(uint64_t Offset)>;
22
23struct AttributesInfo;
24class SyntheticTypeNameBuilder;
25class DIEGenerator;
26class TypeUnit;
27class DependencyTracker;
28
29class CompileUnit;
30
31/// This is a helper structure which keeps a debug info entry
32/// with it's containing compilation unit.
33struct UnitEntryPairTy {
34 UnitEntryPairTy() = default;
35 UnitEntryPairTy(CompileUnit *CU, const DWARFDebugInfoEntry *DieEntry)
36 : CU(CU), DieEntry(DieEntry) {}
37
38 CompileUnit *CU = nullptr;
39 const DWARFDebugInfoEntry *DieEntry = nullptr;
40
41 UnitEntryPairTy getNamespaceOrigin();
42 std::optional<UnitEntryPairTy> getParent();
43};
44
45enum ResolveInterCUReferencesMode : bool {
46 Resolve = true,
47 AvoidResolving = false,
48};
49
50/// Stores all information related to a compile unit, be it in its original
51/// instance of the object file or its brand new cloned and generated DIE tree.
52/// NOTE: we need alignment of at least 8 bytes as we use
53/// PointerIntPair<CompileUnit *, 3> in the DependencyTracker.h
54class alignas(8) CompileUnit : public DwarfUnit {
55public:
56 /// The stages of new compile unit processing.
57 enum class Stage : uint8_t {
58 /// Created, linked with input DWARF file.
59 CreatedNotLoaded = 0,
60
61 /// Input DWARF is loaded.
62 Loaded,
63
64 /// DIEs with a live address are found. Marking a unit reads whether the
65 /// DIEs it references in other units have an address, so every
66 /// inter-connected unit gets here before any of them is marked.
67 LiveRootsCollected,
68
69 /// Input DWARF is analysed(DIEs pointing to the real code section and the
70 /// DIEs they depend on are marked).
71 LivenessAnalysisDone,
72
73 /// Check if dependencies have incompatible placement.
74 /// If that is the case modify placement to be compatible.
75 UpdateDependenciesCompleteness,
76
77 /// Type names assigned to DIEs.
78 TypeNamesAssigned,
79
80 /// Output DWARF is generated.
81 Cloned,
82
83 /// Offsets inside patch records are updated.
84 PatchesUpdated,
85
86 /// Resources(Input DWARF, Output DWARF tree) are released.
87 Cleaned,
88
89 /// Compile Unit should be skipped
90 Skipped
91 };
92
93 CompileUnit(LinkingGlobalData &GlobalData, unsigned ID,
94 StringRef ClangModuleName, DWARFFile &File,
95 OffsetToUnitTy UnitFromOffset, dwarf::FormParams Format,
96 llvm::endianness Endianess);
97
98 CompileUnit(LinkingGlobalData &GlobalData, DWARFUnit &OrigUnit, unsigned ID,
99 StringRef ClangModuleName, DWARFFile &File,
100 OffsetToUnitTy UnitFromOffset, dwarf::FormParams Format,
101 llvm::endianness Endianess);
102
103 /// Returns stage of overall processing.
104 Stage getStage() const { return Stage; }
105
106 /// Returns raw DW_AT_language of the input compile unit.
107 std::optional<uint16_t> getLanguage() const { return Language; }
108
109 /// Set stage of overall processing.
110 void setStage(Stage Stage) { this->Stage = Stage; }
111
112 /// Loads unit line table.
113 void loadLineTable();
114
115 /// Returns name of the file for the \p FileIdx
116 /// from the unit`s line table.
117 StringEntry *getFileName(unsigned FileIdx, StringPool &GlobalStrings);
118
119 /// Returns DWARFFile containing this compile unit.
120 const DWARFFile &getContainingFile() const { return File; }
121
122 std::string remapPath(StringRef Path) const override {
123 return File.remapPath(Path);
124 }
125
126 /// Appends the names of the DW_TAG_module enclosing \p DieEntry, outermost
127 /// first. Returns false when one of them has no name making the module
128 /// unidentifiable across units.
129 bool getModulePath(const DWARFDebugInfoEntry *DieEntry,
130 SmallVectorImpl<char> &Path);
131
132 /// Must run while the output offsets are still available, and once they are
133 /// final.
134 void noteModuleAnchors();
135
136 /// Set deterministic priority for type DIE allocation ordering. Units compare
137 /// by \p ObjFileIdx first and by \p LocalIdx second.
138 /// Lower priority values win when multiple CUs race to define the same type.
139 llvm::Error setPriority(uint64_t ObjFileIdx, uint64_t LocalIdx);
140
141 uint64_t getPriority() const { return Priority; }
142
143 /// Load DIEs of input compilation unit. \returns true if input DIEs
144 /// successfully loaded.
145 bool loadInputDIEs();
146
147 /// Reset compile units data(results of liveness analysis, clonning)
148 /// if current stage greater than Stage::Loaded. We need to reset data
149 /// as we are going to repeat stages.
150 void maybeResetToLoadedStage();
151
152 /// Collect references to parseable Swift interfaces in imported
153 /// DW_TAG_module blocks. The entries are staged on the CompileUnit and
154 /// merged into the shared map after the parallel analysis phase.
155 void analyzeImportedModule(const DWARFDebugInfoEntry *DieEntry);
156
157 /// Merge the Swift interface entries collected by analyzeImportedModule
158 /// into \p Map, emitting a warning for each conflicting path. Must be
159 /// called serially after analysis has completed.
160 void mergeSwiftInterfaces(DWARFLinkerBase::SwiftInterfacesMapTy &Map);
161
162 /// Navigate DWARF tree and set die properties.
163 void analyzeDWARFStructure() {
164 analyzeDWARFStructureRec(DieEntry: getUnitDIE().getDebugInfoEntry(), IsODRUnavailableFunctionScope: false);
165 }
166
167 /// Cleanup unneeded resources after compile unit is cloned.
168 void cleanupDataAfterClonning();
169
170 /// After cloning stage the output DIEs offsets are deallocated.
171 /// This method copies output offsets for referenced DIEs into DIEs patches.
172 void updateDieRefPatchesWithClonedOffsets();
173
174 /// Search for subprograms and variables referencing live code.
175 void collectLiveRoots();
176
177 /// Discover the DIEs the live roots depend on. Mark live DIEs, set placement
178 /// for DIEs.
179 bool resolveDependenciesAndMarkLiveness(
180 bool InterCUProcessingStarted,
181 std::atomic<bool> &HasNewInterconnectedCUs);
182
183 /// Check dependend DIEs for incompatible placement.
184 /// Make placement to be consistent.
185 bool updateDependenciesCompleteness();
186
187 /// Check DIEs to have a consistent marking(keep marking, placement marking).
188 void verifyDependencies();
189
190 /// Search for type entries and assign names.
191 Error assignTypeNames(TypePool &TypePoolRef);
192
193 /// Kinds of placement for the output die.
194 enum DieOutputPlacement : uint8_t {
195 NotSet = 0,
196
197 /// Corresponding DIE goes to the type table only.
198 TypeTable = 1,
199
200 /// Corresponding DIE goes to the plain dwarf only.
201 PlainDwarf = 2,
202
203 /// Corresponding DIE goes to type table and to plain dwarf.
204 Both = 3,
205 };
206
207 /// Information gathered about source DIEs.
208 struct DIEInfo {
209 DIEInfo() = default;
210 DIEInfo(const DIEInfo &Other) { Flags = Other.Flags.load(); }
211 DIEInfo &operator=(const DIEInfo &Other) {
212 Flags = Other.Flags.load();
213 return *this;
214 }
215
216 /// Data member keeping various flags.
217 std::atomic<uint16_t> Flags = {0};
218
219 /// \returns Placement kind for the corresponding die.
220 DieOutputPlacement getPlacement() const {
221 return DieOutputPlacement(Flags & 0x7);
222 }
223
224 /// Sets Placement kind for the corresponding die.
225 void setPlacement(DieOutputPlacement Placement) {
226 auto InputData = Flags.load();
227 while (!Flags.compare_exchange_weak(i1&: InputData,
228 i2: ((InputData & ~0x7) | Placement))) {
229 }
230 }
231
232 /// Unsets Placement kind for the corresponding die.
233 void unsetPlacement() {
234 auto InputData = Flags.load();
235 while (!Flags.compare_exchange_weak(i1&: InputData, i2: (InputData & ~0x7))) {
236 }
237 }
238
239 /// Sets Placement kind for the corresponding die.
240 bool setPlacementIfUnset(DieOutputPlacement Placement) {
241 auto InputData = Flags.load();
242 if ((InputData & 0x7) == NotSet)
243 if (Flags.compare_exchange_strong(i1&: InputData, i2: (InputData | Placement)))
244 return true;
245
246 return false;
247 }
248
249 /// Atomically joins \p Placement into the current placement: the
250 /// least-upper-bound of the lattice NotSet < {TypeTable, PlainDwarf} <
251 /// Both, which is a plain OR because the values are bit flags. The join is
252 /// monotone and never clears a bit, so unlike setPlacement it composes
253 /// correctly when applied concurrently from several marks.
254 void joinPlacement(DieOutputPlacement Placement) {
255 auto InputData = Flags.load();
256 while (!Flags.compare_exchange_weak(i1&: InputData, i2: (InputData | Placement))) {
257 }
258 }
259
260 /// Atomically joins \p Placement for a DW_TAG_variable, for which
261 /// PlainDwarf is absorbing because a variable cannot occupy the type table
262 /// and plain DWARF at once. Once the placement is (or concurrently becomes)
263 /// PlainDwarf it stays PlainDwarf, otherwise \p Placement is OR-joined.
264 /// Recomputing inside the compare_exchange loop keeps a racing PlainDwarf
265 /// mark from turning the variable into Both.
266 void joinVariablePlacement(DieOutputPlacement Placement) {
267 auto InputData = Flags.load();
268 uint16_t Desired;
269 do {
270 DieOutputPlacement Current = DieOutputPlacement(InputData & 0x7);
271 DieOutputPlacement Joined =
272 (Current == PlainDwarf || Current == Both)
273 ? PlainDwarf
274 : DieOutputPlacement(Current | Placement);
275 Desired = (InputData & ~0x7) | Joined;
276 } while (!Flags.compare_exchange_weak(i1&: InputData, i2: Desired));
277 }
278
279#define SINGLE_FLAG_METHODS_SET(Name, Value) \
280 bool get##Name() const { return Flags & Value; } \
281 void set##Name() { \
282 auto InputData = Flags.load(); \
283 while (!Flags.compare_exchange_weak(InputData, InputData | Value)) { \
284 } \
285 } \
286 void unset##Name() { \
287 auto InputData = Flags.load(); \
288 while (!Flags.compare_exchange_weak(InputData, InputData & ~Value)) { \
289 } \
290 }
291
292 /// DIE is a part of the linked output.
293 SINGLE_FLAG_METHODS_SET(Keep, 0x08)
294
295 /// DIE has children which are part of the linked output.
296 SINGLE_FLAG_METHODS_SET(KeepPlainChildren, 0x10)
297
298 /// DIE has children which are part of the type table.
299 SINGLE_FLAG_METHODS_SET(KeepTypeChildren, 0x20)
300
301 /// DIE is in module scope.
302 SINGLE_FLAG_METHODS_SET(IsInMouduleScope, 0x40)
303
304 /// DIE is in function scope.
305 SINGLE_FLAG_METHODS_SET(IsInFunctionScope, 0x80)
306
307 /// DIE is in anonymous namespace scope.
308 SINGLE_FLAG_METHODS_SET(IsInAnonNamespaceScope, 0x100)
309
310 /// DIE is available for ODR type deduplication.
311 SINGLE_FLAG_METHODS_SET(ODRAvailable, 0x200)
312
313 /// Track liveness for the DIE.
314 SINGLE_FLAG_METHODS_SET(TrackLiveness, 0x400)
315
316 /// Track liveness for the DIE.
317 SINGLE_FLAG_METHODS_SET(HasAnAddress, 0x800)
318
319 /// DIE is a function-local variable with a live address that does not keep
320 /// its function, and is kept wherever the function is.
321 SINGLE_FLAG_METHODS_SET(KeepWithParent, 0x1000)
322
323 void unsetFlagsWhichSetDuringLiveAnalysis() {
324 auto InputData = Flags.load();
325 while (!Flags.compare_exchange_weak(
326 i1&: InputData, i2: InputData & ~(0x7 | 0x8 | 0x10 | 0x20))) {
327 }
328 }
329
330 /// Erase all flags.
331 void eraseData() { Flags = 0; }
332
333#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
334 LLVM_DUMP_METHOD void dump();
335#endif
336
337 bool needToPlaceInTypeTable() const {
338 return (getKeep() && (getPlacement() == CompileUnit::TypeTable ||
339 getPlacement() == CompileUnit::Both)) ||
340 getKeepTypeChildren();
341 }
342
343 bool needToKeepInPlainDwarf() const {
344 return (getKeep() && (getPlacement() == CompileUnit::PlainDwarf ||
345 getPlacement() == CompileUnit::Both)) ||
346 getKeepPlainChildren();
347 }
348 };
349
350 /// \defgroup Group of functions returning DIE info.
351 ///
352 /// @{
353
354 /// \p Idx index of the DIE.
355 /// \returns DieInfo descriptor.
356 DIEInfo &getDIEInfo(unsigned Idx) { return DieInfoArray[Idx]; }
357
358 /// \p Idx index of the DIE.
359 /// \returns DieInfo descriptor.
360 const DIEInfo &getDIEInfo(unsigned Idx) const { return DieInfoArray[Idx]; }
361
362 /// \p Idx index of the DIE.
363 /// \returns DieInfo descriptor.
364 DIEInfo &getDIEInfo(const DWARFDebugInfoEntry *Entry) {
365 return DieInfoArray[getOrigUnit().getDIEIndex(Die: Entry)];
366 }
367
368 /// \p Idx index of the DIE.
369 /// \returns DieInfo descriptor.
370 const DIEInfo &getDIEInfo(const DWARFDebugInfoEntry *Entry) const {
371 return DieInfoArray[getOrigUnit().getDIEIndex(Die: Entry)];
372 }
373
374 /// \p Die
375 /// \returns PlainDieInfo descriptor.
376 DIEInfo &getDIEInfo(const DWARFDie &Die) {
377 return DieInfoArray[getOrigUnit().getDIEIndex(D: Die)];
378 }
379
380 /// \p Die
381 /// \returns PlainDieInfo descriptor.
382 const DIEInfo &getDIEInfo(const DWARFDie &Die) const {
383 return DieInfoArray[getOrigUnit().getDIEIndex(D: Die)];
384 }
385
386 /// \p Idx index of the DIE.
387 /// \returns DieInfo descriptor.
388 uint64_t getDieOutOffset(uint32_t Idx) {
389 return reinterpret_cast<std::atomic<uint64_t> *>(&OutDieOffsetArray[Idx])
390 ->load();
391 }
392
393 /// \p Idx index of the DIE.
394 /// \returns type entry.
395 TypeEntry *getDieTypeEntry(uint32_t Idx) {
396 return reinterpret_cast<std::atomic<TypeEntry *> *>(&TypeEntries[Idx])
397 ->load();
398 }
399
400 /// \p InputDieEntry debug info entry.
401 /// \returns DieInfo descriptor.
402 uint64_t getDieOutOffset(const DWARFDebugInfoEntry *InputDieEntry) {
403 return reinterpret_cast<std::atomic<uint64_t> *>(
404 &OutDieOffsetArray[getOrigUnit().getDIEIndex(Die: InputDieEntry)])
405 ->load();
406 }
407
408 /// \p InputDieEntry debug info entry.
409 /// \returns type entry.
410 TypeEntry *getDieTypeEntry(const DWARFDebugInfoEntry *InputDieEntry) {
411 return reinterpret_cast<std::atomic<TypeEntry *> *>(
412 &TypeEntries[getOrigUnit().getDIEIndex(Die: InputDieEntry)])
413 ->load();
414 }
415
416 /// \p Idx index of the DIE.
417 /// \returns DieInfo descriptor.
418 void rememberDieOutOffset(uint32_t Idx, uint64_t Offset) {
419 reinterpret_cast<std::atomic<uint64_t> *>(&OutDieOffsetArray[Idx])
420 ->store(i: Offset);
421 }
422
423 /// \p Idx index of the DIE.
424 /// \p Type entry.
425 void setDieTypeEntry(uint32_t Idx, TypeEntry *Entry) {
426 reinterpret_cast<std::atomic<TypeEntry *> *>(&TypeEntries[Idx])
427 ->store(p: Entry);
428 }
429
430 /// \p InputDieEntry debug info entry.
431 /// \p Type entry.
432 void setDieTypeEntry(const DWARFDebugInfoEntry *InputDieEntry,
433 TypeEntry *Entry) {
434 reinterpret_cast<std::atomic<TypeEntry *> *>(
435 &TypeEntries[getOrigUnit().getDIEIndex(Die: InputDieEntry)])
436 ->store(p: Entry);
437 }
438
439 /// @}
440
441 /// Returns value of DW_AT_low_pc attribute.
442 std::optional<uint64_t> getLowPc() const { return LowPc; }
443
444 /// Returns value of DW_AT_high_pc attribute.
445 uint64_t getHighPc() const { return HighPc; }
446
447 /// Returns true if there is a label corresponding to the specified \p Addr.
448 bool hasLabelAt(uint64_t Addr) const { return Labels.count(Val: Addr); }
449
450 /// Add the low_pc of a label that is relocated by applying
451 /// offset \p PCOffset.
452 void addLabelLowPc(uint64_t LabelLowPc, int64_t PcOffset);
453
454 /// Resolve the DIE attribute reference that has been extracted in \p
455 /// RefValue. The resulting DIE might be in another CompileUnit.
456 /// \returns referenced die and corresponding compilation unit.
457 /// compilation unit is null if reference could not be resolved.
458 std::optional<UnitEntryPairTy>
459 resolveDIEReference(const DWARFFormValue &RefValue,
460 ResolveInterCUReferencesMode CanResolveInterCUReferences);
461
462 std::optional<UnitEntryPairTy>
463 resolveDIEReference(const DWARFDebugInfoEntry *DieEntry,
464 dwarf::Attribute Attr,
465 ResolveInterCUReferencesMode CanResolveInterCUReferences);
466
467 /// @}
468
469 /// Add a function range [\p LowPC, \p HighPC) that is relocated by applying
470 /// offset \p PCOffset.
471 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
472
473 /// Returns function ranges of this unit.
474 const RangesTy &getFunctionRanges() const { return Ranges; }
475
476 /// Record that a DW_AT_LLVM_stmt_sequence attribute on this unit
477 /// references the input line-table sequence whose header sits at
478 /// \p InputStmtSeqOffset. Resolution of that offset to an input
479 /// first-row index (via parser results plus a manual boundary-based
480 /// fallback) happens in a post-cloning pass, before \p V is rewritten
481 /// to the byte offset of the matching output sequence. Keying on row
482 /// index rather than address avoids collisions when two input
483 /// sequences would relocate to the same output address (e.g. ICF).
484 void noteStmtSeqListAttribute(DIEValue *V, uint64_t InputStmtSeqOffset) {
485 StmtSeqListAttributes.push_back(Elt: {.Value: V, .InputStmtSeqOffset: InputStmtSeqOffset});
486 }
487
488 /// Clone and emit this compilation unit.
489 Error
490 cloneAndEmit(std::optional<std::reference_wrapper<const Triple>> TargetTriple,
491 TypeUnit *ArtificialTypeUnit);
492
493 /// Clone and emit debug locations(.debug_loc/.debug_loclists).
494 Error cloneAndEmitDebugLocations();
495
496 /// Clone and emit ranges.
497 Error cloneAndEmitRanges();
498
499 /// Clone and emit debug macros(.debug_macinfo/.debug_macro).
500 Error cloneAndEmitDebugMacro();
501
502 // Clone input DIE entry. \p SiblingOrdinal is this DIE's position in its
503 // parent's child list, or UINT32_MAX for the unit DIE.
504 std::pair<DIE *, TypeEntry *>
505 cloneDIE(const DWARFDebugInfoEntry *InputDieEntry,
506 TypeEntry *ClonedParentTypeDIE, uint64_t OutOffset,
507 std::optional<int64_t> FuncAddressAdjustment,
508 std::optional<int64_t> VarAddressAdjustment,
509 BumpPtrAllocator &Allocator, TypeUnit *ArtificialTypeUnit,
510 uint32_t SiblingOrdinal = std::numeric_limits<uint32_t>::max());
511
512 // Clone and emit line table.
513 Error cloneAndEmitLineTable(const Triple &TargetTriple);
514
515 /// Clone attribute location axpression.
516 void cloneDieAttrExpression(const DWARFExpression &InputExpression,
517 SmallVectorImpl<uint8_t> &OutputExpression,
518 SectionDescriptor &Section,
519 std::optional<int64_t> VarAddressAdjustment,
520 OffsetsPtrVector &PatchesOffsets);
521
522 /// Returns index(inside .debug_addr) of an address.
523 uint64_t getDebugAddrIndex(uint64_t Addr) {
524 return DebugAddrIndexMap.getValueIndex(Value: Addr);
525 }
526
527 /// Returns directory and file from the line table by index.
528 std::optional<std::pair<StringRef, StringRef>>
529 getDirAndFilenameFromLineTable(const DWARFFormValue &FileIdxValue);
530
531 /// Returns directory and file from the line table by index.
532 std::optional<std::pair<StringRef, StringRef>>
533 getDirAndFilenameFromLineTable(uint64_t FileIdx);
534
535 /// \defgroup Helper methods to access OrigUnit.
536 ///
537 /// @{
538
539 /// Returns paired compile unit from input DWARF.
540 DWARFUnit &getOrigUnit() const {
541 assert(OrigUnit != nullptr);
542 return *OrigUnit;
543 }
544
545 const DWARFDebugInfoEntry *
546 getFirstChildEntry(const DWARFDebugInfoEntry *Die) const {
547 assert(OrigUnit != nullptr);
548 return OrigUnit->getFirstChildEntry(Die);
549 }
550
551 const DWARFDebugInfoEntry *
552 getSiblingEntry(const DWARFDebugInfoEntry *Die) const {
553 assert(OrigUnit != nullptr);
554 return OrigUnit->getSiblingEntry(Die);
555 }
556
557 DWARFDie getParent(const DWARFDebugInfoEntry *Die) {
558 assert(OrigUnit != nullptr);
559 return OrigUnit->getParent(Die);
560 }
561
562 DWARFDie getDIEAtIndex(unsigned Index) {
563 assert(OrigUnit != nullptr);
564 return OrigUnit->getDIEAtIndex(Index);
565 }
566
567 const DWARFDebugInfoEntry *getDebugInfoEntry(unsigned Index) const {
568 assert(OrigUnit != nullptr);
569 return OrigUnit->getDebugInfoEntry(Index);
570 }
571
572 DWARFDie getUnitDIE(bool ExtractUnitDIEOnly = true) {
573 assert(OrigUnit != nullptr);
574 return OrigUnit->getUnitDIE(ExtractUnitDIEOnly);
575 }
576
577 DWARFDie getDIE(const DWARFDebugInfoEntry *Die) {
578 assert(OrigUnit != nullptr);
579 return DWARFDie(OrigUnit, Die);
580 }
581
582 uint32_t getDIEIndex(const DWARFDebugInfoEntry *Die) const {
583 assert(OrigUnit != nullptr);
584 return OrigUnit->getDIEIndex(Die);
585 }
586
587 uint32_t getDIEIndex(const DWARFDie &Die) const {
588 assert(OrigUnit != nullptr);
589 return OrigUnit->getDIEIndex(D: Die);
590 }
591
592 std::optional<DWARFFormValue> find(uint32_t DieIdx,
593 ArrayRef<dwarf::Attribute> Attrs) const {
594 assert(OrigUnit != nullptr);
595 return find(Die: OrigUnit->getDebugInfoEntry(Index: DieIdx), Attrs);
596 }
597
598 std::optional<DWARFFormValue> find(const DWARFDebugInfoEntry *Die,
599 ArrayRef<dwarf::Attribute> Attrs) const {
600 if (!Die)
601 return std::nullopt;
602 auto AbbrevDecl = Die->getAbbreviationDeclarationPtr();
603 if (AbbrevDecl) {
604 for (auto Attr : Attrs) {
605 if (auto Value = AbbrevDecl->getAttributeValue(DIEOffset: Die->getOffset(), Attr,
606 U: *OrigUnit))
607 return Value;
608 }
609 }
610 return std::nullopt;
611 }
612
613 std::optional<uint32_t> getDIEIndexForOffset(uint64_t Offset) {
614 return OrigUnit->getDIEIndexForOffset(Offset);
615 }
616
617 /// @}
618
619 /// \defgroup Methods used for reporting warnings and errors:
620 ///
621 /// @{
622
623 void warn(const Twine &Warning, const DWARFDie *DIE = nullptr) {
624 GlobalData.warn(Warning, Context: getUnitName(), DIE);
625 }
626
627 void warn(Error Warning, const DWARFDie *DIE = nullptr) {
628 handleAllErrors(E: std::move(Warning), Handlers: [&](ErrorInfoBase &Info) {
629 GlobalData.warn(Warning: Info.message(), Context: getUnitName(), DIE);
630 });
631 }
632
633 void warn(const Twine &Warning, const DWARFDebugInfoEntry *DieEntry) {
634 if (DieEntry != nullptr) {
635 DWARFDie DIE(&getOrigUnit(), DieEntry);
636 GlobalData.warn(Warning, Context: getUnitName(), DIE: &DIE);
637 return;
638 }
639
640 GlobalData.warn(Warning, Context: getUnitName());
641 }
642
643 void error(const Twine &Err, const DWARFDie *DIE = nullptr) {
644 GlobalData.warn(Warning: Err, Context: getUnitName(), DIE);
645 }
646
647 void error(Error Err, const DWARFDie *DIE = nullptr) {
648 handleAllErrors(E: std::move(Err), Handlers: [&](ErrorInfoBase &Info) {
649 GlobalData.error(Err: Info.message(), Context: getUnitName(), DIE);
650 });
651 }
652
653 /// @}
654
655 /// Save specified accelerator info \p Info.
656 void saveAcceleratorInfo(const DwarfUnit::AccelInfo &Info) {
657 AcceleratorRecords.add(Item: Info);
658 }
659
660 /// Enumerates all units accelerator records.
661 void
662 forEachAcceleratorRecord(function_ref<void(AccelInfo &)> Handler) override {
663 AcceleratorRecords.forEach(Handler);
664 }
665
666 /// Output unit selector.
667 class OutputUnitVariantPtr {
668 public:
669 OutputUnitVariantPtr(CompileUnit *U);
670 OutputUnitVariantPtr(TypeUnit *U);
671
672 /// Accessor for common functionality.
673 DwarfUnit *operator->();
674
675 bool isCompileUnit();
676
677 bool isTypeUnit();
678
679 /// Returns CompileUnit if applicable.
680 CompileUnit *getAsCompileUnit();
681
682 /// Returns TypeUnit if applicable.
683 TypeUnit *getAsTypeUnit();
684
685 protected:
686 PointerUnion<CompileUnit *, TypeUnit *> Ptr;
687 };
688
689private:
690 /// Navigate DWARF tree recursively and set die properties.
691 void analyzeDWARFStructureRec(const DWARFDebugInfoEntry *DieEntry,
692 bool IsODRUnavailableFunctionScope);
693
694 struct LinkedLocationExpressionsWithOffsetPatches {
695 DWARFLocationExpression Expression;
696 OffsetsPtrVector Patches;
697 };
698 using LinkedLocationExpressionsVector =
699 SmallVector<LinkedLocationExpressionsWithOffsetPatches>;
700
701 /// Emit debug locations.
702 void emitLocations(DebugSectionKind LocationSectionKind);
703
704 /// Emit location list header.
705 uint64_t emitLocListHeader(SectionDescriptor &OutLocationSection);
706
707 /// Emit location list fragment.
708 uint64_t emitLocListFragment(
709 const LinkedLocationExpressionsVector &LinkedLocationExpression,
710 SectionDescriptor &OutLocationSection);
711
712 /// Emit the .debug_addr section fragment for current unit.
713 Error emitDebugAddrSection();
714
715 /// Emit .debug_aranges.
716 void emitAranges(AddressRanges &LinkedFunctionRanges);
717
718 /// Clone and emit .debug_ranges/.debug_rnglists.
719 void cloneAndEmitRangeList(DebugSectionKind RngSectionKind,
720 AddressRanges &LinkedFunctionRanges);
721
722 /// Emit range list header.
723 uint64_t emitRangeListHeader(SectionDescriptor &OutRangeSection);
724
725 /// Emit range list fragment.
726 void emitRangeListFragment(const AddressRanges &LinkedRanges,
727 SectionDescriptor &OutRangeSection);
728
729 /// Insert the new line info sequence \p Seq into the current
730 /// set of already linked line info \p Rows. \p SeqIndices carries the
731 /// input Row index that each entry in \p Seq originated from (or the
732 /// invalid-row-index sentinel for manufactured end-of-range rows), and
733 /// is kept in lockstep with \p RowIndices.
734 void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
735 SmallVectorImpl<uint64_t> &SeqIndices,
736 std::vector<DWARFDebugLine::Row> &Rows,
737 SmallVectorImpl<uint64_t> &RowIndices);
738
739 /// Filter \p InputLineTable's rows to those covered by this unit's
740 /// function ranges, relocating addresses in the process, and store the
741 /// result in \p NewRows. \p NewRowIndices is populated in lockstep with
742 /// \p NewRows and carries, for each output row, the index of the input
743 /// row it originated from — or InvalidRowIndex for manufactured
744 /// end-of-range rows.
745 void filterLineTableRows(const DWARFDebugLine::LineTable &InputLineTable,
746 std::vector<DWARFDebugLine::Row> &NewRows,
747 SmallVectorImpl<uint64_t> &NewRowIndices);
748
749 /// Rewrite every DW_AT_LLVM_stmt_sequence DIEValue recorded on this
750 /// unit with the local .debug_line offset of the output sequence
751 /// containing the corresponding input first row.
752 /// \p SeqOffsetToFirstRowIndex maps an input stmt-sequence offset to
753 /// its first-row index (built by buildStmtSeqOffsetToFirstRowIndex so
754 /// that sequences missed by the DWARF parser are recovered from row
755 /// boundaries). \p RowIndexToSeqStartOffset maps an input first-row
756 /// index to the byte offset of the output DW_LNE_set_address that
757 /// opens the matching output sequence.
758 void patchStmtSeqAttributes(
759 const DenseMap<uint64_t, uint64_t> &SeqOffsetToFirstRowIndex,
760 const DenseMap<uint64_t, uint64_t> &RowIndexToSeqStartOffset);
761
762 /// Build a map from input stmt-sequence offset to the first-row index
763 /// of the corresponding sequence in \p InputLineTable. Seeds the map
764 /// from \p InputLineTable.Sequences (the DWARF parser's results), then
765 /// augments it by manually walking row boundaries and realigning them
766 /// against the recorded DW_AT_LLVM_stmt_sequence values so that
767 /// sequences missed by the parser still resolve. Mirrors the
768 /// classic DWARFLinker's constructSeqOffsettoOrigRowMapping.
769 DenseMap<uint64_t, uint64_t> buildStmtSeqOffsetToFirstRowIndex(
770 const DWARFDebugLine::LineTable &InputLineTable) const;
771
772 /// Emits body for both macro sections.
773 void emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
774 uint64_t OffsetToMacroTable, bool hasDWARFv5Header);
775
776 /// Creates DIE which would be placed into the "Plain" compile unit.
777 DIE *createPlainDIEandCloneAttributes(
778 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &PlainDIEGenerator,
779 uint64_t &OutOffset, std::optional<int64_t> &FuncAddressAdjustment,
780 std::optional<int64_t> &VarAddressAdjustment);
781
782 /// Creates DIE which would be placed into the "Type" compile unit.
783 /// \p SiblingOrdinal is the input DIE's position in its parent's child list.
784 TypeEntry *createTypeDIEandCloneAttributes(
785 const DWARFDebugInfoEntry *InputDieEntry, DIEGenerator &TypeDIEGenerator,
786 TypeEntry *ClonedParentTypeDIE, TypeUnit *ArtificialTypeUnit,
787 uint32_t SiblingOrdinal);
788
789 /// Create output DIE inside specified \p TypeDescriptor.
790 DIE *allocateTypeDie(TypeEntryBody *TypeDescriptor,
791 DIEGenerator &TypeDIEGenerator, dwarf::Tag DieTag,
792 bool IsDeclaration, bool IsParentDeclaration);
793
794 /// Enumerate \p DieEntry children and assign names for them.
795 Error assignTypeNamesRec(const DWARFDebugInfoEntry *DieEntry,
796 SyntheticTypeNameBuilder &NameBuilder);
797
798 /// DWARFFile containing this compile unit.
799 DWARFFile &File;
800
801 /// Pointer to the paired compile unit from the input DWARF.
802 DWARFUnit *OrigUnit = nullptr;
803
804 /// Raw DW_AT_language from the input (not ODR-filtered).
805 std::optional<uint16_t> Language;
806
807 /// Parseable Swift interface entries staged during the parallel analysis
808 /// phase. Merged serially afterwards.
809 struct PendingSwiftInterface {
810 PendingSwiftInterface(StringRef ModuleName, StringRef ResolvedPath)
811 : ModuleName(ModuleName), ResolvedPath(ResolvedPath) {}
812 std::string ModuleName;
813 std::string ResolvedPath;
814 };
815 SmallVector<PendingSwiftInterface> PendingSwiftInterfaces;
816
817 /// Line table for this unit.
818 const DWARFDebugLine::LineTable *LineTablePtr = nullptr;
819
820 /// Cached resolved paths from the line table.
821 /// The key is <UniqueUnitID, FileIdx>.
822 using ResolvedPathsMap = DenseMap<unsigned, StringEntry *>;
823 ResolvedPathsMap ResolvedFullPaths;
824 StringMap<StringEntry *> ResolvedParentPaths;
825
826 /// Maps an address into the index inside .debug_addr section.
827 IndexedValuesMap<uint64_t> DebugAddrIndexMap;
828
829 std::unique_ptr<DependencyTracker> Dependencies;
830
831 /// \defgroup Data Members accessed asynchronously.
832 ///
833 /// @{
834 OffsetToUnitTy getUnitFromOffset;
835
836 std::optional<uint64_t> LowPc;
837 uint64_t HighPc = 0;
838
839 /// Flag indicating whether type de-duplication is forbidden.
840 bool NoODR = true;
841
842 /// Deterministic priority for type DIE allocation (lower wins).
843 uint64_t Priority = std::numeric_limits<uint64_t>::max();
844
845 /// The ranges in that map are the PC ranges for functions in this unit,
846 /// associated with the PC offset to apply to the addresses to get
847 /// the linked address.
848 RangesTy Ranges;
849 std::mutex RangesMutex;
850
851 /// The DW_AT_low_pc of each DW_TAG_label.
852 using LabelMapTy = SmallDenseMap<uint64_t, uint64_t, 1>;
853 LabelMapTy Labels;
854
855 /// Recorded DW_AT_LLVM_stmt_sequence attributes for this unit. Each
856 /// entry pairs the DIEValue holding the attribute with the input-side
857 /// byte offset of the referenced line-table sequence. The value is
858 /// rewritten with the matching output offset after the line table has
859 /// been emitted; resolution from input offset to input first-row
860 /// index (including the parser-miss fallback) happens at patch time.
861 struct StmtSeqPatch {
862 DIEValue *Value = nullptr;
863 uint64_t InputStmtSeqOffset = 0;
864 };
865 SmallVector<StmtSeqPatch, 4> StmtSeqListAttributes;
866 std::mutex LabelsMutex;
867
868 /// This field keeps current stage of overall compile unit processing.
869 std::atomic<Stage> Stage;
870
871 /// DIE info indexed by DIE index.
872 SmallVector<DIEInfo> DieInfoArray;
873 SmallVector<uint64_t> OutDieOffsetArray;
874 SmallVector<TypeEntry *> TypeEntries;
875
876 /// The list of accelerator records for this unit.
877 ArrayList<AccelInfo> AcceleratorRecords;
878 /// @}
879};
880
881/// \returns list of attributes referencing type DIEs which might be
882/// deduplicated.
883/// Note: it does not include DW_AT_containing_type attribute to avoid
884/// infinite recursion.
885ArrayRef<dwarf::Attribute> getODRAttributes();
886
887} // end of namespace parallel
888} // end of namespace dwarf_linker
889} // end of namespace llvm
890
891#endif // LLVM_LIB_DWARFLINKER_PARALLEL_DWARFLINKERCOMPILEUNIT_H
892