1 //===- DWARFUnit.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_DEBUGINFO_DWARF_DWARFUNIT_H
10 #define LLVM_DEBUGINFO_DWARF_DWARFUNIT_H
11 
12 #include "llvm/ADT/DenseSet.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/iterator_range.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/DebugInfo/DWARF/DWARFAddressRange.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
21 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
22 #include "llvm/DebugInfo/DWARF/DWARFLocationExpression.h"
23 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
24 #include "llvm/Support/DataExtractor.h"
25 #include <cassert>
26 #include <cstddef>
27 #include <cstdint>
28 #include <map>
29 #include <memory>
30 #include <set>
31 #include <utility>
32 #include <vector>
33 
34 namespace llvm {
35 
36 class DWARFAbbreviationDeclarationSet;
37 class DWARFContext;
38 class DWARFDebugAbbrev;
39 class DWARFUnit;
40 class DWARFDebugRangeList;
41 class DWARFLocationTable;
42 class DWARFObject;
43 class raw_ostream;
44 struct DIDumpOptions;
45 struct DWARFSection;
46 namespace dwarflinker_parallel {
47 class CompileUnit;
48 }
49 
50 /// Base class describing the header of any kind of "unit."  Some information
51 /// is specific to certain unit types.  We separate this class out so we can
52 /// parse the header before deciding what specific kind of unit to construct.
53 class DWARFUnitHeader {
54   // Offset within section.
55   uint64_t Offset = 0;
56   // Version, address size, and DWARF format.
57   dwarf::FormParams FormParams;
58   uint64_t Length = 0;
59   uint64_t AbbrOffset = 0;
60 
61   // For DWO units only.
62   const DWARFUnitIndex::Entry *IndexEntry = nullptr;
63 
64   // For type units only.
65   uint64_t TypeHash = 0;
66   uint64_t TypeOffset = 0;
67 
68   // For v5 split or skeleton compile units only.
69   std::optional<uint64_t> DWOId;
70 
71   // Unit type as parsed, or derived from the section kind.
72   uint8_t UnitType = 0;
73 
74   // Size as parsed. uint8_t for compactness.
75   uint8_t Size = 0;
76 
77 public:
78   /// Parse a unit header from \p debug_info starting at \p offset_ptr.
79   /// Note that \p SectionKind is used as a hint to guess the unit type
80   /// for DWARF formats prior to DWARFv5. In DWARFv5 the unit type is
81   /// explicitly defined in the header and the hint is ignored.
82   bool extract(DWARFContext &Context, const DWARFDataExtractor &debug_info,
83                uint64_t *offset_ptr, DWARFSectionKind SectionKind);
84   // For units in DWARF Package File, remember the index entry and update
85   // the abbreviation offset read by extract().
86   bool applyIndexEntry(const DWARFUnitIndex::Entry *Entry);
87   uint64_t getOffset() const { return Offset; }
88   const dwarf::FormParams &getFormParams() const { return FormParams; }
89   uint16_t getVersion() const { return FormParams.Version; }
90   dwarf::DwarfFormat getFormat() const { return FormParams.Format; }
91   uint8_t getAddressByteSize() const { return FormParams.AddrSize; }
92   uint8_t getRefAddrByteSize() const { return FormParams.getRefAddrByteSize(); }
93   uint8_t getDwarfOffsetByteSize() const {
94     return FormParams.getDwarfOffsetByteSize();
95   }
96   uint64_t getLength() const { return Length; }
97   uint64_t getAbbrOffset() const { return AbbrOffset; }
98   std::optional<uint64_t> getDWOId() const { return DWOId; }
99   void setDWOId(uint64_t Id) {
100     assert((!DWOId || *DWOId == Id) && "setting DWOId to a different value");
101     DWOId = Id;
102   }
103   const DWARFUnitIndex::Entry *getIndexEntry() const { return IndexEntry; }
104   uint64_t getTypeHash() const { return TypeHash; }
105   uint64_t getTypeOffset() const { return TypeOffset; }
106   uint8_t getUnitType() const { return UnitType; }
107   bool isTypeUnit() const {
108     return UnitType == dwarf::DW_UT_type || UnitType == dwarf::DW_UT_split_type;
109   }
110   uint8_t getSize() const { return Size; }
111   uint8_t getUnitLengthFieldByteSize() const {
112     return dwarf::getUnitLengthFieldByteSize(FormParams.Format);
113   }
114   uint64_t getNextUnitOffset() const {
115     return Offset + Length + getUnitLengthFieldByteSize();
116   }
117 };
118 
119 const DWARFUnitIndex &getDWARFUnitIndex(DWARFContext &Context,
120                                         DWARFSectionKind Kind);
121 
122 bool isCompileUnit(const std::unique_ptr<DWARFUnit> &U);
123 
124 /// Describe a collection of units. Intended to hold all units either from
125 /// .debug_info and .debug_types, or from .debug_info.dwo and .debug_types.dwo.
126 class DWARFUnitVector final : public SmallVector<std::unique_ptr<DWARFUnit>, 1> {
127   std::function<std::unique_ptr<DWARFUnit>(uint64_t, DWARFSectionKind,
128                                            const DWARFSection *,
129                                            const DWARFUnitIndex::Entry *)>
130       Parser;
131   int NumInfoUnits = -1;
132 
133 public:
134   using UnitVector = SmallVectorImpl<std::unique_ptr<DWARFUnit>>;
135   using iterator = typename UnitVector::iterator;
136   using iterator_range = llvm::iterator_range<typename UnitVector::iterator>;
137 
138   using compile_unit_range =
139       decltype(make_filter_range(std::declval<iterator_range>(), isCompileUnit));
140 
141   DWARFUnit *getUnitForOffset(uint64_t Offset) const;
142   DWARFUnit *getUnitForIndexEntry(const DWARFUnitIndex::Entry &E);
143 
144   /// Read units from a .debug_info or .debug_types section.  Calls made
145   /// before finishedInfoUnits() are assumed to be for .debug_info sections,
146   /// calls after finishedInfoUnits() are for .debug_types sections.  Caller
147   /// must not mix calls to addUnitsForSection and addUnitsForDWOSection.
148   void addUnitsForSection(DWARFContext &C, const DWARFSection &Section,
149                           DWARFSectionKind SectionKind);
150   /// Read units from a .debug_info.dwo or .debug_types.dwo section.  Calls
151   /// made before finishedInfoUnits() are assumed to be for .debug_info.dwo
152   /// sections, calls after finishedInfoUnits() are for .debug_types.dwo
153   /// sections.  Caller must not mix calls to addUnitsForSection and
154   /// addUnitsForDWOSection.
155   void addUnitsForDWOSection(DWARFContext &C, const DWARFSection &DWOSection,
156                              DWARFSectionKind SectionKind, bool Lazy = false);
157 
158   /// Add an existing DWARFUnit to this UnitVector. This is used by the DWARF
159   /// verifier to process unit separately.
160   DWARFUnit *addUnit(std::unique_ptr<DWARFUnit> Unit);
161 
162   /// Returns number of all units held by this instance.
163   unsigned getNumUnits() const { return size(); }
164   /// Returns number of units from all .debug_info[.dwo] sections.
165   unsigned getNumInfoUnits() const {
166     return NumInfoUnits == -1 ? size() : NumInfoUnits;
167   }
168   /// Returns number of units from all .debug_types[.dwo] sections.
169   unsigned getNumTypesUnits() const { return size() - NumInfoUnits; }
170   /// Indicate that parsing .debug_info[.dwo] is done, and remaining units
171   /// will be from .debug_types[.dwo].
172   void finishedInfoUnits() { NumInfoUnits = size(); }
173 
174 private:
175   void addUnitsImpl(DWARFContext &Context, const DWARFObject &Obj,
176                     const DWARFSection &Section, const DWARFDebugAbbrev *DA,
177                     const DWARFSection *RS, const DWARFSection *LocSection,
178                     StringRef SS, const DWARFSection &SOS,
179                     const DWARFSection *AOS, const DWARFSection &LS, bool LE,
180                     bool IsDWO, bool Lazy, DWARFSectionKind SectionKind);
181 };
182 
183 /// Represents base address of the CU.
184 /// Represents a unit's contribution to the string offsets table.
185 struct StrOffsetsContributionDescriptor {
186   uint64_t Base = 0;
187   /// The contribution size not including the header.
188   uint64_t Size = 0;
189   /// Format and version.
190   dwarf::FormParams FormParams = {0, 0, dwarf::DwarfFormat::DWARF32};
191 
192   StrOffsetsContributionDescriptor(uint64_t Base, uint64_t Size,
193                                    uint8_t Version, dwarf::DwarfFormat Format)
194       : Base(Base), Size(Size), FormParams({Version, 0, Format}) {}
195   StrOffsetsContributionDescriptor() = default;
196 
197   uint8_t getVersion() const { return FormParams.Version; }
198   dwarf::DwarfFormat getFormat() const { return FormParams.Format; }
199   uint8_t getDwarfOffsetByteSize() const {
200     return FormParams.getDwarfOffsetByteSize();
201   }
202   /// Determine whether a contribution to the string offsets table is
203   /// consistent with the relevant section size and that its length is
204   /// a multiple of the size of one of its entries.
205   Expected<StrOffsetsContributionDescriptor>
206   validateContributionSize(DWARFDataExtractor &DA);
207 };
208 
209 class DWARFUnit {
210   DWARFContext &Context;
211   /// Section containing this DWARFUnit.
212   const DWARFSection &InfoSection;
213 
214   DWARFUnitHeader Header;
215   const DWARFDebugAbbrev *Abbrev;
216   const DWARFSection *RangeSection;
217   uint64_t RangeSectionBase;
218   uint64_t LocSectionBase;
219 
220   /// Location table of this unit.
221   std::unique_ptr<DWARFLocationTable> LocTable;
222 
223   const DWARFSection &LineSection;
224   StringRef StringSection;
225   const DWARFSection &StringOffsetSection;
226   const DWARFSection *AddrOffsetSection;
227   DWARFUnit *SU;
228   std::optional<uint64_t> AddrOffsetSectionBase;
229   bool IsLittleEndian;
230   bool IsDWO;
231   const DWARFUnitVector &UnitVector;
232 
233   /// Start, length, and DWARF format of the unit's contribution to the string
234   /// offsets table (DWARF v5).
235   std::optional<StrOffsetsContributionDescriptor>
236       StringOffsetsTableContribution;
237 
238   mutable const DWARFAbbreviationDeclarationSet *Abbrevs;
239   std::optional<object::SectionedAddress> BaseAddr;
240   /// The compile unit debug information entry items.
241   std::vector<DWARFDebugInfoEntry> DieArray;
242 
243   /// Map from range's start address to end address and corresponding DIE.
244   /// IntervalMap does not support range removal, as a result, we use the
245   /// std::map::upper_bound for address range lookup.
246   std::map<uint64_t, std::pair<uint64_t, DWARFDie>> AddrDieMap;
247 
248   /// Map from the location (interpreted DW_AT_location) of a DW_TAG_variable,
249   /// to the end address and the corresponding DIE.
250   std::map<uint64_t, std::pair<uint64_t, DWARFDie>> VariableDieMap;
251   DenseSet<uint64_t> RootsParsedForVariables;
252 
253   using die_iterator_range =
254       iterator_range<std::vector<DWARFDebugInfoEntry>::iterator>;
255 
256   std::shared_ptr<DWARFUnit> DWO;
257 
258 protected:
259   friend dwarflinker_parallel::CompileUnit;
260 
261   /// Return the index of a \p Die entry inside the unit's DIE vector.
262   ///
263   /// It is illegal to call this method with a DIE that hasn't be
264   /// created by this unit. In other word, it's illegal to call this
265   /// method on a DIE that isn't accessible by following
266   /// children/sibling links starting from this unit's getUnitDIE().
267   uint32_t getDIEIndex(const DWARFDebugInfoEntry *Die) const {
268     auto First = DieArray.data();
269     assert(Die >= First && Die < First + DieArray.size());
270     return Die - First;
271   }
272 
273   /// Return DWARFDebugInfoEntry for the specified index \p Index.
274   const DWARFDebugInfoEntry *getDebugInfoEntry(unsigned Index) const {
275     assert(Index < DieArray.size());
276     return &DieArray[Index];
277   }
278 
279   const DWARFDebugInfoEntry *
280   getParentEntry(const DWARFDebugInfoEntry *Die) const;
281   const DWARFDebugInfoEntry *
282   getSiblingEntry(const DWARFDebugInfoEntry *Die) const;
283   const DWARFDebugInfoEntry *
284   getPreviousSiblingEntry(const DWARFDebugInfoEntry *Die) const;
285   const DWARFDebugInfoEntry *
286   getFirstChildEntry(const DWARFDebugInfoEntry *Die) const;
287   const DWARFDebugInfoEntry *
288   getLastChildEntry(const DWARFDebugInfoEntry *Die) const;
289 
290   const DWARFUnitHeader &getHeader() const { return Header; }
291 
292   /// Find the unit's contribution to the string offsets table and determine its
293   /// length and form. The given offset is expected to be derived from the unit
294   /// DIE's DW_AT_str_offsets_base attribute.
295   Expected<std::optional<StrOffsetsContributionDescriptor>>
296   determineStringOffsetsTableContribution(DWARFDataExtractor &DA);
297 
298   /// Find the unit's contribution to the string offsets table and determine its
299   /// length and form. The given offset is expected to be 0 in a dwo file or,
300   /// in a dwp file, the start of the unit's contribution to the string offsets
301   /// table section (as determined by the index table).
302   Expected<std::optional<StrOffsetsContributionDescriptor>>
303   determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA);
304 
305 public:
306   DWARFUnit(DWARFContext &Context, const DWARFSection &Section,
307             const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,
308             const DWARFSection *RS, const DWARFSection *LocSection,
309             StringRef SS, const DWARFSection &SOS, const DWARFSection *AOS,
310             const DWARFSection &LS, bool LE, bool IsDWO,
311             const DWARFUnitVector &UnitVector);
312 
313   virtual ~DWARFUnit();
314 
315   bool isLittleEndian() const { return IsLittleEndian; }
316   bool isDWOUnit() const { return IsDWO; }
317   DWARFContext& getContext() const { return Context; }
318   const DWARFSection &getInfoSection() const { return InfoSection; }
319   uint64_t getOffset() const { return Header.getOffset(); }
320   const dwarf::FormParams &getFormParams() const {
321     return Header.getFormParams();
322   }
323   uint16_t getVersion() const { return Header.getVersion(); }
324   uint8_t getAddressByteSize() const { return Header.getAddressByteSize(); }
325   uint8_t getRefAddrByteSize() const { return Header.getRefAddrByteSize(); }
326   uint8_t getDwarfOffsetByteSize() const {
327     return Header.getDwarfOffsetByteSize();
328   }
329   /// Size in bytes of the parsed unit header.
330   uint32_t getHeaderSize() const { return Header.getSize(); }
331   uint64_t getLength() const { return Header.getLength(); }
332   dwarf::DwarfFormat getFormat() const { return Header.getFormat(); }
333   uint8_t getUnitType() const { return Header.getUnitType(); }
334   bool isTypeUnit() const { return Header.isTypeUnit(); }
335   uint64_t getAbbrOffset() const { return Header.getAbbrOffset(); }
336   uint64_t getNextUnitOffset() const { return Header.getNextUnitOffset(); }
337   const DWARFSection &getLineSection() const { return LineSection; }
338   StringRef getStringSection() const { return StringSection; }
339   const DWARFSection &getStringOffsetSection() const {
340     return StringOffsetSection;
341   }
342 
343   void setSkeletonUnit(DWARFUnit *SU) { this->SU = SU; }
344   // Returns itself if not using Split DWARF, or if the unit is a skeleton unit
345   // - otherwise returns the split full unit's corresponding skeleton, if
346   // available.
347   DWARFUnit *getLinkedUnit() { return IsDWO ? SU : this; }
348 
349   void setAddrOffsetSection(const DWARFSection *AOS, uint64_t Base) {
350     AddrOffsetSection = AOS;
351     AddrOffsetSectionBase = Base;
352   }
353 
354   std::optional<uint64_t> getAddrOffsetSectionBase() const {
355     return AddrOffsetSectionBase;
356   }
357 
358   /// Returns offset to the indexed address value inside .debug_addr section.
359   std::optional<uint64_t> getIndexedAddressOffset(uint64_t Index) {
360     if (std::optional<uint64_t> AddrOffsetSectionBase =
361             getAddrOffsetSectionBase())
362       return *AddrOffsetSectionBase + Index * getAddressByteSize();
363 
364     return std::nullopt;
365   }
366 
367   /// Recursively update address to Die map.
368   void updateAddressDieMap(DWARFDie Die);
369 
370   /// Recursively update address to variable Die map.
371   void updateVariableDieMap(DWARFDie Die);
372 
373   void setRangesSection(const DWARFSection *RS, uint64_t Base) {
374     RangeSection = RS;
375     RangeSectionBase = Base;
376   }
377 
378   uint64_t getLocSectionBase() const {
379     return LocSectionBase;
380   }
381 
382   std::optional<object::SectionedAddress>
383   getAddrOffsetSectionItem(uint32_t Index) const;
384   Expected<uint64_t> getStringOffsetSectionItem(uint32_t Index) const;
385 
386   DWARFDataExtractor getDebugInfoExtractor() const;
387 
388   DataExtractor getStringExtractor() const {
389     return DataExtractor(StringSection, false, 0);
390   }
391 
392   const DWARFLocationTable &getLocationTable() { return *LocTable; }
393 
394   /// Extract the range list referenced by this compile unit from the
395   /// .debug_ranges section. If the extraction is unsuccessful, an error
396   /// is returned. Successful extraction requires that the compile unit
397   /// has already been extracted.
398   Error extractRangeList(uint64_t RangeListOffset,
399                          DWARFDebugRangeList &RangeList) const;
400   void clear();
401 
402   const std::optional<StrOffsetsContributionDescriptor> &
403   getStringOffsetsTableContribution() const {
404     return StringOffsetsTableContribution;
405   }
406 
407   uint8_t getDwarfStringOffsetsByteSize() const {
408     assert(StringOffsetsTableContribution);
409     return StringOffsetsTableContribution->getDwarfOffsetByteSize();
410   }
411 
412   uint64_t getStringOffsetsBase() const {
413     assert(StringOffsetsTableContribution);
414     return StringOffsetsTableContribution->Base;
415   }
416 
417   uint64_t getAbbreviationsOffset() const { return Header.getAbbrOffset(); }
418 
419   const DWARFAbbreviationDeclarationSet *getAbbreviations() const;
420 
421   static bool isMatchingUnitTypeAndTag(uint8_t UnitType, dwarf::Tag Tag) {
422     switch (UnitType) {
423     case dwarf::DW_UT_compile:
424       return Tag == dwarf::DW_TAG_compile_unit;
425     case dwarf::DW_UT_type:
426       return Tag == dwarf::DW_TAG_type_unit;
427     case dwarf::DW_UT_partial:
428       return Tag == dwarf::DW_TAG_partial_unit;
429     case dwarf::DW_UT_skeleton:
430       return Tag == dwarf::DW_TAG_skeleton_unit;
431     case dwarf::DW_UT_split_compile:
432     case dwarf::DW_UT_split_type:
433       return dwarf::isUnitType(Tag);
434     }
435     return false;
436   }
437 
438   std::optional<object::SectionedAddress> getBaseAddress();
439 
440   DWARFDie getUnitDIE(bool ExtractUnitDIEOnly = true) {
441     extractDIEsIfNeeded(ExtractUnitDIEOnly);
442     if (DieArray.empty())
443       return DWARFDie();
444     return DWARFDie(this, &DieArray[0]);
445   }
446 
447   DWARFDie getNonSkeletonUnitDIE(bool ExtractUnitDIEOnly = true,
448                                  StringRef DWOAlternativeLocation = {}) {
449     parseDWO(DWOAlternativeLocation);
450     return DWO ? DWO->getUnitDIE(ExtractUnitDIEOnly)
451                : getUnitDIE(ExtractUnitDIEOnly);
452   }
453 
454   const char *getCompilationDir();
455   std::optional<uint64_t> getDWOId() {
456     extractDIEsIfNeeded(/*CUDieOnly*/ true);
457     return getHeader().getDWOId();
458   }
459   void setDWOId(uint64_t NewID) { Header.setDWOId(NewID); }
460 
461   /// Return a vector of address ranges resulting from a (possibly encoded)
462   /// range list starting at a given offset in the appropriate ranges section.
463   Expected<DWARFAddressRangesVector> findRnglistFromOffset(uint64_t Offset);
464 
465   /// Return a vector of address ranges retrieved from an encoded range
466   /// list whose offset is found via a table lookup given an index (DWARF v5
467   /// and later).
468   Expected<DWARFAddressRangesVector> findRnglistFromIndex(uint32_t Index);
469 
470   /// Return a rangelist's offset based on an index. The index designates
471   /// an entry in the rangelist table's offset array and is supplied by
472   /// DW_FORM_rnglistx.
473   std::optional<uint64_t> getRnglistOffset(uint32_t Index);
474 
475   std::optional<uint64_t> getLoclistOffset(uint32_t Index);
476 
477   Expected<DWARFAddressRangesVector> collectAddressRanges();
478 
479   Expected<DWARFLocationExpressionsVector>
480   findLoclistFromOffset(uint64_t Offset);
481 
482   /// Returns subprogram DIE with address range encompassing the provided
483   /// address. The pointer is alive as long as parsed compile unit DIEs are not
484   /// cleared.
485   DWARFDie getSubroutineForAddress(uint64_t Address);
486 
487   /// Returns variable DIE for the address provided. The pointer is alive as
488   /// long as parsed compile unit DIEs are not cleared.
489   DWARFDie getVariableForAddress(uint64_t Address);
490 
491   /// getInlinedChainForAddress - fetches inlined chain for a given address.
492   /// Returns empty chain if there is no subprogram containing address. The
493   /// chain is valid as long as parsed compile unit DIEs are not cleared.
494   void getInlinedChainForAddress(uint64_t Address,
495                                  SmallVectorImpl<DWARFDie> &InlinedChain);
496 
497   /// Return the DWARFUnitVector containing this unit.
498   const DWARFUnitVector &getUnitVector() const { return UnitVector; }
499 
500   /// Returns the number of DIEs in the unit. Parses the unit
501   /// if necessary.
502   unsigned getNumDIEs() {
503     extractDIEsIfNeeded(false);
504     return DieArray.size();
505   }
506 
507   /// Return the index of a DIE inside the unit's DIE vector.
508   ///
509   /// It is illegal to call this method with a DIE that hasn't be
510   /// created by this unit. In other word, it's illegal to call this
511   /// method on a DIE that isn't accessible by following
512   /// children/sibling links starting from this unit's getUnitDIE().
513   uint32_t getDIEIndex(const DWARFDie &D) const {
514     return getDIEIndex(D.getDebugInfoEntry());
515   }
516 
517   /// Return the DIE object at the given index \p Index.
518   DWARFDie getDIEAtIndex(unsigned Index) {
519     return DWARFDie(this, getDebugInfoEntry(Index));
520   }
521 
522   DWARFDie getParent(const DWARFDebugInfoEntry *Die);
523   DWARFDie getSibling(const DWARFDebugInfoEntry *Die);
524   DWARFDie getPreviousSibling(const DWARFDebugInfoEntry *Die);
525   DWARFDie getFirstChild(const DWARFDebugInfoEntry *Die);
526   DWARFDie getLastChild(const DWARFDebugInfoEntry *Die);
527 
528   /// Return the DIE object for a given offset \p Offset inside the
529   /// unit's DIE vector.
530   DWARFDie getDIEForOffset(uint64_t Offset) {
531     if (std::optional<uint32_t> DieIdx = getDIEIndexForOffset(Offset))
532       return DWARFDie(this, &DieArray[*DieIdx]);
533 
534     return DWARFDie();
535   }
536 
537   /// Return the DIE index for a given offset \p Offset inside the
538   /// unit's DIE vector.
539   std::optional<uint32_t> getDIEIndexForOffset(uint64_t Offset) {
540     extractDIEsIfNeeded(false);
541     auto It =
542         llvm::partition_point(DieArray, [=](const DWARFDebugInfoEntry &DIE) {
543           return DIE.getOffset() < Offset;
544         });
545     if (It != DieArray.end() && It->getOffset() == Offset)
546       return It - DieArray.begin();
547     return std::nullopt;
548   }
549 
550   uint32_t getLineTableOffset() const {
551     if (auto IndexEntry = Header.getIndexEntry())
552       if (const auto *Contrib = IndexEntry->getContribution(DW_SECT_LINE))
553         return Contrib->getOffset32();
554     return 0;
555   }
556 
557   die_iterator_range dies() {
558     extractDIEsIfNeeded(false);
559     return die_iterator_range(DieArray.begin(), DieArray.end());
560   }
561 
562   virtual void dump(raw_ostream &OS, DIDumpOptions DumpOpts) = 0;
563 
564   Error tryExtractDIEsIfNeeded(bool CUDieOnly);
565 
566 private:
567   /// Size in bytes of the .debug_info data associated with this compile unit.
568   size_t getDebugInfoSize() const {
569     return Header.getLength() + Header.getUnitLengthFieldByteSize() -
570            getHeaderSize();
571   }
572 
573   /// extractDIEsIfNeeded - Parses a compile unit and indexes its DIEs if it
574   /// hasn't already been done
575   void extractDIEsIfNeeded(bool CUDieOnly);
576 
577   /// extractDIEsToVector - Appends all parsed DIEs to a vector.
578   void extractDIEsToVector(bool AppendCUDie, bool AppendNonCUDIEs,
579                            std::vector<DWARFDebugInfoEntry> &DIEs) const;
580 
581   /// clearDIEs - Clear parsed DIEs to keep memory usage low.
582   void clearDIEs(bool KeepCUDie);
583 
584   /// parseDWO - Parses .dwo file for current compile unit. Returns true if
585   /// it was actually constructed.
586   /// The \p AlternativeLocation specifies an alternative location to get
587   /// the DWARF context for the DWO object; this is the case when it has
588   /// been moved from its original location.
589   bool parseDWO(StringRef AlternativeLocation = {});
590 };
591 
592 inline bool isCompileUnit(const std::unique_ptr<DWARFUnit> &U) {
593   return !U->isTypeUnit();
594 }
595 
596 } // end namespace llvm
597 
598 #endif // LLVM_DEBUGINFO_DWARF_DWARFUNIT_H
599