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