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