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