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 dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue,
73                              DWARFUnit *U, unsigned Indent,
74                              DIDumpOptions DumpOpts) {
75   assert(FormValue.isFormClass(DWARFFormValue::FC_SectionOffset) &&
76          "bad FORM for location list");
77   DWARFContext &Ctx = U->getContext();
78   const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
79   uint64_t Offset = *FormValue.getAsSectionOffset();
80 
81   if (FormValue.getForm() == DW_FORM_loclistx) {
82     FormValue.dump(OS, DumpOpts);
83 
84     if (auto LoclistOffset = U->getLoclistOffset(Offset))
85       Offset = *LoclistOffset;
86     else
87       return;
88   }
89   U->getLocationTable().dumpLocationList(&Offset, OS, U->getBaseAddress(), MRI,
90                                          Ctx.getDWARFObj(), U, DumpOpts,
91                                          Indent);
92   return;
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   return;
109 }
110 
111 namespace {
112 
113 // FIXME: We should have pretty printers per language. Currently we print
114 // everything as if it was C++ and fall back to the TAG type name.
115 struct DWARFTypePrinter {
116   raw_ostream &OS;
117   bool Word = true;
118   bool EndedWithTemplate = false;
119 
120   DWARFTypePrinter(raw_ostream &OS) : OS(OS) {}
121 
122   /// Dump the name encoded in the type tag.
123   void appendTypeTagName(dwarf::Tag T) {
124     StringRef TagStr = TagString(T);
125     static constexpr StringRef Prefix = "DW_TAG_";
126     static constexpr StringRef Suffix = "_type";
127     if (!TagStr.startswith(Prefix) || !TagStr.endswith(Suffix))
128       return;
129     OS << TagStr.substr(Prefix.size(),
130                         TagStr.size() - (Prefix.size() + Suffix.size()))
131        << " ";
132   }
133 
134   void appendArrayType(const DWARFDie &D) {
135     for (const DWARFDie &C : D.children()) {
136       if (C.getTag() != DW_TAG_subrange_type)
137         continue;
138       Optional<uint64_t> LB;
139       Optional<uint64_t> Count;
140       Optional<uint64_t> UB;
141       Optional<unsigned> DefaultLB;
142       if (Optional<DWARFFormValue> L = C.find(DW_AT_lower_bound))
143         LB = L->getAsUnsignedConstant();
144       if (Optional<DWARFFormValue> CountV = C.find(DW_AT_count))
145         Count = CountV->getAsUnsignedConstant();
146       if (Optional<DWARFFormValue> UpperV = C.find(DW_AT_upper_bound))
147         UB = UpperV->getAsUnsignedConstant();
148       if (Optional<DWARFFormValue> LV =
149               D.getDwarfUnit()->getUnitDIE().find(DW_AT_language))
150         if (Optional<uint64_t> LC = LV->getAsUnsignedConstant())
151           if ((DefaultLB =
152                    LanguageLowerBound(static_cast<dwarf::SourceLanguage>(*LC))))
153             if (LB && *LB == *DefaultLB)
154               LB = None;
155       if (!LB && !Count && !UB)
156         OS << "[]";
157       else if (!LB && (Count || UB) && DefaultLB)
158         OS << '[' << (Count ? *Count : *UB - *DefaultLB + 1) << ']';
159       else {
160         OS << "[[";
161         if (LB)
162           OS << *LB;
163         else
164           OS << '?';
165         OS << ", ";
166         if (Count)
167           if (LB)
168             OS << *LB + *Count;
169           else
170             OS << "? + " << *Count;
171         else if (UB)
172           OS << *UB + 1;
173         else
174           OS << '?';
175         OS << ")]";
176       }
177     }
178     EndedWithTemplate = false;
179   }
180 
181   DWARFDie skipQualifiers(DWARFDie D) {
182     while (D && (D.getTag() == DW_TAG_const_type ||
183                  D.getTag() == DW_TAG_volatile_type))
184       D = D.getAttributeValueAsReferencedDie(DW_AT_type);
185     return D;
186   }
187 
188   bool needsParens(DWARFDie D) {
189     D = skipQualifiers(D);
190     return D && (D.getTag() == DW_TAG_subroutine_type || D.getTag() == DW_TAG_array_type);
191   }
192 
193   void appendPointerLikeTypeBefore(DWARFDie D, DWARFDie Inner, StringRef Ptr) {
194     appendQualifiedNameBefore(Inner);
195     if (Word)
196       OS << ' ';
197     if (needsParens(Inner))
198       OS << '(';
199     OS << Ptr;
200     Word = false;
201     EndedWithTemplate = false;
202   }
203 
204   DWARFDie
205   appendUnqualifiedNameBefore(DWARFDie D,
206                               std::string *OriginalFullName = nullptr) {
207     Word = true;
208     if (!D) {
209       OS << "void";
210       return DWARFDie();
211     }
212     DWARFDie Inner = D.getAttributeValueAsReferencedDie(DW_AT_type);
213     const dwarf::Tag T = D.getTag();
214     switch (T) {
215     case DW_TAG_pointer_type: {
216       appendPointerLikeTypeBefore(D, Inner, "*");
217       break;
218     }
219     case DW_TAG_subroutine_type: {
220       appendQualifiedNameBefore(Inner);
221       if (Word) {
222         OS << ' ';
223       }
224       Word = false;
225       break;
226     }
227     case DW_TAG_array_type: {
228       appendQualifiedNameBefore(Inner);
229       break;
230     }
231     case DW_TAG_reference_type:
232       appendPointerLikeTypeBefore(D, Inner, "&");
233       break;
234     case DW_TAG_rvalue_reference_type:
235       appendPointerLikeTypeBefore(D, Inner, "&&");
236       break;
237     case DW_TAG_ptr_to_member_type: {
238       appendQualifiedNameBefore(Inner);
239       if (needsParens(Inner))
240         OS << '(';
241       else if (Word)
242         OS << ' ';
243       if (DWARFDie Cont =
244               D.getAttributeValueAsReferencedDie(DW_AT_containing_type)) {
245         appendQualifiedName(Cont);
246         OS << "::";
247       }
248       OS << "*";
249       Word = false;
250       break;
251     }
252     case DW_TAG_const_type:
253     case DW_TAG_volatile_type:
254       appendConstVolatileQualifierBefore(D);
255       break;
256     case DW_TAG_namespace: {
257       if (const char *Name = dwarf::toString(D.find(DW_AT_name), nullptr))
258         OS << Name;
259       else
260         OS << "(anonymous namespace)";
261       break;
262     }
263     case DW_TAG_unspecified_type: {
264       StringRef TypeName = D.getShortName();
265       if (TypeName == "decltype(nullptr)")
266         TypeName = "std::nullptr_t";
267       Word = true;
268       OS << TypeName;
269       EndedWithTemplate = false;
270       break;
271     }
272       /*
273     case DW_TAG_structure_type:
274     case DW_TAG_class_type:
275     case DW_TAG_enumeration_type:
276     case DW_TAG_base_type:
277     */
278     default: {
279       const char *NamePtr = dwarf::toString(D.find(DW_AT_name), nullptr);
280       if (!NamePtr) {
281         appendTypeTagName(D.getTag());
282         return Inner;
283       }
284       Word = true;
285       StringRef Name = NamePtr;
286       static constexpr StringRef MangledPrefix = "_STN";
287       if (Name.startswith(MangledPrefix)) {
288         Name = Name.drop_front(MangledPrefix.size());
289         auto Separator = Name.find('|');
290         assert(Separator != StringRef::npos);
291         StringRef BaseName = Name.substr(0, Separator);
292         StringRef TemplateArgs = Name.substr(Separator + 1);
293         if (OriginalFullName)
294           *OriginalFullName = (BaseName + TemplateArgs).str();
295         Name = BaseName;
296       } else
297         EndedWithTemplate = Name.endswith(">");
298       OS << Name;
299       // This check would be insufficient for operator overloads like
300       // "operator>>" - but for now Clang doesn't try to simplify them, so this
301       // is OK. Add more nuanced operator overload handling here if/when needed.
302       if (Name.endswith(">"))
303         break;
304       if (!appendTemplateParameters(D))
305         break;
306 
307       if (EndedWithTemplate)
308         OS << ' ';
309       OS << '>';
310       EndedWithTemplate = true;
311       Word = true;
312       break;
313     }
314     }
315     return Inner;
316   }
317 
318   void appendUnqualifiedNameAfter(DWARFDie D, DWARFDie Inner,
319                                   bool SkipFirstParamIfArtificial = false) {
320     if (!D)
321       return;
322     switch (D.getTag()) {
323     case DW_TAG_subroutine_type: {
324       appendSubroutineNameAfter(D, Inner, SkipFirstParamIfArtificial, false,
325                                 false);
326       break;
327     }
328     case DW_TAG_array_type: {
329       appendArrayType(D);
330       break;
331     }
332     case DW_TAG_const_type:
333     case DW_TAG_volatile_type:
334       appendConstVolatileQualifierAfter(D);
335       break;
336     case DW_TAG_ptr_to_member_type:
337     case DW_TAG_reference_type:
338     case DW_TAG_rvalue_reference_type:
339     case DW_TAG_pointer_type: {
340       if (needsParens(Inner))
341         OS << ')';
342       appendUnqualifiedNameAfter(
343           Inner, Inner.getAttributeValueAsReferencedDie(DW_AT_type),
344           /*SkipFirstParamIfArtificial=*/D.getTag() ==
345               DW_TAG_ptr_to_member_type);
346       break;
347     }
348       /*
349     case DW_TAG_structure_type:
350     case DW_TAG_class_type:
351     case DW_TAG_enumeration_type:
352     case DW_TAG_base_type:
353     case DW_TAG_namespace:
354     */
355     default:
356       break;
357     }
358   }
359 
360   void appendQualifiedName(DWARFDie D) {
361     if (D)
362       appendScopes(D.getParent());
363     appendUnqualifiedName(D);
364   }
365   DWARFDie appendQualifiedNameBefore(DWARFDie D) {
366     if (D)
367       appendScopes(D.getParent());
368     return appendUnqualifiedNameBefore(D);
369   }
370   bool appendTemplateParameters(DWARFDie D, bool *FirstParameter = nullptr) {
371     bool FirstParameterValue = true;
372     bool IsTemplate = false;
373     if (!FirstParameter)
374       FirstParameter = &FirstParameterValue;
375     for (const DWARFDie &C : D) {
376       auto Sep = [&] {
377         if (*FirstParameter)
378           OS << '<';
379         else
380           OS << ", ";
381         IsTemplate = true;
382         EndedWithTemplate = false;
383         *FirstParameter = false;
384       };
385       if (C.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) {
386         IsTemplate = true;
387         appendTemplateParameters(C, FirstParameter);
388       }
389       if (C.getTag() == dwarf::DW_TAG_template_value_parameter) {
390         DWARFDie T = C.getAttributeValueAsReferencedDie(DW_AT_type);
391         Sep();
392         if (T.getTag() == DW_TAG_enumeration_type) {
393           auto V = C.find(DW_AT_const_value);
394           bool FoundEnumerator = false;
395           for (const DWARFDie &Enumerator : T) {
396             auto EV = Enumerator.find(DW_AT_const_value);
397             if (V && EV &&
398                 V->getAsSignedConstant() == EV->getAsSignedConstant()) {
399               if (T.find(DW_AT_enum_class)) {
400                 appendQualifiedName(T);
401                 OS << "::";
402               } else
403                 appendScopes(T.getParent());
404               OS << Enumerator.getShortName();
405               FoundEnumerator = true;
406               break;
407             }
408           }
409           if (FoundEnumerator)
410             continue;
411           OS << '(';
412           appendQualifiedName(T);
413           OS << ')';
414           OS << to_string(*V->getAsSignedConstant());
415           continue;
416         }
417         // /Maybe/ we could do pointer type parameters, looking for the
418         // symbol in the ELF symbol table to get back to the variable...
419         // but probably not worth it.
420         if (T.getTag() == DW_TAG_pointer_type)
421           continue;
422         const char *RawName = dwarf::toString(T.find(DW_AT_name), nullptr);
423         assert(RawName);
424         StringRef Name = RawName;
425         auto V = C.find(DW_AT_const_value);
426         bool IsQualifiedChar = false;
427         if (Name == "bool") {
428           OS << (*V->getAsUnsignedConstant() ? "true" : "false");
429         } else if (Name == "short") {
430           OS << "(short)";
431           OS << to_string(*V->getAsSignedConstant());
432         } else if (Name == "unsigned short") {
433           OS << "(unsigned short)";
434           OS << to_string(*V->getAsSignedConstant());
435         } else if (Name == "int")
436           OS << to_string(*V->getAsSignedConstant());
437         else if (Name == "long") {
438           OS << to_string(*V->getAsSignedConstant());
439           OS << "L";
440         } else if (Name == "long long") {
441           OS << to_string(*V->getAsSignedConstant());
442           OS << "LL";
443         } else if (Name == "unsigned int") {
444           OS << to_string(*V->getAsUnsignedConstant());
445           OS << "U";
446         } else if (Name == "unsigned long") {
447           OS << to_string(*V->getAsUnsignedConstant());
448           OS << "UL";
449         } else if (Name == "unsigned long long") {
450           OS << to_string(*V->getAsUnsignedConstant());
451           OS << "ULL";
452         } else if (Name == "char" ||
453                    (IsQualifiedChar =
454                         (Name == "unsigned char" || Name == "signed char"))) {
455           // FIXME: check T's DW_AT_type to see if it's signed or not (since
456           // char signedness is implementation defined).
457           auto Val = *V->getAsSignedConstant();
458           // Copied/hacked up from Clang's CharacterLiteral::print - incomplete
459           // (doesn't actually support different character types/widths, sign
460           // handling's not done, and doesn't correctly test if a character is
461           // printable or needs to use a numeric escape sequence instead)
462           if (IsQualifiedChar) {
463             OS << '(';
464             OS << Name;
465             OS << ')';
466           }
467           switch (Val) {
468           case '\\':
469             OS << "'\\\\'";
470             break;
471           case '\'':
472             OS << "'\\''";
473             break;
474           case '\a':
475             // TODO: K&R: the meaning of '\\a' is different in traditional C
476             OS << "'\\a'";
477             break;
478           case '\b':
479             OS << "'\\b'";
480             break;
481           case '\f':
482             OS << "'\\f'";
483             break;
484           case '\n':
485             OS << "'\\n'";
486             break;
487           case '\r':
488             OS << "'\\r'";
489             break;
490           case '\t':
491             OS << "'\\t'";
492             break;
493           case '\v':
494             OS << "'\\v'";
495             break;
496           default:
497             if ((Val & ~0xFFu) == ~0xFFu)
498               Val &= 0xFFu;
499             if (Val < 127 && Val >= 32) {
500               OS << "'";
501               OS << (char)Val;
502               OS << "'";
503             } else if (Val < 256)
504               OS << to_string(llvm::format("'\\x%02x'", Val));
505             else if (Val <= 0xFFFF)
506               OS << to_string(llvm::format("'\\u%04x'", Val));
507             else
508               OS << to_string(llvm::format("'\\U%08x'", Val));
509           }
510         }
511         continue;
512       }
513       if (C.getTag() == dwarf::DW_TAG_GNU_template_template_param) {
514         const char *RawName =
515             dwarf::toString(C.find(DW_AT_GNU_template_name), nullptr);
516         assert(RawName);
517         StringRef Name = RawName;
518         Sep();
519         OS << Name;
520         continue;
521       }
522       if (C.getTag() != dwarf::DW_TAG_template_type_parameter)
523         continue;
524       auto TypeAttr = C.find(DW_AT_type);
525       Sep();
526       appendQualifiedName(TypeAttr
527                               ? C.getAttributeValueAsReferencedDie(*TypeAttr)
528                               : DWARFDie());
529     }
530     if (IsTemplate && *FirstParameter && FirstParameter == &FirstParameterValue)
531       OS << '<';
532     return IsTemplate;
533   }
534   void decomposeConstVolatile(DWARFDie &N, DWARFDie &T, DWARFDie &C,
535                               DWARFDie &V) {
536     (N.getTag() == DW_TAG_const_type ? C : V) = N;
537     T = N.getAttributeValueAsReferencedDie(DW_AT_type);
538     if (T) {
539       auto Tag = T.getTag();
540       if (Tag == DW_TAG_const_type) {
541         C = T;
542         T = T.getAttributeValueAsReferencedDie(DW_AT_type);
543       } else if (Tag == DW_TAG_volatile_type) {
544         V = T;
545         T = T.getAttributeValueAsReferencedDie(DW_AT_type);
546       }
547     }
548   }
549   void appendConstVolatileQualifierAfter(DWARFDie N) {
550     DWARFDie C;
551     DWARFDie V;
552     DWARFDie T;
553     decomposeConstVolatile(N, T, C, V);
554     if (T && T.getTag() == DW_TAG_subroutine_type)
555       appendSubroutineNameAfter(T,
556                                 T.getAttributeValueAsReferencedDie(DW_AT_type),
557                                 false, C.isValid(), V.isValid());
558     else
559       appendUnqualifiedNameAfter(
560           T, T.getAttributeValueAsReferencedDie(DW_AT_type));
561   }
562   void appendConstVolatileQualifierBefore(DWARFDie N) {
563     DWARFDie C;
564     DWARFDie V;
565     DWARFDie T;
566     decomposeConstVolatile(N, T, C, V);
567     bool Subroutine = T && T.getTag() == DW_TAG_subroutine_type;
568     DWARFDie A = T;
569     while (A && A.getTag() == DW_TAG_array_type)
570       A = A.getAttributeValueAsReferencedDie(DW_AT_type);
571     bool Leading =
572         (!A || (A.getTag() != DW_TAG_pointer_type &&
573                 A.getTag() != llvm::dwarf::DW_TAG_ptr_to_member_type)) &&
574         !Subroutine;
575     if (Leading) {
576       if (C)
577         OS << "const ";
578       if (V)
579         OS << "volatile ";
580     }
581     appendQualifiedNameBefore(T);
582     if (!Leading && !Subroutine) {
583       Word = true;
584       if (C)
585         OS << "const";
586       if (V) {
587         if (C)
588           OS << ' ';
589         OS << "volatile";
590       }
591     }
592   }
593 
594   /// Recursively append the DIE type name when applicable.
595   void appendUnqualifiedName(DWARFDie D,
596                              std::string *OriginalFullName = nullptr) {
597     // FIXME: We should have pretty printers per language. Currently we print
598     // everything as if it was C++ and fall back to the TAG type name.
599     DWARFDie Inner = appendUnqualifiedNameBefore(D, OriginalFullName);
600     appendUnqualifiedNameAfter(D, Inner);
601   }
602 
603   void appendSubroutineNameAfter(DWARFDie D, DWARFDie Inner,
604                                  bool SkipFirstParamIfArtificial, bool Const,
605                                  bool Volatile) {
606     DWARFDie FirstParamIfArtificial;
607     OS << '(';
608     EndedWithTemplate = false;
609     bool First = true;
610     bool RealFirst = true;
611     for (DWARFDie P : D) {
612       if (P.getTag() != DW_TAG_formal_parameter)
613         return;
614       DWARFDie T = P.getAttributeValueAsReferencedDie(DW_AT_type);
615       if (SkipFirstParamIfArtificial && RealFirst && P.find(DW_AT_artificial)) {
616         FirstParamIfArtificial = T;
617         RealFirst = false;
618         continue;
619       }
620       if (!First) {
621         OS << ", ";
622       }
623       First = false;
624       appendQualifiedName(T);
625     }
626     EndedWithTemplate = false;
627     OS << ')';
628     if (FirstParamIfArtificial) {
629       if (DWARFDie P = FirstParamIfArtificial) {
630         if (P.getTag() == DW_TAG_pointer_type) {
631           DWARFDie C;
632           DWARFDie V;
633           auto CVStep = [&](DWARFDie CV) {
634             if (DWARFDie U = CV.getAttributeValueAsReferencedDie(DW_AT_type)) {
635               if (U.getTag() == DW_TAG_const_type)
636                 return C = U;
637               if (U.getTag() == DW_TAG_volatile_type)
638                 return V = U;
639             }
640             return DWARFDie();
641           };
642           if (DWARFDie CV = CVStep(P)) {
643             CVStep(CV);
644           }
645           if (C)
646             OS << " const";
647           if (V)
648             OS << " volatile";
649         }
650       }
651     } else {
652       if (Const)
653         OS << " const";
654       if (Volatile)
655         OS << " volatile";
656     }
657     if (D.find(DW_AT_reference))
658       OS << " &";
659     if (D.find(DW_AT_rvalue_reference))
660       OS << " &&";
661     appendUnqualifiedNameAfter(
662         Inner, Inner.getAttributeValueAsReferencedDie(DW_AT_type));
663   }
664   void appendScopes(DWARFDie D) {
665     if (D.getTag() == DW_TAG_compile_unit)
666       return;
667     if (D.getTag() == DW_TAG_type_unit)
668       return;
669     if (D.getTag() == DW_TAG_skeleton_unit)
670       return;
671     if (D.getTag() == DW_TAG_subprogram)
672       return;
673     if (DWARFDie P = D.getParent())
674       appendScopes(P);
675     appendUnqualifiedName(D);
676     OS << "::";
677   }
678 };
679 } // anonymous namespace
680 
681 static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
682                           const DWARFAttribute &AttrValue, unsigned Indent,
683                           DIDumpOptions DumpOpts) {
684   if (!Die.isValid())
685     return;
686   const char BaseIndent[] = "            ";
687   OS << BaseIndent;
688   OS.indent(Indent + 2);
689   dwarf::Attribute Attr = AttrValue.Attr;
690   WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
691 
692   dwarf::Form Form = AttrValue.Value.getForm();
693   if (DumpOpts.Verbose || DumpOpts.ShowForm)
694     OS << formatv(" [{0}]", Form);
695 
696   DWARFUnit *U = Die.getDwarfUnit();
697   const DWARFFormValue &FormValue = AttrValue.Value;
698 
699   OS << "\t(";
700 
701   StringRef Name;
702   std::string File;
703   auto Color = HighlightColor::Enumerator;
704   if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
705     Color = HighlightColor::String;
706     if (const auto *LT = U->getContext().getLineTableForUnit(U))
707       if (LT->getFileNameByIndex(
708               FormValue.getAsUnsignedConstant().getValue(),
709               U->getCompilationDir(),
710               DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
711         File = '"' + File + '"';
712         Name = File;
713       }
714   } else if (Optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
715     Name = AttributeValueString(Attr, *Val);
716 
717   if (!Name.empty())
718     WithColor(OS, Color) << Name;
719   else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
720     OS << *FormValue.getAsUnsignedConstant();
721   else if (Attr == DW_AT_low_pc &&
722            (FormValue.getAsAddress() ==
723             dwarf::computeTombstoneAddress(U->getAddressByteSize()))) {
724     if (DumpOpts.Verbose) {
725       FormValue.dump(OS, DumpOpts);
726       OS << " (";
727     }
728     OS << "dead code";
729     if (DumpOpts.Verbose)
730       OS << ')';
731   } else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
732              FormValue.getAsUnsignedConstant()) {
733     if (DumpOpts.ShowAddresses) {
734       // Print the actual address rather than the offset.
735       uint64_t LowPC, HighPC, Index;
736       if (Die.getLowAndHighPC(LowPC, HighPC, Index))
737         DWARFFormValue::dumpAddress(OS, U->getAddressByteSize(), HighPC);
738       else
739         FormValue.dump(OS, DumpOpts);
740     }
741   } else if (DWARFAttribute::mayHaveLocationList(Attr) &&
742              FormValue.isFormClass(DWARFFormValue::FC_SectionOffset))
743     dumpLocationList(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
744                      DumpOpts);
745   else if (FormValue.isFormClass(DWARFFormValue::FC_Exprloc) ||
746            (DWARFAttribute::mayHaveLocationExpr(Attr) &&
747             FormValue.isFormClass(DWARFFormValue::FC_Block)))
748     dumpLocationExpr(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
749                      DumpOpts);
750   else
751     FormValue.dump(OS, DumpOpts);
752 
753   std::string Space = DumpOpts.ShowAddresses ? " " : "";
754 
755   // We have dumped the attribute raw value. For some attributes
756   // having both the raw value and the pretty-printed value is
757   // interesting. These attributes are handled below.
758   if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
759     if (const char *Name =
760             Die.getAttributeValueAsReferencedDie(FormValue).getName(
761                 DINameKind::LinkageName))
762       OS << Space << "\"" << Name << '\"';
763   } else if (Attr == DW_AT_type) {
764     DWARFDie D = Die.getAttributeValueAsReferencedDie(FormValue);
765     if (D && !D.isNULL()) {
766       OS << Space << "\"";
767       DWARFTypePrinter(OS).appendQualifiedName(D);
768       OS << '"';
769     }
770   } else if (Attr == DW_AT_APPLE_property_attribute) {
771     if (Optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
772       dumpApplePropertyAttribute(OS, *OptVal);
773   } else if (Attr == DW_AT_ranges) {
774     const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
775     // For DW_FORM_rnglistx we need to dump the offset separately, since
776     // we have only dumped the index so far.
777     if (FormValue.getForm() == DW_FORM_rnglistx)
778       if (auto RangeListOffset =
779               U->getRnglistOffset(*FormValue.getAsSectionOffset())) {
780         DWARFFormValue FV = DWARFFormValue::createFromUValue(
781             dwarf::DW_FORM_sec_offset, *RangeListOffset);
782         FV.dump(OS, DumpOpts);
783       }
784     if (auto RangesOrError = Die.getAddressRanges())
785       dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
786                  sizeof(BaseIndent) + Indent + 4, DumpOpts);
787     else
788       DumpOpts.RecoverableErrorHandler(createStringError(
789           errc::invalid_argument, "decoding address ranges: %s",
790           toString(RangesOrError.takeError()).c_str()));
791   }
792 
793   OS << ")\n";
794 }
795 
796 void DWARFDie::getFullName(raw_string_ostream &OS,
797                            std::string *OriginalFullName) const {
798   const char *NamePtr = getShortName();
799   if (!NamePtr)
800     return;
801   DWARFTypePrinter(OS).appendUnqualifiedName(*this, OriginalFullName);
802 }
803 
804 bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
805 
806 bool DWARFDie::isSubroutineDIE() const {
807   auto Tag = getTag();
808   return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
809 }
810 
811 Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
812   if (!isValid())
813     return None;
814   auto AbbrevDecl = getAbbreviationDeclarationPtr();
815   if (AbbrevDecl)
816     return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
817   return None;
818 }
819 
820 Optional<DWARFFormValue>
821 DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
822   if (!isValid())
823     return None;
824   auto AbbrevDecl = getAbbreviationDeclarationPtr();
825   if (AbbrevDecl) {
826     for (auto Attr : Attrs) {
827       if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
828         return Value;
829     }
830   }
831   return None;
832 }
833 
834 Optional<DWARFFormValue>
835 DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
836   SmallVector<DWARFDie, 3> Worklist;
837   Worklist.push_back(*this);
838 
839   // Keep track if DIEs already seen to prevent infinite recursion.
840   // Empirically we rarely see a depth of more than 3 when dealing with valid
841   // DWARF. This corresponds to following the DW_AT_abstract_origin and
842   // DW_AT_specification just once.
843   SmallSet<DWARFDie, 3> Seen;
844   Seen.insert(*this);
845 
846   while (!Worklist.empty()) {
847     DWARFDie Die = Worklist.pop_back_val();
848 
849     if (!Die.isValid())
850       continue;
851 
852     if (auto Value = Die.find(Attrs))
853       return Value;
854 
855     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
856       if (Seen.insert(D).second)
857         Worklist.push_back(D);
858 
859     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
860       if (Seen.insert(D).second)
861         Worklist.push_back(D);
862   }
863 
864   return None;
865 }
866 
867 DWARFDie
868 DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
869   if (Optional<DWARFFormValue> F = find(Attr))
870     return getAttributeValueAsReferencedDie(*F);
871   return DWARFDie();
872 }
873 
874 DWARFDie
875 DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
876   if (auto SpecRef = V.getAsRelativeReference()) {
877     if (SpecRef->Unit)
878       return SpecRef->Unit->getDIEForOffset(SpecRef->Unit->getOffset() + SpecRef->Offset);
879     if (auto SpecUnit = U->getUnitVector().getUnitForOffset(SpecRef->Offset))
880       return SpecUnit->getDIEForOffset(SpecRef->Offset);
881   }
882   return DWARFDie();
883 }
884 
885 Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
886   return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
887 }
888 
889 Optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
890   return toSectionOffset(find(DW_AT_loclists_base));
891 }
892 
893 Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
894   uint64_t Tombstone = dwarf::computeTombstoneAddress(U->getAddressByteSize());
895   if (LowPC == Tombstone)
896     return None;
897   if (auto FormValue = find(DW_AT_high_pc)) {
898     if (auto Address = FormValue->getAsAddress()) {
899       // High PC is an address.
900       return Address;
901     }
902     if (auto Offset = FormValue->getAsUnsignedConstant()) {
903       // High PC is an offset from LowPC.
904       return LowPC + *Offset;
905     }
906   }
907   return None;
908 }
909 
910 bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
911                                uint64_t &SectionIndex) const {
912   auto F = find(DW_AT_low_pc);
913   auto LowPcAddr = toSectionedAddress(F);
914   if (!LowPcAddr)
915     return false;
916   if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
917     LowPC = LowPcAddr->Address;
918     HighPC = *HighPcAddr;
919     SectionIndex = LowPcAddr->SectionIndex;
920     return true;
921   }
922   return false;
923 }
924 
925 Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
926   if (isNULL())
927     return DWARFAddressRangesVector();
928   // Single range specified by low/high PC.
929   uint64_t LowPC, HighPC, Index;
930   if (getLowAndHighPC(LowPC, HighPC, Index))
931     return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
932 
933   Optional<DWARFFormValue> Value = find(DW_AT_ranges);
934   if (Value) {
935     if (Value->getForm() == DW_FORM_rnglistx)
936       return U->findRnglistFromIndex(*Value->getAsSectionOffset());
937     return U->findRnglistFromOffset(*Value->getAsSectionOffset());
938   }
939   return DWARFAddressRangesVector();
940 }
941 
942 bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
943   auto RangesOrError = getAddressRanges();
944   if (!RangesOrError) {
945     llvm::consumeError(RangesOrError.takeError());
946     return false;
947   }
948 
949   for (const auto &R : RangesOrError.get())
950     if (R.LowPC <= Address && Address < R.HighPC)
951       return true;
952   return false;
953 }
954 
955 Expected<DWARFLocationExpressionsVector>
956 DWARFDie::getLocations(dwarf::Attribute Attr) const {
957   Optional<DWARFFormValue> Location = find(Attr);
958   if (!Location)
959     return createStringError(inconvertibleErrorCode(), "No %s",
960                              dwarf::AttributeString(Attr).data());
961 
962   if (Optional<uint64_t> Off = Location->getAsSectionOffset()) {
963     uint64_t Offset = *Off;
964 
965     if (Location->getForm() == DW_FORM_loclistx) {
966       if (auto LoclistOffset = U->getLoclistOffset(Offset))
967         Offset = *LoclistOffset;
968       else
969         return createStringError(inconvertibleErrorCode(),
970                                  "Loclist table not found");
971     }
972     return U->findLoclistFromOffset(Offset);
973   }
974 
975   if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
976     return DWARFLocationExpressionsVector{
977         DWARFLocationExpression{None, to_vector<4>(*Expr)}};
978   }
979 
980   return createStringError(
981       inconvertibleErrorCode(), "Unsupported %s encoding: %s",
982       dwarf::AttributeString(Attr).data(),
983       dwarf::FormEncodingString(Location->getForm()).data());
984 }
985 
986 const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
987   if (!isSubroutineDIE())
988     return nullptr;
989   return getName(Kind);
990 }
991 
992 const char *DWARFDie::getName(DINameKind Kind) const {
993   if (!isValid() || Kind == DINameKind::None)
994     return nullptr;
995   // Try to get mangled name only if it was asked for.
996   if (Kind == DINameKind::LinkageName) {
997     if (auto Name = getLinkageName())
998       return Name;
999   }
1000   return getShortName();
1001 }
1002 
1003 const char *DWARFDie::getShortName() const {
1004   if (!isValid())
1005     return nullptr;
1006 
1007   return dwarf::toString(findRecursively(dwarf::DW_AT_name), nullptr);
1008 }
1009 
1010 const char *DWARFDie::getLinkageName() const {
1011   if (!isValid())
1012     return nullptr;
1013 
1014   return dwarf::toString(findRecursively({dwarf::DW_AT_MIPS_linkage_name,
1015                                           dwarf::DW_AT_linkage_name}),
1016                          nullptr);
1017 }
1018 
1019 uint64_t DWARFDie::getDeclLine() const {
1020   return toUnsigned(findRecursively(DW_AT_decl_line), 0);
1021 }
1022 
1023 std::string
1024 DWARFDie::getDeclFile(DILineInfoSpecifier::FileLineInfoKind Kind) const {
1025   if (auto FormValue = findRecursively(DW_AT_decl_file))
1026     if (auto OptString = FormValue->getAsFile(Kind))
1027       return *OptString;
1028   return {};
1029 }
1030 
1031 void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
1032                               uint32_t &CallColumn,
1033                               uint32_t &CallDiscriminator) const {
1034   CallFile = toUnsigned(find(DW_AT_call_file), 0);
1035   CallLine = toUnsigned(find(DW_AT_call_line), 0);
1036   CallColumn = toUnsigned(find(DW_AT_call_column), 0);
1037   CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
1038 }
1039 
1040 /// Helper to dump a DIE with all of its parents, but no siblings.
1041 static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
1042                                 DIDumpOptions DumpOpts, unsigned Depth = 0) {
1043   if (!Die)
1044     return Indent;
1045   if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
1046     return Indent;
1047   Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts, Depth + 1);
1048   Die.dump(OS, Indent, DumpOpts);
1049   return Indent + 2;
1050 }
1051 
1052 void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
1053                     DIDumpOptions DumpOpts) const {
1054   if (!isValid())
1055     return;
1056   DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
1057   const uint64_t Offset = getOffset();
1058   uint64_t offset = Offset;
1059   if (DumpOpts.ShowParents) {
1060     DIDumpOptions ParentDumpOpts = DumpOpts;
1061     ParentDumpOpts.ShowParents = false;
1062     ParentDumpOpts.ShowChildren = false;
1063     Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
1064   }
1065 
1066   if (debug_info_data.isValidOffset(offset)) {
1067     uint32_t abbrCode = debug_info_data.getULEB128(&offset);
1068     if (DumpOpts.ShowAddresses)
1069       WithColor(OS, HighlightColor::Address).get()
1070           << format("\n0x%8.8" PRIx64 ": ", Offset);
1071 
1072     if (abbrCode) {
1073       auto AbbrevDecl = getAbbreviationDeclarationPtr();
1074       if (AbbrevDecl) {
1075         WithColor(OS, HighlightColor::Tag).get().indent(Indent)
1076             << formatv("{0}", getTag());
1077         if (DumpOpts.Verbose) {
1078           OS << format(" [%u] %c", abbrCode,
1079                        AbbrevDecl->hasChildren() ? '*' : ' ');
1080           if (Optional<uint32_t> ParentIdx = Die->getParentIdx())
1081             OS << format(" (0x%8.8" PRIx64 ")",
1082                          U->getDIEAtIndex(*ParentIdx).getOffset());
1083         }
1084         OS << '\n';
1085 
1086         // Dump all data in the DIE for the attributes.
1087         for (const DWARFAttribute &AttrValue : attributes())
1088           dumpAttribute(OS, *this, AttrValue, Indent, DumpOpts);
1089 
1090         if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0) {
1091           DWARFDie Child = getFirstChild();
1092           DumpOpts.ChildRecurseDepth--;
1093           DIDumpOptions ChildDumpOpts = DumpOpts;
1094           ChildDumpOpts.ShowParents = false;
1095           while (Child) {
1096             Child.dump(OS, Indent + 2, ChildDumpOpts);
1097             Child = Child.getSibling();
1098           }
1099         }
1100       } else {
1101         OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
1102            << abbrCode << '\n';
1103       }
1104     } else {
1105       OS.indent(Indent) << "NULL\n";
1106     }
1107   }
1108 }
1109 
1110 LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }
1111 
1112 DWARFDie DWARFDie::getParent() const {
1113   if (isValid())
1114     return U->getParent(Die);
1115   return DWARFDie();
1116 }
1117 
1118 DWARFDie DWARFDie::getSibling() const {
1119   if (isValid())
1120     return U->getSibling(Die);
1121   return DWARFDie();
1122 }
1123 
1124 DWARFDie DWARFDie::getPreviousSibling() const {
1125   if (isValid())
1126     return U->getPreviousSibling(Die);
1127   return DWARFDie();
1128 }
1129 
1130 DWARFDie DWARFDie::getFirstChild() const {
1131   if (isValid())
1132     return U->getFirstChild(Die);
1133   return DWARFDie();
1134 }
1135 
1136 DWARFDie DWARFDie::getLastChild() const {
1137   if (isValid())
1138     return U->getLastChild(Die);
1139   return DWARFDie();
1140 }
1141 
1142 iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
1143   return make_range(attribute_iterator(*this, false),
1144                     attribute_iterator(*this, true));
1145 }
1146 
1147 DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
1148     : Die(D), Index(0) {
1149   auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
1150   assert(AbbrDecl && "Must have abbreviation declaration");
1151   if (End) {
1152     // This is the end iterator so we set the index to the attribute count.
1153     Index = AbbrDecl->getNumAttributes();
1154   } else {
1155     // This is the begin iterator so we extract the value for this->Index.
1156     AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
1157     updateForIndex(*AbbrDecl, 0);
1158   }
1159 }
1160 
1161 void DWARFDie::attribute_iterator::updateForIndex(
1162     const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
1163   Index = I;
1164   // AbbrDecl must be valid before calling this function.
1165   auto NumAttrs = AbbrDecl.getNumAttributes();
1166   if (Index < NumAttrs) {
1167     AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
1168     // Add the previous byte size of any previous attribute value.
1169     AttrValue.Offset += AttrValue.ByteSize;
1170     uint64_t ParseOffset = AttrValue.Offset;
1171     if (AbbrDecl.getAttrIsImplicitConstByIndex(Index))
1172       AttrValue.Value = DWARFFormValue::createFromSValue(
1173           AbbrDecl.getFormByIndex(Index),
1174           AbbrDecl.getAttrImplicitConstValueByIndex(Index));
1175     else {
1176       auto U = Die.getDwarfUnit();
1177       assert(U && "Die must have valid DWARF unit");
1178       AttrValue.Value = DWARFFormValue::createFromUnit(
1179           AbbrDecl.getFormByIndex(Index), U, &ParseOffset);
1180     }
1181     AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
1182   } else {
1183     assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
1184     AttrValue = {};
1185   }
1186 }
1187 
1188 DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
1189   if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
1190     updateForIndex(*AbbrDecl, Index + 1);
1191   return *this;
1192 }
1193 
1194 bool DWARFAttribute::mayHaveLocationList(dwarf::Attribute Attr) {
1195   switch(Attr) {
1196   case DW_AT_location:
1197   case DW_AT_string_length:
1198   case DW_AT_return_addr:
1199   case DW_AT_data_member_location:
1200   case DW_AT_frame_base:
1201   case DW_AT_static_link:
1202   case DW_AT_segment:
1203   case DW_AT_use_location:
1204   case DW_AT_vtable_elem_location:
1205     return true;
1206   default:
1207     return false;
1208   }
1209 }
1210 
1211 bool DWARFAttribute::mayHaveLocationExpr(dwarf::Attribute Attr) {
1212   switch (Attr) {
1213   // From the DWARF v5 specification.
1214   case DW_AT_location:
1215   case DW_AT_byte_size:
1216   case DW_AT_bit_offset:
1217   case DW_AT_bit_size:
1218   case DW_AT_string_length:
1219   case DW_AT_lower_bound:
1220   case DW_AT_return_addr:
1221   case DW_AT_bit_stride:
1222   case DW_AT_upper_bound:
1223   case DW_AT_count:
1224   case DW_AT_data_member_location:
1225   case DW_AT_frame_base:
1226   case DW_AT_segment:
1227   case DW_AT_static_link:
1228   case DW_AT_use_location:
1229   case DW_AT_vtable_elem_location:
1230   case DW_AT_allocated:
1231   case DW_AT_associated:
1232   case DW_AT_data_location:
1233   case DW_AT_byte_stride:
1234   case DW_AT_rank:
1235   case DW_AT_call_value:
1236   case DW_AT_call_origin:
1237   case DW_AT_call_target:
1238   case DW_AT_call_target_clobbered:
1239   case DW_AT_call_data_location:
1240   case DW_AT_call_data_value:
1241   // Extensions.
1242   case DW_AT_GNU_call_site_value:
1243   case DW_AT_GNU_call_site_target:
1244     return true;
1245   default:
1246     return false;
1247   }
1248 }
1249