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/SmallPtrSet.h"
11#include "llvm/ADT/SmallSet.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/BinaryFormat/Dwarf.h"
14#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
15#include "llvm/DebugInfo/DWARF/DWARFContext.h"
16#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
17#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
18#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
19#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20#include "llvm/DebugInfo/DWARF/DWARFTypePrinter.h"
21#include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
22#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
23#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
24#include "llvm/Object/ObjectFile.h"
25#include "llvm/Support/DataExtractor.h"
26#include "llvm/Support/FormatVariadic.h"
27#include "llvm/Support/WithColor.h"
28#include "llvm/Support/raw_ostream.h"
29#include <cassert>
30#include <cstdint>
31#include <string>
32
33using namespace llvm;
34using namespace dwarf;
35using namespace object;
36
37static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
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(Fmt: "DW_APPLE_PROPERTY_{0:x}", Vals&: 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(NumSpaces: Indent);
65 R.dump(OS, AddressSize, DumpOpts, Obj: &Obj);
66 }
67}
68
69static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue,
70 DWARFUnit *U, unsigned Indent,
71 DIDumpOptions DumpOpts) {
72 assert(FormValue.isFormClass(DWARFFormValue::FC_SectionOffset) &&
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(Index: Offset))
81 Offset = *LoclistOffset;
82 else
83 return;
84 }
85 U->getLocationTable().dumpLocationList(
86 Offset: &Offset, OS, BaseAddr: U->getBaseAddress(), Obj: Ctx.getDWARFObj(), U, DumpOpts, Indent);
87}
88
89static void dumpLocationExpr(raw_ostream &OS, const DWARFFormValue &FormValue,
90 DWARFUnit *U, unsigned Indent,
91 DIDumpOptions DumpOpts) {
92 assert((FormValue.isFormClass(DWARFFormValue::FC_Block) ||
93 FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) &&
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(E: &DE, OS, DumpOpts, U);
100}
101
102static DWARFDie resolveReferencedType(DWARFDie D, DWARFFormValue F) {
103 return D.getAttributeValueAsReferencedDie(V: F).resolveTypeUnitReference();
104}
105
106static llvm::StringRef
107prettyLanguageVersionString(const DWARFAttribute &AttrValue,
108 const DWARFDie &Die) {
109 if (AttrValue.Attr != DW_AT_language_version)
110 return {};
111
112 auto NameForm = Die.find(Attr: 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
124 return llvm::dwarf::LanguageDescription(
125 Name: static_cast<SourceLanguageName>(*LName), Version: *LVersion);
126}
127
128static llvm::Expected<llvm::StringRef>
129getApplePropertyName(const DWARFDie &PropDIE) {
130 if (!PropDIE)
131 return llvm::createStringError(Fmt: "invalid DIE");
132
133 if (PropDIE.getTag() != DW_TAG_APPLE_property)
134 return llvm::createStringError(Fmt: "not referencing a DW_TAG_APPLE_property");
135
136 auto PropNameForm = PropDIE.find(Attr: 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(NumSpaces: Indent + 2);
155 dwarf::Attribute Attr = AttrValue.Attr;
156 WithColor(OS, HighlightColor::Attribute) << formatv(Fmt: "{0}", Vals&: Attr);
157
158 dwarf::Form Form = AttrValue.Value.getForm();
159 if (DumpOpts.Verbose || DumpOpts.ShowForm)
160 OS << formatv(Fmt: " [{0}]", Vals&: 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) {
171 Color = HighlightColor::String;
172 if (const auto *LT = U->getContext().getLineTableForUnit(U)) {
173 if (std::optional<uint64_t> Val = FormValue.getAsUnsignedConstant()) {
174 if (LT->getFileNameByIndex(
175 FileIndex: *Val, CompDir: U->getCompilationDir(),
176 Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
177 Result&: 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: *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(AddressByteSize: 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, SectionIndex&: Index))
224 DWARFFormValue::dumpAddress(OS, AddressSize: U->getAddressByteSize(), Address: HighPC);
225 else
226 FormValue.dump(OS, DumpOpts);
227 }
228 } else if (DWARFAttribute::mayHaveLocationList(Attr) &&
229 FormValue.isFormClass(FC: DWARFFormValue::FC_SectionOffset))
230 dumpLocationList(OS, FormValue, U, Indent: sizeof(BaseIndent) + Indent + 4,
231 DumpOpts);
232 else if (FormValue.isFormClass(FC: DWARFFormValue::FC_Exprloc) ||
233 (DWARFAttribute::mayHaveLocationExpr(Attr) &&
234 FormValue.isFormClass(FC: DWARFFormValue::FC_Block)))
235 dumpLocationExpr(OS, FormValue, U, Indent: 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 =
249 Die.getAttributeValueAsReferencedDie(V: FormValue).getName(
250 Kind: DINameKind::LinkageName))
251 OS << Space << "\"" << Name << '\"';
252 } else if (Attr == DW_AT_property_forward) {
253 if (const char *Name =
254 Die.getAttributeValueAsReferencedDie(V: FormValue).getName(
255 Kind: DINameKind::ShortName))
256 OS << Space << "\"" << Name << '\"';
257 } else if (Attr == DW_AT_APPLE_property) {
258 auto PropDIE = Die.getAttributeValueAsReferencedDie(V: FormValue);
259 if (auto PropNameOrErr = getApplePropertyName(PropDIE))
260 OS << Space << "\"" << *PropNameOrErr << '\"';
261 else
262 DumpOpts.RecoverableErrorHandler(createStringError(
263 EC: errc::invalid_argument,
264 S: llvm::formatv(Fmt: "decoding DW_AT_APPLE_property_name: {}",
265 Vals: toString(E: PropNameOrErr.takeError()))));
266 } else if (Attr == DW_AT_type || Attr == DW_AT_containing_type) {
267 DWARFDie D = resolveReferencedType(D: Die, F: FormValue);
268 if (D && !D.isNULL()) {
269 OS << Space << "\"";
270 dumpTypeQualifiedName(DIE: D, OS);
271 OS << '"';
272 }
273 } else if (Attr == DW_AT_APPLE_property_attribute) {
274 if (std::optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
275 dumpApplePropertyAttribute(OS, Val: *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(Index: *FormValue.getAsSectionOffset())) {
283 DWARFFormValue FV = DWARFFormValue::createFromUValue(
284 F: dwarf::DW_FORM_sec_offset, V: *RangeListOffset);
285 FV.dump(OS, DumpOpts);
286 }
287 if (auto RangesOrError = Die.getAddressRanges())
288 dumpRanges(Obj, OS, Ranges: RangesOrError.get(), AddressSize: U->getAddressByteSize(),
289 Indent: sizeof(BaseIndent) + Indent + 4, DumpOpts);
290 else
291 DumpOpts.RecoverableErrorHandler(createStringError(
292 EC: errc::invalid_argument, Fmt: "decoding address ranges: %s",
293 Vals: toString(E: 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
303void DWARFDie::getFullName(raw_string_ostream &OS,
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(DIE: *this, OS, OriginalFullName);
311}
312
313bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
314
315bool DWARFDie::isSubroutineDIE() const {
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(DIEOffset: getOffset(), Attr, U: *U);
326 return std::nullopt;
327}
328
329std::optional<DWARFFormValue>
330DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
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(DIEOffset: getOffset(), Attr, U: *U))
337 return Value;
338 }
339 }
340 return std::nullopt;
341}
342
343std::optional<DWARFFormValue>
344DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
345 SmallVector<DWARFDie, 3> Worklist;
346 Worklist.push_back(Elt: *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.
352 SmallSet<DWARFDie, 3> Seen;
353 Seen.insert(V: *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(V: D).second)
368 Worklist.push_back(Elt: D);
369 }
370 }
371
372 return std::nullopt;
373}
374
375DWARFDie
376DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
377 if (std::optional<DWARFFormValue> F = find(Attr))
378 return getAttributeValueAsReferencedDie(V: *F);
379 return DWARFDie();
380}
381
382DWARFDie
383DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
384 DWARFDie Result;
385 if (std::optional<uint64_t> Offset = V.getAsRelativeReference()) {
386 Result = const_cast<DWARFUnit *>(V.getUnit())
387 ->getDIEForOffset(Offset: V.getUnit()->getOffset() + *Offset);
388 } else if (Offset = V.getAsDebugInfoReference(); Offset) {
389 if (DWARFUnit *SpecUnit = U->getUnitVector().getUnitForOffset(Offset: *Offset))
390 Result = SpecUnit->getDIEForOffset(Offset: *Offset);
391 } else if (std::optional<uint64_t> Sig = V.getAsSignatureReference()) {
392 if (DWARFTypeUnit *TU =
393 U->getContext().getTypeUnitForHash(Hash: *Sig, IsDWO: U->isDWOUnit()))
394 Result = TU->getDIEForOffset(Offset: TU->getTypeOffset() + TU->getOffset());
395 }
396 return Result;
397}
398
399DWARFDie DWARFDie::resolveTypeUnitReference() const {
400 if (auto Attr = find(Attr: DW_AT_signature)) {
401 if (std::optional<uint64_t> Sig = Attr->getAsReferenceUVal()) {
402 if (DWARFTypeUnit *TU =
403 U->getContext().getTypeUnitForHash(Hash: *Sig, IsDWO: U->isDWOUnit()))
404 return TU->getDIEForOffset(Offset: TU->getTypeOffset() + TU->getOffset());
405 }
406 }
407 return *this;
408}
409
410DWARFDie DWARFDie::resolveReferencedType(dwarf::Attribute Attr) const {
411 return getAttributeValueAsReferencedDie(Attr).resolveTypeUnitReference();
412}
413DWARFDie DWARFDie::resolveReferencedType(const DWARFFormValue &V) const {
414 return getAttributeValueAsReferencedDie(V).resolveTypeUnitReference();
415}
416
417std::optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
418 return toSectionOffset(V: find(Attrs: {DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
419}
420
421std::optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
422 return toSectionOffset(V: find(Attr: DW_AT_loclists_base));
423}
424
425std::optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
426 uint64_t Tombstone = dwarf::computeTombstoneAddress(AddressByteSize: U->getAddressByteSize());
427 if (LowPC == Tombstone)
428 return std::nullopt;
429 if (auto FormValue = find(Attr: 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(Attr: DW_AT_low_pc);
445 auto LowPcAddr = toSectionedAddress(V: F);
446 if (!LowPcAddr)
447 return false;
448 if (auto HighPcAddr = getHighPC(LowPC: LowPcAddr->Address)) {
449 LowPC = LowPcAddr->Address;
450 HighPC = *HighPcAddr;
451 SectionIndex = LowPcAddr->SectionIndex;
452 return true;
453 }
454 return false;
455}
456
457Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
458 if (isNULL())
459 return DWARFAddressRangesVector();
460 // Single range specified by low/high PC.
461 uint64_t LowPC, HighPC, Index;
462 if (getLowAndHighPC(LowPC, HighPC, SectionIndex&: Index))
463 return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
464
465 std::optional<DWARFFormValue> Value = find(Attr: DW_AT_ranges);
466 if (Value) {
467 if (Value->getForm() == DW_FORM_rnglistx)
468 return U->findRnglistFromIndex(Index: *Value->getAsSectionOffset());
469 return U->findRnglistFromOffset(Offset: *Value->getAsSectionOffset());
470 }
471 return DWARFAddressRangesVector();
472}
473
474bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
475 auto RangesOrError = getAddressRanges();
476 if (!RangesOrError) {
477 llvm::consumeError(Err: 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(Attr: dwarf::DW_AT_language))
498 return LV->getAsUnsignedConstant();
499
500 uint16_t Name =
501 dwarf::toUnsigned(V: Unit.find(Attr: dwarf::DW_AT_language_name), /*Default=*/0);
502 uint32_t Version = dwarf::toUnsigned(V: Unit.find(Attr: dwarf::DW_AT_language_version),
503 /*Default=*/0);
504
505 return llvm::dwarf::toDW_LANG(name: static_cast<SourceLanguageName>(Name), version: Version);
506}
507
508Expected<DWARFLocationExpressionsVector>
509DWARFDie::getLocations(dwarf::Attribute Attr) const {
510 std::optional<DWARFFormValue> Location = find(Attr);
511 if (!Location)
512 return createStringError(EC: inconvertibleErrorCode(), Fmt: "No %s",
513 Vals: dwarf::AttributeString(Attribute: Attr).data());
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(Index: Offset))
520 Offset = *LoclistOffset;
521 else
522 return createStringError(EC: inconvertibleErrorCode(),
523 S: "Loclist table not found");
524 }
525 return U->findLoclistFromOffset(Offset);
526 }
527
528 if (std::optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
529 return DWARFLocationExpressionsVector{
530 DWARFLocationExpression{.Range: std::nullopt, .Expr: to_vector<4>(Range&: *Expr)}};
531 }
532
533 return createStringError(
534 EC: inconvertibleErrorCode(), Fmt: "Unsupported %s encoding: %s",
535 Vals: dwarf::AttributeString(Attribute: Attr).data(),
536 Vals: dwarf::FormEncodingString(Encoding: Location->getForm()).data());
537}
538
539const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
540 if (!isSubroutineDIE())
541 return nullptr;
542 return getName(Kind);
543}
544
545const char *DWARFDie::getName(DINameKind Kind) const {
546 if (!isValid() || Kind == DINameKind::None)
547 return nullptr;
548 // Try to get mangled name only if it was asked for.
549 if (Kind == DINameKind::LinkageName) {
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(V: findRecursively(Attrs: dwarf::DW_AT_name), Default: nullptr);
561}
562
563const char *DWARFDie::getLinkageName() const {
564 if (!isValid())
565 return nullptr;
566
567 return dwarf::toString(V: findRecursively(Attrs: {dwarf::DW_AT_MIPS_linkage_name,
568 dwarf::DW_AT_linkage_name}),
569 Default: nullptr);
570}
571
572uint64_t DWARFDie::getDeclLine() const {
573 return toUnsigned(V: findRecursively(Attrs: DW_AT_decl_line), Default: 0);
574}
575
576std::string
577DWARFDie::getDeclFile(DILineInfoSpecifier::FileLineInfoKind Kind) const {
578 if (auto FormValue = findRecursively(Attrs: DW_AT_decl_file))
579 if (auto OptString = FormValue->getAsFile(Kind))
580 return *OptString;
581 return {};
582}
583
584void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
585 uint32_t &CallColumn,
586 uint32_t &CallDiscriminator) const {
587 CallFile = toUnsigned(V: find(Attr: DW_AT_call_file), Default: 0);
588 CallLine = toUnsigned(V: find(Attr: DW_AT_call_line), Default: 0);
589 CallColumn = toUnsigned(V: find(Attr: DW_AT_call_column), Default: 0);
590 CallDiscriminator = toUnsigned(V: find(Attr: DW_AT_GNU_discriminator), Default: 0);
591}
592
593static std::optional<uint64_t>
594getTypeSizeImpl(DWARFDie Die, uint64_t PointerSize,
595 SmallPtrSetImpl<const DWARFDebugInfoEntry *> &Visited) {
596 // Cycle detected?
597 if (!Visited.insert(Ptr: Die.getDebugInfoEntry()).second)
598 return {};
599 if (auto SizeAttr = Die.find(Attr: 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: {
609 if (DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_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: {
620 if (DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type))
621 return getTypeSizeImpl(Die: BaseType, PointerSize, Visited);
622 break;
623 }
624 case DW_TAG_array_type: {
625 DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type);
626 if (!BaseType)
627 return std::nullopt;
628 std::optional<uint64_t> BaseSize =
629 getTypeSizeImpl(Die: 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(Attr: DW_AT_count))
638 if (std::optional<uint64_t> ElemCount =
639 ElemCountAttr->getAsUnsignedConstant())
640 Size *= *ElemCount;
641 if (auto UpperBoundAttr = Child.find(Attr: 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(Attr: DW_AT_lower_bound))
646 LowerBound = LowerBoundAttr->getAsSignedConstant().value_or(u: 0);
647 Size *= *UpperBound - LowerBound + 1;
648 }
649 }
650 return Size;
651 }
652 default:
653 if (DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type))
654 return getTypeSizeImpl(Die: BaseType, PointerSize, Visited);
655 break;
656 }
657 return std::nullopt;
658}
659
660std::optional<uint64_t> DWARFDie::getTypeSize(uint64_t PointerSize) {
661 SmallPtrSet<const DWARFDebugInfoEntry *, 4> Visited;
662 return getTypeSizeImpl(Die: *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: Die.getParent(), OS, Indent, DumpOpts, Depth: Depth + 1);
673 Die.dump(OS, indent: 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(Die: getParent(), OS, Indent, DumpOpts: ParentDumpOpts);
689 }
690
691 if (debug_info_data.isValidOffset(offset)) {
692 uint32_t abbrCode = debug_info_data.getULEB128(offset_ptr: &offset);
693 if (DumpOpts.ShowAddresses)
694 WithColor(OS, HighlightColor::Address).get()
695 << formatv(Fmt: "\n{0:x8}: ", Vals: Offset);
696
697 if (abbrCode) {
698 auto AbbrevDecl = getAbbreviationDeclarationPtr();
699 if (AbbrevDecl) {
700 WithColor(OS, HighlightColor::Tag).get().indent(NumSpaces: Indent)
701 << formatv(Fmt: "{0}", Vals: getTag());
702 if (DumpOpts.Verbose) {
703 OS << formatv(Fmt: " [{0}] {1}", Vals&: abbrCode,
704 Vals: AbbrevDecl->hasChildren() ? '*' : ' ');
705 if (std::optional<uint32_t> ParentIdx = Die->getParentIdx())
706 OS << formatv(Fmt: " ({0:x8})",
707 Vals: U->getDIEAtIndex(Index: *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, Die: *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(Range&: DumpOpts.FilterChildTag, Element: Child.getTag()))
723 Child.dump(OS, Indent: Indent + 2, DumpOpts: 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(NumSpaces: Indent) << "NULL\n";
733 }
734 }
735}
736
737LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(OS&: llvm::errs(), Indent: 0); }
738
739DWARFDie DWARFDie::getParent() const {
740 if (isValid())
741 return U->getParent(Die);
742 return DWARFDie();
743}
744
745DWARFDie DWARFDie::getSibling() const {
746 if (isValid())
747 return U->getSibling(Die);
748 return DWARFDie();
749}
750
751DWARFDie DWARFDie::getPreviousSibling() const {
752 if (isValid())
753 return U->getPreviousSibling(Die);
754 return DWARFDie();
755}
756
757DWARFDie DWARFDie::getFirstChild() const {
758 if (isValid())
759 return U->getFirstChild(Die);
760 return DWARFDie();
761}
762
763DWARFDie DWARFDie::getLastChild() const {
764 if (isValid())
765 return U->getLastChild(Die);
766 return DWARFDie();
767}
768
769iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
770 return make_range(x: attribute_iterator(*this, false),
771 y: attribute_iterator(*this, true));
772}
773
774DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
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: *AbbrDecl, I: 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(idx: Index);
795 // Add the previous byte size of any previous attribute value.
796 AttrValue.Offset += AttrValue.ByteSize;
797 uint64_t ParseOffset = AttrValue.Offset;
798 if (AbbrDecl.getAttrIsImplicitConstByIndex(idx: Index))
799 AttrValue.Value = DWARFFormValue::createFromSValue(
800 F: AbbrDecl.getFormByIndex(idx: Index),
801 V: AbbrDecl.getAttrImplicitConstValueByIndex(idx: Index));
802 else {
803 auto U = Die.getDwarfUnit();
804 assert(U && "Die must have valid DWARF unit");
805 AttrValue.Value = DWARFFormValue::createFromUnit(
806 F: AbbrDecl.getFormByIndex(idx: Index), Unit: U, OffsetPtr: &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
815DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
816 if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
817 updateForIndex(AbbrDecl: *AbbrDecl, I: Index + 1);
818 return *this;
819}
820
821bool DWARFAttribute::mayHaveLocationList(dwarf::Attribute Attr) {
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
838bool DWARFAttribute::mayHaveLocationExpr(dwarf::Attribute Attr) {
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
880void dumpTypeQualifiedName(const DWARFDie &DIE, raw_ostream &OS) {
881 DWARFTypePrinter<DWARFDie>(OS).appendQualifiedName(D: DIE);
882}
883
884void dumpTypeUnqualifiedName(const DWARFDie &DIE, raw_ostream &OS,
885 std::string *OriginalFullName) {
886 DWARFTypePrinter<DWARFDie>(OS).appendUnqualifiedName(D: DIE, OriginalFullName);
887}
888
889} // namespace llvm
890