1 //===- DWARFDie.cpp -------------------------------------------------------===//
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 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
10 #include "llvm/ADT/None.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/SmallSet.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/BinaryFormat/Dwarf.h"
15 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
16 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
18 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/DataExtractor.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/FormatAdapters.h"
25 #include "llvm/Support/FormatVariadic.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/WithColor.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cinttypes>
32 #include <cstdint>
33 #include <string>
34 #include <utility>
35 
36 using namespace llvm;
37 using namespace dwarf;
38 using namespace object;
39 
40 static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
41   OS << " (";
42   do {
43     uint64_t Shift = countTrailingZeros(Val);
44     assert(Shift < 64 && "undefined behavior");
45     uint64_t Bit = 1ULL << Shift;
46     auto PropName = ApplePropertyString(Bit);
47     if (!PropName.empty())
48       OS << PropName;
49     else
50       OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
51     if (!(Val ^= Bit))
52       break;
53     OS << ", ";
54   } while (true);
55   OS << ")";
56 }
57 
58 static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
59                        const DWARFAddressRangesVector &Ranges,
60                        unsigned AddressSize, unsigned Indent,
61                        const DIDumpOptions &DumpOpts) {
62   if (!DumpOpts.ShowAddresses)
63     return;
64 
65   ArrayRef<SectionName> SectionNames;
66   if (DumpOpts.Verbose)
67     SectionNames = Obj.getSectionNames();
68 
69   for (const DWARFAddressRange &R : Ranges) {
70     OS << '\n';
71     OS.indent(Indent);
72     R.dump(OS, AddressSize);
73 
74     DWARFFormValue::dumpAddressSection(Obj, OS, DumpOpts, R.SectionIndex);
75   }
76 }
77 
78 static void dumpLocation(raw_ostream &OS, DWARFFormValue &FormValue,
79                          DWARFUnit *U, unsigned Indent,
80                          DIDumpOptions DumpOpts) {
81   DWARFContext &Ctx = U->getContext();
82   const DWARFObject &Obj = Ctx.getDWARFObj();
83   const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
84   if (FormValue.isFormClass(DWARFFormValue::FC_Block) ||
85       FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) {
86     ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
87     DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()),
88                        Ctx.isLittleEndian(), 0);
89     DWARFExpression(Data, U->getVersion(), U->getAddressByteSize())
90         .print(OS, MRI, U);
91     return;
92   }
93 
94   if (FormValue.isFormClass(DWARFFormValue::FC_SectionOffset)) {
95     uint64_t Offset = *FormValue.getAsSectionOffset();
96     uint64_t BaseAddr = 0;
97     if (Optional<object::SectionedAddress> BA = U->getBaseAddress())
98       BaseAddr = BA->Address;
99     auto LLDumpOpts = DumpOpts;
100     LLDumpOpts.Verbose = false;
101 
102     if (!U->isDWOUnit() && !U->getLocSection()->Data.empty()) {
103       DWARFDebugLoc DebugLoc;
104       DWARFDataExtractor Data(Obj, *U->getLocSection(), Ctx.isLittleEndian(),
105                               Obj.getAddressSize());
106 
107       FormValue.dump(OS, DumpOpts);
108       OS << ": ";
109 
110       if (Expected<DWARFDebugLoc::LocationList> LL =
111               DebugLoc.parseOneLocationList(Data, &Offset)) {
112         LL->dump(OS, BaseAddr, Ctx.isLittleEndian(), Obj.getAddressSize(), MRI,
113                  U, LLDumpOpts, Indent);
114       } else {
115         OS << '\n';
116         OS.indent(Indent);
117         OS << formatv("error extracting location list: {0}",
118                       fmt_consume(LL.takeError()));
119       }
120       return;
121     }
122 
123     bool UseLocLists = !U->isDWOUnit();
124     auto Data =
125         UseLocLists
126             ? DWARFDataExtractor(Obj, Obj.getLoclistsSection(),
127                                  Ctx.isLittleEndian(), Obj.getAddressSize())
128             : DWARFDataExtractor(U->getLocSectionData(), Ctx.isLittleEndian(),
129                                  Obj.getAddressSize());
130 
131     if (!Data.getData().empty()) {
132       // Old-style location list were used in DWARF v4 (.debug_loc.dwo section).
133       // Modern locations list (.debug_loclists) are used starting from v5.
134       // Ideally we should take the version from the .debug_loclists section
135       // header, but using CU's version for simplicity.
136       DWARFDebugLoclists::dumpLocationList(
137           Data, &Offset, UseLocLists ? U->getVersion() : 4, OS, BaseAddr, MRI,
138           U, LLDumpOpts, Indent);
139     }
140     return;
141   }
142 
143   FormValue.dump(OS, DumpOpts);
144 }
145 
146 /// Dump the name encoded in the type tag.
147 static void dumpTypeTagName(raw_ostream &OS, dwarf::Tag T) {
148   StringRef TagStr = TagString(T);
149   if (!TagStr.startswith("DW_TAG_") || !TagStr.endswith("_type"))
150     return;
151   OS << TagStr.substr(7, TagStr.size() - 12) << " ";
152 }
153 
154 static void dumpArrayType(raw_ostream &OS, const DWARFDie &D) {
155   Optional<uint64_t> Bound;
156   for (const DWARFDie &C : D.children())
157     if (C.getTag() == DW_TAG_subrange_type) {
158       Optional<uint64_t> LB;
159       Optional<uint64_t> Count;
160       Optional<uint64_t> UB;
161       Optional<unsigned> DefaultLB;
162       if (Optional<DWARFFormValue> L = C.find(DW_AT_lower_bound))
163         LB = L->getAsUnsignedConstant();
164       if (Optional<DWARFFormValue> CountV = C.find(DW_AT_count))
165         Count = CountV->getAsUnsignedConstant();
166       if (Optional<DWARFFormValue> UpperV = C.find(DW_AT_upper_bound))
167         UB = UpperV->getAsUnsignedConstant();
168       if (Optional<DWARFFormValue> LV =
169               D.getDwarfUnit()->getUnitDIE().find(DW_AT_language))
170         if (Optional<uint64_t> LC = LV->getAsUnsignedConstant())
171           if ((DefaultLB =
172                    LanguageLowerBound(static_cast<dwarf::SourceLanguage>(*LC))))
173             if (LB && *LB == *DefaultLB)
174               LB = None;
175       if (!LB && !Count && !UB)
176         OS << "[]";
177       else if (!LB && (Count || UB) && DefaultLB)
178         OS << '[' << (Count ? *Count : *UB - *DefaultLB + 1) << ']';
179       else {
180         OS << "[[";
181         if (LB)
182           OS << *LB;
183         else
184           OS << '?';
185         OS << ", ";
186         if (Count)
187           if (LB)
188             OS << *LB + *Count;
189           else
190             OS << "? + " << *Count;
191         else if (UB)
192           OS << *UB + 1;
193         else
194           OS << '?';
195         OS << ")]";
196       }
197     }
198 }
199 
200 /// Recursively dump the DIE type name when applicable.
201 static void dumpTypeName(raw_ostream &OS, const DWARFDie &D) {
202   if (!D.isValid())
203     return;
204 
205   if (const char *Name = D.getName(DINameKind::LinkageName)) {
206     OS << Name;
207     return;
208   }
209 
210   // FIXME: We should have pretty printers per language. Currently we print
211   // everything as if it was C++ and fall back to the TAG type name.
212   const dwarf::Tag T = D.getTag();
213   switch (T) {
214   case DW_TAG_array_type:
215   case DW_TAG_pointer_type:
216   case DW_TAG_ptr_to_member_type:
217   case DW_TAG_reference_type:
218   case DW_TAG_rvalue_reference_type:
219   case DW_TAG_subroutine_type:
220     break;
221   default:
222     dumpTypeTagName(OS, T);
223   }
224 
225   // Follow the DW_AT_type if possible.
226   DWARFDie TypeDie = D.getAttributeValueAsReferencedDie(DW_AT_type);
227   dumpTypeName(OS, TypeDie);
228 
229   switch (T) {
230   case DW_TAG_subroutine_type: {
231     if (!TypeDie)
232       OS << "void";
233     OS << '(';
234     bool First = true;
235     for (const DWARFDie &C : D.children()) {
236       if (C.getTag() == DW_TAG_formal_parameter) {
237         if (!First)
238           OS << ", ";
239         First = false;
240         dumpTypeName(OS, C.getAttributeValueAsReferencedDie(DW_AT_type));
241       }
242     }
243     OS << ')';
244     break;
245   }
246   case DW_TAG_array_type: {
247     dumpArrayType(OS, D);
248     break;
249   }
250   case DW_TAG_pointer_type:
251     OS << '*';
252     break;
253   case DW_TAG_ptr_to_member_type:
254     if (DWARFDie Cont =
255             D.getAttributeValueAsReferencedDie(DW_AT_containing_type)) {
256       dumpTypeName(OS << ' ', Cont);
257       OS << "::";
258     }
259     OS << '*';
260     break;
261   case DW_TAG_reference_type:
262     OS << '&';
263     break;
264   case DW_TAG_rvalue_reference_type:
265     OS << "&&";
266     break;
267   default:
268     break;
269   }
270 }
271 
272 static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
273                           uint64_t *OffsetPtr, dwarf::Attribute Attr,
274                           dwarf::Form Form, unsigned Indent,
275                           DIDumpOptions DumpOpts) {
276   if (!Die.isValid())
277     return;
278   const char BaseIndent[] = "            ";
279   OS << BaseIndent;
280   OS.indent(Indent + 2);
281   WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
282 
283   if (DumpOpts.Verbose || DumpOpts.ShowForm)
284     OS << formatv(" [{0}]", Form);
285 
286   DWARFUnit *U = Die.getDwarfUnit();
287   DWARFFormValue FormValue = DWARFFormValue::createFromUnit(Form, U, OffsetPtr);
288 
289   OS << "\t(";
290 
291   StringRef Name;
292   std::string File;
293   auto Color = HighlightColor::Enumerator;
294   if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
295     Color = HighlightColor::String;
296     if (const auto *LT = U->getContext().getLineTableForUnit(U))
297       if (LT->getFileNameByIndex(
298               FormValue.getAsUnsignedConstant().getValue(),
299               U->getCompilationDir(),
300               DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
301         File = '"' + File + '"';
302         Name = File;
303       }
304   } else if (Optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
305     Name = AttributeValueString(Attr, *Val);
306 
307   if (!Name.empty())
308     WithColor(OS, Color) << Name;
309   else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
310     OS << *FormValue.getAsUnsignedConstant();
311   else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
312            FormValue.getAsUnsignedConstant()) {
313     if (DumpOpts.ShowAddresses) {
314       // Print the actual address rather than the offset.
315       uint64_t LowPC, HighPC, Index;
316       if (Die.getLowAndHighPC(LowPC, HighPC, Index))
317         OS << format("0x%016" PRIx64, HighPC);
318       else
319         FormValue.dump(OS, DumpOpts);
320     }
321   } else if (DWARFAttribute::mayHaveLocationDescription(Attr))
322     dumpLocation(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4, DumpOpts);
323   else
324     FormValue.dump(OS, DumpOpts);
325 
326   std::string Space = DumpOpts.ShowAddresses ? " " : "";
327 
328   // We have dumped the attribute raw value. For some attributes
329   // having both the raw value and the pretty-printed value is
330   // interesting. These attributes are handled below.
331   if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
332     if (const char *Name =
333             Die.getAttributeValueAsReferencedDie(FormValue).getName(
334                 DINameKind::LinkageName))
335       OS << Space << "\"" << Name << '\"';
336   } else if (Attr == DW_AT_type) {
337     OS << Space << "\"";
338     dumpTypeName(OS, Die.getAttributeValueAsReferencedDie(FormValue));
339     OS << '"';
340   } else if (Attr == DW_AT_APPLE_property_attribute) {
341     if (Optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
342       dumpApplePropertyAttribute(OS, *OptVal);
343   } else if (Attr == DW_AT_ranges) {
344     const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
345     // For DW_FORM_rnglistx we need to dump the offset separately, since
346     // we have only dumped the index so far.
347     if (FormValue.getForm() == DW_FORM_rnglistx)
348       if (auto RangeListOffset =
349               U->getRnglistOffset(*FormValue.getAsSectionOffset())) {
350         DWARFFormValue FV = DWARFFormValue::createFromUValue(
351             dwarf::DW_FORM_sec_offset, *RangeListOffset);
352         FV.dump(OS, DumpOpts);
353       }
354     if (auto RangesOrError = Die.getAddressRanges())
355       dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
356                  sizeof(BaseIndent) + Indent + 4, DumpOpts);
357     else
358       WithColor::error() << "decoding address ranges: "
359                          << toString(RangesOrError.takeError()) << '\n';
360   }
361 
362   OS << ")\n";
363 }
364 
365 bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
366 
367 bool DWARFDie::isSubroutineDIE() const {
368   auto Tag = getTag();
369   return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
370 }
371 
372 Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
373   if (!isValid())
374     return None;
375   auto AbbrevDecl = getAbbreviationDeclarationPtr();
376   if (AbbrevDecl)
377     return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
378   return None;
379 }
380 
381 Optional<DWARFFormValue>
382 DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
383   if (!isValid())
384     return None;
385   auto AbbrevDecl = getAbbreviationDeclarationPtr();
386   if (AbbrevDecl) {
387     for (auto Attr : Attrs) {
388       if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
389         return Value;
390     }
391   }
392   return None;
393 }
394 
395 Optional<DWARFFormValue>
396 DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
397   std::vector<DWARFDie> Worklist;
398   Worklist.push_back(*this);
399 
400   // Keep track if DIEs already seen to prevent infinite recursion.
401   // Empirically we rarely see a depth of more than 3 when dealing with valid
402   // DWARF. This corresponds to following the DW_AT_abstract_origin and
403   // DW_AT_specification just once.
404   SmallSet<DWARFDie, 3> Seen;
405   Seen.insert(*this);
406 
407   while (!Worklist.empty()) {
408     DWARFDie Die = Worklist.back();
409     Worklist.pop_back();
410 
411     if (!Die.isValid())
412       continue;
413 
414     if (auto Value = Die.find(Attrs))
415       return Value;
416 
417     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
418       if (Seen.insert(D).second)
419         Worklist.push_back(D);
420 
421     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
422       if (Seen.insert(D).second)
423         Worklist.push_back(D);
424   }
425 
426   return None;
427 }
428 
429 DWARFDie
430 DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
431   if (Optional<DWARFFormValue> F = find(Attr))
432     return getAttributeValueAsReferencedDie(*F);
433   return DWARFDie();
434 }
435 
436 DWARFDie
437 DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
438   if (auto SpecRef = V.getAsRelativeReference()) {
439     if (SpecRef->Unit)
440       return SpecRef->Unit->getDIEForOffset(SpecRef->Unit->getOffset() + SpecRef->Offset);
441     if (auto SpecUnit = U->getUnitVector().getUnitForOffset(SpecRef->Offset))
442       return SpecUnit->getDIEForOffset(SpecRef->Offset);
443   }
444   return DWARFDie();
445 }
446 
447 Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
448   return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
449 }
450 
451 Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
452   if (auto FormValue = find(DW_AT_high_pc)) {
453     if (auto Address = FormValue->getAsAddress()) {
454       // High PC is an address.
455       return Address;
456     }
457     if (auto Offset = FormValue->getAsUnsignedConstant()) {
458       // High PC is an offset from LowPC.
459       return LowPC + *Offset;
460     }
461   }
462   return None;
463 }
464 
465 bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
466                                uint64_t &SectionIndex) const {
467   auto F = find(DW_AT_low_pc);
468   auto LowPcAddr = toSectionedAddress(F);
469   if (!LowPcAddr)
470     return false;
471   if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
472     LowPC = LowPcAddr->Address;
473     HighPC = *HighPcAddr;
474     SectionIndex = LowPcAddr->SectionIndex;
475     return true;
476   }
477   return false;
478 }
479 
480 Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
481   if (isNULL())
482     return DWARFAddressRangesVector();
483   // Single range specified by low/high PC.
484   uint64_t LowPC, HighPC, Index;
485   if (getLowAndHighPC(LowPC, HighPC, Index))
486     return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
487 
488   Optional<DWARFFormValue> Value = find(DW_AT_ranges);
489   if (Value) {
490     if (Value->getForm() == DW_FORM_rnglistx)
491       return U->findRnglistFromIndex(*Value->getAsSectionOffset());
492     return U->findRnglistFromOffset(*Value->getAsSectionOffset());
493   }
494   return DWARFAddressRangesVector();
495 }
496 
497 void DWARFDie::collectChildrenAddressRanges(
498     DWARFAddressRangesVector &Ranges) const {
499   if (isNULL())
500     return;
501   if (isSubprogramDIE()) {
502     if (auto DIERangesOrError = getAddressRanges())
503       Ranges.insert(Ranges.end(), DIERangesOrError.get().begin(),
504                     DIERangesOrError.get().end());
505     else
506       llvm::consumeError(DIERangesOrError.takeError());
507   }
508 
509   for (auto Child : children())
510     Child.collectChildrenAddressRanges(Ranges);
511 }
512 
513 bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
514   auto RangesOrError = getAddressRanges();
515   if (!RangesOrError) {
516     llvm::consumeError(RangesOrError.takeError());
517     return false;
518   }
519 
520   for (const auto &R : RangesOrError.get())
521     if (R.LowPC <= Address && Address < R.HighPC)
522       return true;
523   return false;
524 }
525 
526 const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
527   if (!isSubroutineDIE())
528     return nullptr;
529   return getName(Kind);
530 }
531 
532 const char *DWARFDie::getName(DINameKind Kind) const {
533   if (!isValid() || Kind == DINameKind::None)
534     return nullptr;
535   // Try to get mangled name only if it was asked for.
536   if (Kind == DINameKind::LinkageName) {
537     if (auto Name = dwarf::toString(
538             findRecursively({DW_AT_MIPS_linkage_name, DW_AT_linkage_name}),
539             nullptr))
540       return Name;
541   }
542   if (auto Name = dwarf::toString(findRecursively(DW_AT_name), nullptr))
543     return Name;
544   return nullptr;
545 }
546 
547 uint64_t DWARFDie::getDeclLine() const {
548   return toUnsigned(findRecursively(DW_AT_decl_line), 0);
549 }
550 
551 void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
552                               uint32_t &CallColumn,
553                               uint32_t &CallDiscriminator) const {
554   CallFile = toUnsigned(find(DW_AT_call_file), 0);
555   CallLine = toUnsigned(find(DW_AT_call_line), 0);
556   CallColumn = toUnsigned(find(DW_AT_call_column), 0);
557   CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
558 }
559 
560 /// Helper to dump a DIE with all of its parents, but no siblings.
561 static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
562                                 DIDumpOptions DumpOpts, unsigned Depth = 0) {
563   if (!Die)
564     return Indent;
565   if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
566     return Indent;
567   Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts, Depth + 1);
568   Die.dump(OS, Indent, DumpOpts);
569   return Indent + 2;
570 }
571 
572 void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
573                     DIDumpOptions DumpOpts) const {
574   if (!isValid())
575     return;
576   DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
577   const uint64_t Offset = getOffset();
578   uint64_t offset = Offset;
579   if (DumpOpts.ShowParents) {
580     DIDumpOptions ParentDumpOpts = DumpOpts;
581     ParentDumpOpts.ShowParents = false;
582     ParentDumpOpts.ShowChildren = false;
583     Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
584   }
585 
586   if (debug_info_data.isValidOffset(offset)) {
587     uint32_t abbrCode = debug_info_data.getULEB128(&offset);
588     if (DumpOpts.ShowAddresses)
589       WithColor(OS, HighlightColor::Address).get()
590           << format("\n0x%8.8" PRIx64 ": ", Offset);
591 
592     if (abbrCode) {
593       auto AbbrevDecl = getAbbreviationDeclarationPtr();
594       if (AbbrevDecl) {
595         WithColor(OS, HighlightColor::Tag).get().indent(Indent)
596             << formatv("{0}", getTag());
597         if (DumpOpts.Verbose)
598           OS << format(" [%u] %c", abbrCode,
599                        AbbrevDecl->hasChildren() ? '*' : ' ');
600         OS << '\n';
601 
602         // Dump all data in the DIE for the attributes.
603         for (const auto &AttrSpec : AbbrevDecl->attributes()) {
604           if (AttrSpec.Form == DW_FORM_implicit_const) {
605             // We are dumping .debug_info section ,
606             // implicit_const attribute values are not really stored here,
607             // but in .debug_abbrev section. So we just skip such attrs.
608             continue;
609           }
610           dumpAttribute(OS, *this, &offset, AttrSpec.Attr, AttrSpec.Form,
611                         Indent, DumpOpts);
612         }
613 
614         DWARFDie child = getFirstChild();
615         if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0 && child) {
616           DumpOpts.ChildRecurseDepth--;
617           DIDumpOptions ChildDumpOpts = DumpOpts;
618           ChildDumpOpts.ShowParents = false;
619           while (child) {
620             child.dump(OS, Indent + 2, ChildDumpOpts);
621             child = child.getSibling();
622           }
623         }
624       } else {
625         OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
626            << abbrCode << '\n';
627       }
628     } else {
629       OS.indent(Indent) << "NULL\n";
630     }
631   }
632 }
633 
634 LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }
635 
636 DWARFDie DWARFDie::getParent() const {
637   if (isValid())
638     return U->getParent(Die);
639   return DWARFDie();
640 }
641 
642 DWARFDie DWARFDie::getSibling() const {
643   if (isValid())
644     return U->getSibling(Die);
645   return DWARFDie();
646 }
647 
648 DWARFDie DWARFDie::getPreviousSibling() const {
649   if (isValid())
650     return U->getPreviousSibling(Die);
651   return DWARFDie();
652 }
653 
654 DWARFDie DWARFDie::getFirstChild() const {
655   if (isValid())
656     return U->getFirstChild(Die);
657   return DWARFDie();
658 }
659 
660 DWARFDie DWARFDie::getLastChild() const {
661   if (isValid())
662     return U->getLastChild(Die);
663   return DWARFDie();
664 }
665 
666 iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
667   return make_range(attribute_iterator(*this, false),
668                     attribute_iterator(*this, true));
669 }
670 
671 DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
672     : Die(D), Index(0) {
673   auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
674   assert(AbbrDecl && "Must have abbreviation declaration");
675   if (End) {
676     // This is the end iterator so we set the index to the attribute count.
677     Index = AbbrDecl->getNumAttributes();
678   } else {
679     // This is the begin iterator so we extract the value for this->Index.
680     AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
681     updateForIndex(*AbbrDecl, 0);
682   }
683 }
684 
685 void DWARFDie::attribute_iterator::updateForIndex(
686     const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
687   Index = I;
688   // AbbrDecl must be valid before calling this function.
689   auto NumAttrs = AbbrDecl.getNumAttributes();
690   if (Index < NumAttrs) {
691     AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
692     // Add the previous byte size of any previous attribute value.
693     AttrValue.Offset += AttrValue.ByteSize;
694     uint64_t ParseOffset = AttrValue.Offset;
695     auto U = Die.getDwarfUnit();
696     assert(U && "Die must have valid DWARF unit");
697     AttrValue.Value = DWARFFormValue::createFromUnit(
698         AbbrDecl.getFormByIndex(Index), U, &ParseOffset);
699     AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
700   } else {
701     assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
702     AttrValue = {};
703   }
704 }
705 
706 DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
707   if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
708     updateForIndex(*AbbrDecl, Index + 1);
709   return *this;
710 }
711 
712 bool DWARFAttribute::mayHaveLocationDescription(dwarf::Attribute Attr) {
713   switch (Attr) {
714   // From the DWARF v5 specification.
715   case DW_AT_location:
716   case DW_AT_byte_size:
717   case DW_AT_bit_size:
718   case DW_AT_string_length:
719   case DW_AT_lower_bound:
720   case DW_AT_return_addr:
721   case DW_AT_bit_stride:
722   case DW_AT_upper_bound:
723   case DW_AT_count:
724   case DW_AT_data_member_location:
725   case DW_AT_frame_base:
726   case DW_AT_segment:
727   case DW_AT_static_link:
728   case DW_AT_use_location:
729   case DW_AT_vtable_elem_location:
730   case DW_AT_allocated:
731   case DW_AT_associated:
732   case DW_AT_byte_stride:
733   case DW_AT_rank:
734   case DW_AT_call_value:
735   case DW_AT_call_origin:
736   case DW_AT_call_target:
737   case DW_AT_call_target_clobbered:
738   case DW_AT_call_data_location:
739   case DW_AT_call_data_value:
740   // Extensions.
741   case DW_AT_GNU_call_site_value:
742   case DW_AT_GNU_call_site_target:
743     return true;
744   default:
745     return false;
746   }
747 }
748