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