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