LLVM 24.0.0git
DWARFDie.cpp
Go to the documentation of this file.
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
11#include "llvm/ADT/SmallSet.h"
12#include "llvm/ADT/StringRef.h"
29#include <cassert>
30#include <cstdint>
31#include <string>
32
33using namespace llvm;
34using namespace dwarf;
35using namespace object;
36
38 OS << " (";
39 do {
40 uint64_t Shift = llvm::countr_zero(Val);
41 assert(Shift < 64 && "undefined behavior");
42 uint64_t Bit = 1ULL << Shift;
43 auto PropName = ApplePropertyString(Bit);
44 if (!PropName.empty())
45 OS << PropName;
46 else
47 OS << formatv("DW_APPLE_PROPERTY_{0:x}", Bit);
48 if (!(Val ^= Bit))
49 break;
50 OS << ", ";
51 } while (true);
52 OS << ")";
53}
54
55static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
56 const DWARFAddressRangesVector &Ranges,
57 unsigned AddressSize, unsigned Indent,
58 const DIDumpOptions &DumpOpts) {
59 if (!DumpOpts.ShowAddresses)
60 return;
61
62 for (const DWARFAddressRange &R : Ranges) {
63 OS << '\n';
64 OS.indent(Indent);
65 R.dump(OS, AddressSize, DumpOpts, &Obj);
66 }
67}
68
69static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue,
70 DWARFUnit *U, unsigned Indent,
71 DIDumpOptions DumpOpts) {
73 "bad FORM for location list");
74 DWARFContext &Ctx = U->getContext();
75 uint64_t Offset = *FormValue.getAsSectionOffset();
76
77 if (FormValue.getForm() == DW_FORM_loclistx) {
78 FormValue.dump(OS, DumpOpts);
79
80 if (auto LoclistOffset = U->getLoclistOffset(Offset))
81 Offset = *LoclistOffset;
82 else
83 return;
84 }
85 U->getLocationTable().dumpLocationList(
86 &Offset, OS, U->getBaseAddress(), Ctx.getDWARFObj(), U, DumpOpts, Indent);
87}
88
89static void dumpLocationExpr(raw_ostream &OS, const DWARFFormValue &FormValue,
90 DWARFUnit *U, unsigned Indent,
91 DIDumpOptions DumpOpts) {
94 "bad FORM for location expression");
95 DWARFContext &Ctx = U->getContext();
96 ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
97 DataExtractor Data(Expr, Ctx.isLittleEndian());
98 DWARFExpression DE(Data, U->getAddressByteSize(), U->getFormParams().Format);
99 printDwarfExpression(&DE, OS, DumpOpts, U);
100}
101
103 return D.getAttributeValueAsReferencedDie(F).resolveTypeUnitReference();
104}
105
106static llvm::StringRef
108 const DWARFDie &Die) {
109 if (AttrValue.Attr != DW_AT_language_version)
110 return {};
111
112 auto NameForm = Die.find(DW_AT_language_name);
113 if (!NameForm)
114 return {};
115
116 auto LName = NameForm->getAsUnsignedConstant();
117 if (!LName)
118 return {};
119
120 auto LVersion = AttrValue.Value.getAsUnsignedConstant();
121 if (!LVersion)
122 return {};
123
125 static_cast<SourceLanguageName>(*LName), *LVersion);
126}
127
130 if (!PropDIE)
131 return llvm::createStringError("invalid DIE");
132
133 if (PropDIE.getTag() != DW_TAG_APPLE_property)
134 return llvm::createStringError("not referencing a DW_TAG_APPLE_property");
135
136 auto PropNameForm = PropDIE.find(DW_AT_APPLE_property_name);
137 if (!PropNameForm)
138 return "";
139
140 auto NameOrErr = PropNameForm->getAsCString();
141 if (!NameOrErr)
142 return NameOrErr.takeError();
143
144 return *NameOrErr;
145}
146
147static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
148 const DWARFAttribute &AttrValue, unsigned Indent,
149 DIDumpOptions DumpOpts) {
150 if (!Die.isValid())
151 return;
152 const char BaseIndent[] = " ";
153 OS << BaseIndent;
154 OS.indent(Indent + 2);
155 dwarf::Attribute Attr = AttrValue.Attr;
156 WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
157
158 dwarf::Form Form = AttrValue.Value.getForm();
159 if (DumpOpts.Verbose || DumpOpts.ShowForm)
160 OS << formatv(" [{0}]", Form);
161
162 DWARFUnit *U = Die.getDwarfUnit();
163 const DWARFFormValue &FormValue = AttrValue.Value;
164
165 OS << "\t(";
166
167 StringRef Name;
168 std::string File;
169 auto Color = HighlightColor::Enumerator;
170 if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
172 if (const auto *LT = U->getContext().getLineTableForUnit(U)) {
173 if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant()) {
174 if (LT->getFileNameByIndex(
175 *Val, U->getCompilationDir(),
177 File)) {
178 File = '"' + File + '"';
179 Name = File;
180 }
181 }
182 }
183 } else if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
184 Name = AttributeValueString(Attr, *Val);
185
186 auto DumpUnsignedConstant = [&OS,
187 &DumpOpts](const DWARFFormValue &FormValue) {
188 if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
189 OS << *Val;
190 else
191 FormValue.dump(OS, DumpOpts);
192 };
193
194 llvm::StringRef PrettyVersionName =
195 prettyLanguageVersionString(AttrValue, Die);
196 bool ShouldDumpRawLanguageVersion =
197 Attr == DW_AT_language_version &&
198 (DumpOpts.Verbose || PrettyVersionName.empty());
199
200 if (!Name.empty())
201 WithColor(OS, Color) << Name;
202 else if (Attr == DW_AT_decl_line || Attr == DW_AT_decl_column ||
203 Attr == DW_AT_call_line || Attr == DW_AT_call_column) {
204 DumpUnsignedConstant(FormValue);
205 } else if (Attr == DW_AT_language_version) {
206 if (ShouldDumpRawLanguageVersion)
207 DumpUnsignedConstant(FormValue);
208 } else if (Attr == DW_AT_low_pc &&
209 (FormValue.getAsAddress() ==
210 dwarf::computeTombstoneAddress(U->getAddressByteSize()))) {
211 if (DumpOpts.Verbose) {
212 FormValue.dump(OS, DumpOpts);
213 OS << " (";
214 }
215 OS << "dead code";
216 if (DumpOpts.Verbose)
217 OS << ')';
218 } else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
219 FormValue.getAsUnsignedConstant()) {
220 if (DumpOpts.ShowAddresses) {
221 // Print the actual address rather than the offset.
222 uint64_t LowPC, HighPC, Index;
223 if (Die.getLowAndHighPC(LowPC, HighPC, Index))
224 DWARFFormValue::dumpAddress(OS, U->getAddressByteSize(), HighPC);
225 else
226 FormValue.dump(OS, DumpOpts);
227 }
228 } else if (DWARFAttribute::mayHaveLocationList(Attr) &&
230 dumpLocationList(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
231 DumpOpts);
232 else if (FormValue.isFormClass(DWARFFormValue::FC_Exprloc) ||
235 dumpLocationExpr(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
236 DumpOpts);
237 else
238 FormValue.dump(OS, DumpOpts);
239
240 std::string Space = DumpOpts.ShowAddresses ? " " : "";
241
242 // We have dumped the attribute raw value. For some attributes
243 // having both the raw value and the pretty-printed value is
244 // interesting. These attributes are handled below.
245 if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin ||
246 Attr == DW_AT_call_origin || Attr == DW_AT_import ||
247 Attr == DW_AT_LLVM_virtual_call_origin) {
248 if (const char *Name =
251 OS << Space << "\"" << Name << '\"';
252 } else if (Attr == DW_AT_property_forward) {
253 if (const char *Name =
256 OS << Space << "\"" << Name << '\"';
257 } else if (Attr == DW_AT_APPLE_property) {
258 auto PropDIE = Die.getAttributeValueAsReferencedDie(FormValue);
259 if (auto PropNameOrErr = getApplePropertyName(PropDIE))
260 OS << Space << "\"" << *PropNameOrErr << '\"';
261 else
264 llvm::formatv("decoding DW_AT_APPLE_property_name: {}",
265 toString(PropNameOrErr.takeError()))));
266 } else if (Attr == DW_AT_type || Attr == DW_AT_containing_type) {
267 DWARFDie D = resolveReferencedType(Die, FormValue);
268 if (D && !D.isNULL()) {
269 OS << Space << "\"";
271 OS << '"';
272 }
273 } else if (Attr == DW_AT_APPLE_property_attribute) {
274 if (std::optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
275 dumpApplePropertyAttribute(OS, *OptVal);
276 } else if (Attr == DW_AT_ranges) {
277 const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
278 // For DW_FORM_rnglistx we need to dump the offset separately, since
279 // we have only dumped the index so far.
280 if (FormValue.getForm() == DW_FORM_rnglistx)
281 if (auto RangeListOffset =
282 U->getRnglistOffset(*FormValue.getAsSectionOffset())) {
284 dwarf::DW_FORM_sec_offset, *RangeListOffset);
285 FV.dump(OS, DumpOpts);
286 }
287 if (auto RangesOrError = Die.getAddressRanges())
288 dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
289 sizeof(BaseIndent) + Indent + 4, DumpOpts);
290 else
292 errc::invalid_argument, "decoding address ranges: %s",
293 toString(RangesOrError.takeError()).c_str()));
294 } else if (Attr == DW_AT_language_version) {
295 if (!PrettyVersionName.empty())
296 WithColor(OS, Color) << (ShouldDumpRawLanguageVersion ? " " : "")
297 << PrettyVersionName;
298 }
299
300 OS << ")\n";
301}
302
304 std::string *OriginalFullName) const {
305 const char *NamePtr = getShortName();
306 if (!NamePtr)
307 return;
308 if (getTag() == DW_TAG_GNU_template_parameter_pack)
309 return;
310 dumpTypeUnqualifiedName(*this, OS, OriginalFullName);
311}
312
313bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
314
316 auto Tag = getTag();
317 return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
318}
319
320std::optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
321 if (!isValid())
322 return std::nullopt;
323 auto AbbrevDecl = getAbbreviationDeclarationPtr();
324 if (AbbrevDecl)
325 return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
326 return std::nullopt;
327}
328
329std::optional<DWARFFormValue>
331 if (!isValid())
332 return std::nullopt;
333 auto AbbrevDecl = getAbbreviationDeclarationPtr();
334 if (AbbrevDecl) {
335 for (auto Attr : Attrs) {
336 if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
337 return Value;
338 }
339 }
340 return std::nullopt;
341}
342
343std::optional<DWARFFormValue>
346 Worklist.push_back(*this);
347
348 // Keep track if DIEs already seen to prevent infinite recursion.
349 // Empirically we rarely see a depth of more than 3 when dealing with valid
350 // DWARF. This corresponds to following the DW_AT_abstract_origin and
351 // DW_AT_specification just once.
353 Seen.insert(*this);
354
355 while (!Worklist.empty()) {
356 DWARFDie Die = Worklist.pop_back_val();
357
358 if (!Die.isValid())
359 continue;
360
361 if (auto Value = Die.find(Attrs))
362 return Value;
363
364 for (dwarf::Attribute Attr :
365 {DW_AT_abstract_origin, DW_AT_specification, DW_AT_signature}) {
366 if (auto D = Die.getAttributeValueAsReferencedDie(Attr))
367 if (Seen.insert(D).second)
368 Worklist.push_back(D);
369 }
370 }
371
372 return std::nullopt;
373}
374
377 if (std::optional<DWARFFormValue> F = find(Attr))
379 return DWARFDie();
380}
381
384 DWARFDie Result;
385 if (std::optional<uint64_t> Offset = V.getAsRelativeReference()) {
386 Result = const_cast<DWARFUnit *>(V.getUnit())
387 ->getDIEForOffset(V.getUnit()->getOffset() + *Offset);
388 } else if (Offset = V.getAsDebugInfoReference(); Offset) {
389 if (DWARFUnit *SpecUnit = U->getUnitVector().getUnitForOffset(*Offset))
390 Result = SpecUnit->getDIEForOffset(*Offset);
391 } else if (std::optional<uint64_t> Sig = V.getAsSignatureReference()) {
392 if (DWARFTypeUnit *TU =
393 U->getContext().getTypeUnitForHash(*Sig, U->isDWOUnit()))
394 Result = TU->getDIEForOffset(TU->getTypeOffset() + TU->getOffset());
395 }
396 return Result;
397}
398
400 if (auto Attr = find(DW_AT_signature)) {
401 if (std::optional<uint64_t> Sig = Attr->getAsReferenceUVal()) {
402 if (DWARFTypeUnit *TU =
403 U->getContext().getTypeUnitForHash(*Sig, U->isDWOUnit()))
404 return TU->getDIEForOffset(TU->getTypeOffset() + TU->getOffset());
405 }
406 }
407 return *this;
408}
409
416
417std::optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
418 return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
419}
420
421std::optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
422 return toSectionOffset(find(DW_AT_loclists_base));
423}
424
425std::optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
426 uint64_t Tombstone = dwarf::computeTombstoneAddress(U->getAddressByteSize());
427 if (LowPC == Tombstone)
428 return std::nullopt;
429 if (auto FormValue = find(DW_AT_high_pc)) {
430 if (auto Address = FormValue->getAsAddress()) {
431 // High PC is an address.
432 return Address;
433 }
434 if (auto Offset = FormValue->getAsUnsignedConstant()) {
435 // High PC is an offset from LowPC.
436 return LowPC + *Offset;
437 }
438 }
439 return std::nullopt;
440}
441
442bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
443 uint64_t &SectionIndex) const {
444 auto F = find(DW_AT_low_pc);
445 auto LowPcAddr = toSectionedAddress(F);
446 if (!LowPcAddr)
447 return false;
448 if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
449 LowPC = LowPcAddr->Address;
450 HighPC = *HighPcAddr;
451 SectionIndex = LowPcAddr->SectionIndex;
452 return true;
453 }
454 return false;
455}
456
458 if (isNULL())
460 // Single range specified by low/high PC.
461 uint64_t LowPC, HighPC, Index;
462 if (getLowAndHighPC(LowPC, HighPC, Index))
463 return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
464
465 std::optional<DWARFFormValue> Value = find(DW_AT_ranges);
466 if (Value) {
467 if (Value->getForm() == DW_FORM_rnglistx)
468 return U->findRnglistFromIndex(*Value->getAsSectionOffset());
469 return U->findRnglistFromOffset(*Value->getAsSectionOffset());
470 }
472}
473
475 auto RangesOrError = getAddressRanges();
476 if (!RangesOrError) {
477 llvm::consumeError(RangesOrError.takeError());
478 return false;
479 }
480
481 for (const auto &R : RangesOrError.get())
482 if (R.LowPC <= Address && Address < R.HighPC)
483 return true;
484 return false;
485}
486
487// FIXME: should we return a structure akin to DISourceLanguageName here
488// encapsulates an unversioned (dwarf::SourceLanguage) and versioned
489// (dwarf::SourceLanguageName) language, and put the burden on the
490// user to determine which to use?
491std::optional<uint64_t> DWARFDie::getLanguage() const {
492 if (!isValid())
493 return std::nullopt;
494
495 DWARFDie Unit = U->getUnitDIE();
496
497 if (std::optional<DWARFFormValue> LV = Unit.find(dwarf::DW_AT_language))
498 return LV->getAsUnsignedConstant();
499
500 uint16_t Name =
501 dwarf::toUnsigned(Unit.find(dwarf::DW_AT_language_name), /*Default=*/0);
502 uint32_t Version = dwarf::toUnsigned(Unit.find(dwarf::DW_AT_language_version),
503 /*Default=*/0);
504
505 return llvm::dwarf::toDW_LANG(static_cast<SourceLanguageName>(Name), Version);
506}
507
510 std::optional<DWARFFormValue> Location = find(Attr);
511 if (!Location)
514
515 if (std::optional<uint64_t> Off = Location->getAsSectionOffset()) {
516 uint64_t Offset = *Off;
517
518 if (Location->getForm() == DW_FORM_loclistx) {
519 if (auto LoclistOffset = U->getLoclistOffset(Offset))
520 Offset = *LoclistOffset;
521 else
523 "Loclist table not found");
524 }
525 return U->findLoclistFromOffset(Offset);
526 }
527
528 if (std::optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
530 DWARFLocationExpression{std::nullopt, to_vector<4>(*Expr)}};
531 }
532
533 return createStringError(
534 inconvertibleErrorCode(), "Unsupported %s encoding: %s",
536 dwarf::FormEncodingString(Location->getForm()).data());
537}
538
540 if (!isSubroutineDIE())
541 return nullptr;
542 return getName(Kind);
543}
544
546 if (!isValid() || Kind == DINameKind::None)
547 return nullptr;
548 // Try to get mangled name only if it was asked for.
550 if (auto Name = getLinkageName())
551 return Name;
552 }
553 return getShortName();
554}
555
556const char *DWARFDie::getShortName() const {
557 if (!isValid())
558 return nullptr;
559
560 return dwarf::toString(findRecursively(dwarf::DW_AT_name), nullptr);
561}
562
563const char *DWARFDie::getLinkageName() const {
564 if (!isValid())
565 return nullptr;
566
567 return dwarf::toString(findRecursively({dwarf::DW_AT_MIPS_linkage_name,
568 dwarf::DW_AT_linkage_name}),
569 nullptr);
570}
571
572uint64_t DWARFDie::getDeclLine() const {
573 return toUnsigned(findRecursively(DW_AT_decl_line), 0);
574}
575
576std::string
578 if (auto FormValue = findRecursively(DW_AT_decl_file))
579 if (auto OptString = FormValue->getAsFile(Kind))
580 return *OptString;
581 return {};
582}
583
585 uint32_t &CallColumn,
586 uint32_t &CallDiscriminator) const {
587 CallFile = toUnsigned(find(DW_AT_call_file), 0);
588 CallLine = toUnsigned(find(DW_AT_call_line), 0);
589 CallColumn = toUnsigned(find(DW_AT_call_column), 0);
590 CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
591}
592
593static std::optional<uint64_t>
596 // Cycle detected?
597 if (!Visited.insert(Die.getDebugInfoEntry()).second)
598 return {};
599 if (auto SizeAttr = Die.find(DW_AT_byte_size))
600 if (std::optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
601 return Size;
602
603 switch (Die.getTag()) {
604 case DW_TAG_pointer_type:
605 case DW_TAG_reference_type:
606 case DW_TAG_rvalue_reference_type:
607 return PointerSize;
608 case DW_TAG_ptr_to_member_type: {
610 if (BaseType.getTag() == DW_TAG_subroutine_type)
611 return 2 * PointerSize;
612 return PointerSize;
613 }
614 case DW_TAG_const_type:
615 case DW_TAG_immutable_type:
616 case DW_TAG_volatile_type:
617 case DW_TAG_restrict_type:
618 case DW_TAG_template_alias:
619 case DW_TAG_typedef: {
621 return getTypeSizeImpl(BaseType, PointerSize, Visited);
622 break;
623 }
624 case DW_TAG_array_type: {
626 if (!BaseType)
627 return std::nullopt;
628 std::optional<uint64_t> BaseSize =
629 getTypeSizeImpl(BaseType, PointerSize, Visited);
630 if (!BaseSize)
631 return std::nullopt;
632 uint64_t Size = *BaseSize;
633 for (DWARFDie Child : Die) {
634 if (Child.getTag() != DW_TAG_subrange_type)
635 continue;
636
637 if (auto ElemCountAttr = Child.find(DW_AT_count))
638 if (std::optional<uint64_t> ElemCount =
639 ElemCountAttr->getAsUnsignedConstant())
640 Size *= *ElemCount;
641 if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
642 if (std::optional<int64_t> UpperBound =
643 UpperBoundAttr->getAsSignedConstant()) {
644 int64_t LowerBound = 0;
645 if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
646 LowerBound = LowerBoundAttr->getAsSignedConstant().value_or(0);
647 Size *= *UpperBound - LowerBound + 1;
648 }
649 }
650 return Size;
651 }
652 default:
654 return getTypeSizeImpl(BaseType, PointerSize, Visited);
655 break;
656 }
657 return std::nullopt;
658}
659
660std::optional<uint64_t> DWARFDie::getTypeSize(uint64_t PointerSize) {
662 return getTypeSizeImpl(*this, PointerSize, Visited);
663}
664
665/// Helper to dump a DIE with all of its parents, but no siblings.
666static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
667 DIDumpOptions DumpOpts, unsigned Depth = 0) {
668 if (!Die)
669 return Indent;
670 if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
671 return Indent;
672 Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts, Depth + 1);
673 Die.dump(OS, Indent, DumpOpts);
674 return Indent + 2;
675}
676
677void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
678 DIDumpOptions DumpOpts) const {
679 if (!isValid())
680 return;
681 DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
682 const uint64_t Offset = getOffset();
683 uint64_t offset = Offset;
684 if (DumpOpts.ShowParents) {
685 DIDumpOptions ParentDumpOpts = DumpOpts;
686 ParentDumpOpts.ShowParents = false;
687 ParentDumpOpts.ShowChildren = false;
688 Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
689 }
690
691 if (debug_info_data.isValidOffset(offset)) {
692 uint32_t abbrCode = debug_info_data.getULEB128(&offset);
693 if (DumpOpts.ShowAddresses)
695 << formatv("\n{0:x8}: ", Offset);
696
697 if (abbrCode) {
698 auto AbbrevDecl = getAbbreviationDeclarationPtr();
699 if (AbbrevDecl) {
701 << formatv("{0}", getTag());
702 if (DumpOpts.Verbose) {
703 OS << formatv(" [{0}] {1}", abbrCode,
704 AbbrevDecl->hasChildren() ? '*' : ' ');
705 if (std::optional<uint32_t> ParentIdx = Die->getParentIdx())
706 OS << formatv(" ({0:x8})",
707 U->getDIEAtIndex(*ParentIdx).getOffset());
708 }
709 OS << '\n';
710
711 // Dump all data in the DIE for the attributes.
712 for (const DWARFAttribute &AttrValue : attributes())
713 dumpAttribute(OS, *this, AttrValue, Indent, DumpOpts);
714
715 if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0) {
716 DWARFDie Child = getFirstChild();
717 DumpOpts.ChildRecurseDepth--;
718 DIDumpOptions ChildDumpOpts = DumpOpts;
719 ChildDumpOpts.ShowParents = false;
720 while (Child) {
721 if (DumpOpts.FilterChildTag.empty() ||
722 llvm::is_contained(DumpOpts.FilterChildTag, Child.getTag()))
723 Child.dump(OS, Indent + 2, ChildDumpOpts);
724 Child = Child.getSibling();
725 }
726 }
727 } else {
728 OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
729 << abbrCode << '\n';
730 }
731 } else {
732 OS.indent(Indent) << "NULL\n";
733 }
734 }
735}
736
738
740 if (isValid())
741 return U->getParent(Die);
742 return DWARFDie();
743}
744
746 if (isValid())
747 return U->getSibling(Die);
748 return DWARFDie();
749}
750
752 if (isValid())
753 return U->getPreviousSibling(Die);
754 return DWARFDie();
755}
756
758 if (isValid())
759 return U->getFirstChild(Die);
760 return DWARFDie();
761}
762
764 if (isValid())
765 return U->getLastChild(Die);
766 return DWARFDie();
767}
768
773
775 : Die(D), Index(0) {
776 auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
777 assert(AbbrDecl && "Must have abbreviation declaration");
778 if (End) {
779 // This is the end iterator so we set the index to the attribute count.
780 Index = AbbrDecl->getNumAttributes();
781 } else {
782 // This is the begin iterator so we extract the value for this->Index.
783 AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
784 updateForIndex(*AbbrDecl, 0);
785 }
786}
787
788void DWARFDie::attribute_iterator::updateForIndex(
789 const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
790 Index = I;
791 // AbbrDecl must be valid before calling this function.
792 auto NumAttrs = AbbrDecl.getNumAttributes();
793 if (Index < NumAttrs) {
794 AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
795 // Add the previous byte size of any previous attribute value.
796 AttrValue.Offset += AttrValue.ByteSize;
797 uint64_t ParseOffset = AttrValue.Offset;
799 AttrValue.Value = DWARFFormValue::createFromSValue(
800 AbbrDecl.getFormByIndex(Index),
802 else {
803 auto U = Die.getDwarfUnit();
804 assert(U && "Die must have valid DWARF unit");
805 AttrValue.Value = DWARFFormValue::createFromUnit(
806 AbbrDecl.getFormByIndex(Index), U, &ParseOffset);
807 }
808 AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
809 } else {
810 assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
811 AttrValue = {};
812 }
813}
814
816 if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
817 updateForIndex(*AbbrDecl, Index + 1);
818 return *this;
819}
820
822 switch(Attr) {
823 case DW_AT_location:
824 case DW_AT_string_length:
825 case DW_AT_return_addr:
826 case DW_AT_data_member_location:
827 case DW_AT_frame_base:
828 case DW_AT_static_link:
829 case DW_AT_segment:
830 case DW_AT_use_location:
831 case DW_AT_vtable_elem_location:
832 return true;
833 default:
834 return false;
835 }
836}
837
839 switch (Attr) {
840 // From the DWARF v5 specification.
841 case DW_AT_location:
842 case DW_AT_byte_size:
843 case DW_AT_bit_offset:
844 case DW_AT_bit_size:
845 case DW_AT_string_length:
846 case DW_AT_lower_bound:
847 case DW_AT_return_addr:
848 case DW_AT_bit_stride:
849 case DW_AT_upper_bound:
850 case DW_AT_count:
851 case DW_AT_data_member_location:
852 case DW_AT_frame_base:
853 case DW_AT_segment:
854 case DW_AT_static_link:
855 case DW_AT_use_location:
856 case DW_AT_vtable_elem_location:
857 case DW_AT_allocated:
858 case DW_AT_associated:
859 case DW_AT_data_location:
860 case DW_AT_byte_stride:
861 case DW_AT_rank:
862 case DW_AT_call_value:
863 case DW_AT_call_origin:
864 case DW_AT_call_target:
865 case DW_AT_call_target_clobbered:
866 case DW_AT_call_data_location:
867 case DW_AT_call_data_value:
868 // Extensions.
869 case DW_AT_GNU_call_site_value:
870 case DW_AT_GNU_call_site_target:
871 case DW_AT_GNU_call_site_target_clobbered:
872 return true;
873 default:
874 return false;
875 }
876}
877
878namespace llvm {
879
883
885 std::string *OriginalFullName) {
887}
888
889} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die, const DWARFAttribute &AttrValue, unsigned Indent, DIDumpOptions DumpOpts)
Definition DWARFDie.cpp:147
static void dumpLocationExpr(raw_ostream &OS, const DWARFFormValue &FormValue, DWARFUnit *U, unsigned Indent, DIDumpOptions DumpOpts)
Definition DWARFDie.cpp:89
static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent, DIDumpOptions DumpOpts, unsigned Depth=0)
Helper to dump a DIE with all of its parents, but no siblings.
Definition DWARFDie.cpp:666
static DWARFDie resolveReferencedType(DWARFDie D, DWARFFormValue F)
Definition DWARFDie.cpp:102
static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue, DWARFUnit *U, unsigned Indent, DIDumpOptions DumpOpts)
Definition DWARFDie.cpp:69
static llvm::StringRef prettyLanguageVersionString(const DWARFAttribute &AttrValue, const DWARFDie &Die)
Definition DWARFDie.cpp:107
static llvm::Expected< llvm::StringRef > getApplePropertyName(const DWARFDie &PropDIE)
Definition DWARFDie.cpp:129
static std::optional< uint64_t > getTypeSizeImpl(DWARFDie Die, uint64_t PointerSize, SmallPtrSetImpl< const DWARFDebugInfoEntry * > &Visited)
Definition DWARFDie.cpp:594
static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val)
Definition DWARFDie.cpp:37
static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS, const DWARFAddressRangesVector &Ranges, unsigned AddressSize, unsigned Indent, const DIDumpOptions &DumpOpts)
Definition DWARFDie.cpp:55
This file contains constants used for implementing Dwarf debug support.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
static Split data
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A structured debug information entry.
Definition DIE.h:842
dwarf::Attribute getAttrByIndex(uint32_t idx) const
int64_t getAttrImplicitConstValueByIndex(uint32_t idx) const
dwarf::Form getFormByIndex(uint32_t idx) const
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
DWARFTypeUnit * getTypeUnitForHash(uint64_t Hash, bool IsDWO)
const DWARFObject & getDWARFObj() const
A DWARFDataExtractor (typically for an in-memory copy of an object-file section) plus a relocation ma...
LLVM_ABI attribute_iterator & operator++()
Definition DWARFDie.cpp:815
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
LLVM_ABI void getFullName(raw_string_ostream &, std::string *OriginalFullName=nullptr) const
Definition DWARFDie.cpp:303
LLVM_ABI DWARFDie resolveTypeUnitReference() const
Definition DWARFDie.cpp:399
LLVM_ABI std::optional< uint64_t > getLocBaseAttribute() const
Definition DWARFDie.cpp:421
uint64_t getOffset() const
Get the absolute offset into the debug info or types section.
Definition DWARFDie.h:68
LLVM_ABI const char * getShortName() const
Return the DIE short name resolving DW_AT_specification or DW_AT_abstract_origin references if necess...
Definition DWARFDie.cpp:556
LLVM_ABI Expected< DWARFAddressRangesVector > getAddressRanges() const
Get the address ranges for this DIE.
Definition DWARFDie.cpp:457
LLVM_ABI DWARFDie getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE as the referenced DIE.
Definition DWARFDie.cpp:376
LLVM_ABI DWARFDie getParent() const
Get the parent of this DIE object.
Definition DWARFDie.cpp:739
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition DWARFDie.cpp:320
DWARFUnit * getDwarfUnit() const
Definition DWARFDie.h:55
const DWARFDebugInfoEntry * getDebugInfoEntry() const
Definition DWARFDie.h:54
LLVM_ABI const char * getSubroutineName(DINameKind Kind) const
If a DIE represents a subprogram (or inlined subroutine), returns its mangled name (or short name,...
Definition DWARFDie.cpp:539
LLVM_ABI DWARFDie getSibling() const
Get the sibling of this DIE object.
Definition DWARFDie.cpp:745
LLVM_ABI bool isSubroutineDIE() const
Returns true if DIE represents a subprogram or an inlined subroutine.
Definition DWARFDie.cpp:315
LLVM_ABI bool getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC, uint64_t &SectionIndex) const
Retrieves DW_AT_low_pc and DW_AT_high_pc from CU.
Definition DWARFDie.cpp:442
LLVM_ABI LLVM_DUMP_METHOD void dump() const
Convenience zero-argument overload for debugging.
Definition DWARFDie.cpp:737
LLVM_ABI void getCallerFrame(uint32_t &CallFile, uint32_t &CallLine, uint32_t &CallColumn, uint32_t &CallDiscriminator) const
Retrieves values of DW_AT_call_file, DW_AT_call_line and DW_AT_call_column from DIE (or zeroes if the...
Definition DWARFDie.cpp:584
LLVM_ABI bool isSubprogramDIE() const
Returns true if DIE represents a subprogram (not inlined).
Definition DWARFDie.cpp:313
LLVM_ABI bool addressRangeContainsAddress(const uint64_t Address) const
Definition DWARFDie.cpp:474
LLVM_ABI std::optional< DWARFFormValue > findRecursively(ArrayRef< dwarf::Attribute > Attrs) const
Extract the first value of any attribute in Attrs from this DIE and recurse into any DW_AT_specificat...
Definition DWARFDie.cpp:344
llvm::DWARFFormValue DWARFFormValue
Definition DWARFDie.h:48
LLVM_ABI std::optional< uint64_t > getHighPC(uint64_t LowPC) const
Get the DW_AT_high_pc attribute value as an address.
Definition DWARFDie.cpp:425
LLVM_ABI std::optional< uint64_t > getTypeSize(uint64_t PointerSize)
Gets the type size (in bytes) for this DIE.
Definition DWARFDie.cpp:660
LLVM_ABI DWARFDie resolveReferencedType(dwarf::Attribute Attr) const
Definition DWARFDie.cpp:410
LLVM_ABI const char * getName(DINameKind Kind) const
Return the DIE name resolving DW_AT_specification or DW_AT_abstract_origin references if necessary.
Definition DWARFDie.cpp:545
LLVM_ABI DWARFDie getLastChild() const
Get the last child of this DIE object.
Definition DWARFDie.cpp:763
LLVM_ABI DWARFDie getPreviousSibling() const
Get the previous sibling of this DIE object.
Definition DWARFDie.cpp:751
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Get the abbreviation declaration for this DIE.
Definition DWARFDie.h:60
DWARFDie()=default
LLVM_ABI std::string getDeclFile(DILineInfoSpecifier::FileLineInfoKind Kind) const
Definition DWARFDie.cpp:577
LLVM_ABI DWARFDie getFirstChild() const
Get the first child of this DIE object.
Definition DWARFDie.cpp:757
LLVM_ABI uint64_t getDeclLine() const
Returns the declaration line (start line) for a DIE, assuming it specifies a subprogram.
Definition DWARFDie.cpp:572
dwarf::Tag getTag() const
Definition DWARFDie.h:73
LLVM_ABI const char * getLinkageName() const
Return the DIE linkage name resolving DW_AT_specification or DW_AT_abstract_origin references if nece...
Definition DWARFDie.cpp:563
LLVM_ABI Expected< DWARFLocationExpressionsVector > getLocations(dwarf::Attribute Attr) const
Definition DWARFDie.cpp:509
LLVM_ABI std::optional< uint64_t > getRangesBaseAttribute() const
Extract the range base attribute from this DIE as absolute section offset.
Definition DWARFDie.cpp:417
bool isNULL() const
Returns true for a valid DIE that terminates a sibling chain.
Definition DWARFDie.h:86
LLVM_ABI std::optional< uint64_t > getLanguage() const
Returns the DW_LANG_ code for this DIE's DWARF unit, if it exists.
Definition DWARFDie.cpp:491
bool isValid() const
Definition DWARFDie.h:52
LLVM_ABI iterator_range< attribute_iterator > attributes() const
Get an iterator range to all attributes in the current DIE only.
Definition DWARFDie.cpp:769
LLVM_ABI void dump(raw_ostream &OS, unsigned indent=0, DIDumpOptions DumpOpts=DIDumpOptions()) const
Dump the DIE and all of its attributes to the supplied stream.
Definition DWARFDie.cpp:677
static LLVM_ABI DWARFFormValue createFromUValue(dwarf::Form F, uint64_t V)
LLVM_ABI std::optional< ArrayRef< uint8_t > > getAsBlock() const
LLVM_ABI std::optional< uint64_t > getAsSectionOffset() const
LLVM_ABI bool isFormClass(FormClass FC) const
LLVM_ABI void dumpAddress(raw_ostream &OS, uint64_t Address) const
LLVM_ABI std::optional< uint64_t > getAsAddress() const
LLVM_ABI void dump(raw_ostream &OS, DIDumpOptions DumpOpts=DIDumpOptions()) const
static LLVM_ABI DWARFFormValue createFromSValue(dwarf::Form F, int64_t V)
LLVM_ABI std::optional< uint64_t > getAsUnsignedConstant() const
static LLVM_ABI DWARFFormValue createFromUnit(dwarf::Form F, const DWARFUnit *Unit, uint64_t *OffsetPtr)
dwarf::Form getForm() const
LLVM_ABI DWARFUnit * getUnitForOffset(uint64_t Offset) const
DWARFContext & getContext() const
Definition DWARFUnit.h:326
DWARFDie getDIEForOffset(uint64_t Offset)
Return the DIE object for a given offset Offset inside the unit's DIE vector.
Definition DWARFUnit.h:550
const DWARFUnitVector & getUnitVector() const
Return the DWARFUnitVector containing this unit.
Definition DWARFUnit.h:518
LLVM_ABI uint64_t getULEB128(uint64_t *offset_ptr, llvm::Error *Err=nullptr) const
Extract a unsigned LEB128 value from *offset_ptr.
bool isValidOffset(uint64_t offset) const
Test the validity of offset.
Tagged union holding either a T or a Error.
Definition Error.h:485
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
LLVM Value Representation.
Definition Value.h:75
An RAII object that temporarily switches an output stream to a specific color.
Definition WithColor.h:54
raw_ostream & get()
Definition WithColor.h:81
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
LLVM_ABI StringRef AttributeString(unsigned Attribute)
Definition Dwarf.cpp:72
LLVM_ABI StringRef FormEncodingString(unsigned Encoding)
Definition Dwarf.cpp:105
LLVM_ABI StringRef ApplePropertyString(unsigned)
Definition Dwarf.cpp:830
Calculates the starting offsets for various sections within the .debug_names section.
Definition Dwarf.h:35
Attribute
Attributes.
Definition Dwarf.h:125
SourceLanguageName
Definition Dwarf.h:229
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
std::optional< object::SectionedAddress > toSectionedAddress(const std::optional< DWARFFormValue > &V)
std::optional< SourceLanguage > toDW_LANG(SourceLanguageName name, uint32_t version)
Convert a DWARF 6 pair of language name and version to a DWARF 5 DW_LANG.
Definition Dwarf.h:237
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
LLVM_ABI StringRef AttributeValueString(uint16_t Attr, unsigned Val)
Returns the symbolic string representing Val when used as a value for attribute Attr.
Definition Dwarf.cpp:904
uint64_t computeTombstoneAddress(uint8_t AddressByteSize)
Definition Dwarf.h:1331
LLVM_ABI llvm::StringRef LanguageDescription(SourceLanguageName name)
Returns a version-independent language name.
Definition Dwarf.cpp:466
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LLVM_ABI void printDwarfExpression(const DWARFExpression *E, raw_ostream &OS, DIDumpOptions DumpOpts, DWARFUnit *U, bool IsEH=false)
Print a Dwarf expression/.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
@ invalid_argument
Definition Errc.h:56
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void dumpTypeQualifiedName(const DWARFDie &DIE, raw_ostream &OS)
Definition DWARFDie.cpp:880
DINameKind
A DINameKind is passed to name search methods to specify a preference regarding the type of name reso...
Definition DIContext.h:142
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI void dumpTypeUnqualifiedName(const DWARFDie &DIE, raw_ostream &OS, std::string *OriginalFullName=nullptr)
Definition DWARFDie.cpp:884
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
std::vector< DWARFAddressRange > DWARFAddressRangesVector
DWARFAddressRangesVector - represents a set of absolute address ranges.
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
Container for dump options that control which debug information will be dumped.
Definition DIContext.h:196
std::function< void(Error)> RecoverableErrorHandler
Definition DIContext.h:237
llvm::SmallVector< unsigned, 0 > FilterChildTag
List of DWARF tags to filter children by.
Definition DIContext.h:215
unsigned ChildRecurseDepth
Definition DIContext.h:198
unsigned ParentRecurseDepth
Definition DIContext.h:199
Encapsulates a DWARF attribute value and all of the data required to describe the attribute value.
static LLVM_ABI bool mayHaveLocationList(dwarf::Attribute Attr)
Identify DWARF attributes that may contain a pointer to a location list.
Definition DWARFDie.cpp:821
DWARFFormValue Value
The form and value for this attribute.
static LLVM_ABI bool mayHaveLocationExpr(dwarf::Attribute Attr)
Identifies DWARF attributes that may contain a reference to a DWARF expression.
Definition DWARFDie.cpp:838
dwarf::Attribute Attr
The attribute enumeration of this attribute.
Represents a single DWARF expression, whose value is location-dependent.
void appendQualifiedName(DieType D)
void appendUnqualifiedName(DieType D, std::string *OriginalFullName=nullptr)
Recursively append the DIE type name when applicable.