[llvm] [llvm-dwarfdump] Added .debug_abbrev section for --output-style format (PR #227195)

via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 29 01:25:38 PDT 2026


https://github.com/arrowten updated https://github.com/llvm/llvm-project/pull/227195

>From d9600c2f45eacd7cafcc390407c87d097c79b25d Mon Sep 17 00:00:00 2001
From: Ajay Wakodikar <ajaywakodikarsocial at gmail.com>
Date: Sun, 16 Aug 2026 06:45:03 -0400
Subject: [PATCH 1/4] [llvm-dwarfdump] Added --output-style option for
 controlling output format

---
 llvm/docs/CommandGuide/llvm-dwarfdump.rst     |  7 ++++
 .../tools/llvm-dwarfdump/output-style.test    | 23 +++++++++++++
 llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp  | 33 ++++++++++++++++++-
 3 files changed, 62 insertions(+), 1 deletion(-)
 create mode 100644 llvm/test/tools/llvm-dwarfdump/output-style.test

diff --git a/llvm/docs/CommandGuide/llvm-dwarfdump.rst b/llvm/docs/CommandGuide/llvm-dwarfdump.rst
index 22f2edfc30f57..fff1bede3dced 100644
--- a/llvm/docs/CommandGuide/llvm-dwarfdump.rst
+++ b/llvm/docs/CommandGuide/llvm-dwarfdump.rst
@@ -95,6 +95,13 @@ OPTIONS
             Redirect output to a file specified by <path>, where `-` is the
             standard output stream.
 
+.. option:: --output-style=<value>
+
+            Specify the format of the output. The supported values are:
+
+            `LLVM` - Output in the format used by llvm-dwarfdump. [default]
+            `JSON` - Output in JSON format.
+
 .. option:: -p, --show-parents
 
             Show a debug info entry's parents when selectively printing with
diff --git a/llvm/test/tools/llvm-dwarfdump/output-style.test b/llvm/test/tools/llvm-dwarfdump/output-style.test
new file mode 100644
index 0000000000000..b59fc3c392f56
--- /dev/null
+++ b/llvm/test/tools/llvm-dwarfdump/output-style.test
@@ -0,0 +1,23 @@
+## Show that --output-style=LLVM (the default) dumps normally.
+# RUN: yaml2obj %s -o %t.o
+# RUN: llvm-dwarfdump --output-style=LLVM %t.o | FileCheck %s --check-prefix=LLVM
+
+# LLVM: file format elf64-x86-64
+
+## Show that --output-style=JSON emits a warning, since JSON output is not yet implemented.
+# RUN: llvm-dwarfdump --output-style=JSON %t.o 2>&1 | FileCheck %s --check-prefix=JSON
+
+#      JSON: file format elf64-x86-64
+# JSON-NEXT: warning: JSON output style is not yet implemented
+
+## Show that an unrecognized --output-style value is rejected.
+# RUN: not llvm-dwarfdump --output-style=YAML 2>&1 | FileCheck %s --check-prefix=INVALID
+
+# INVALID: error: --output-style value should be either 'LLVM' or 'JSON', but was 'YAML'
+
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS64
+  Data:    ELFDATA2LSB
+  Type:    ET_REL
+  Machine: EM_X86_64
diff --git a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
index 4d7fc7e3108bf..36d22335d935a 100644
--- a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
+++ b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
@@ -16,6 +16,7 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVectorExtras.h"
 #include "llvm/ADT/StringSet.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/DebugInfo/DIContext.h"
 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
@@ -135,6 +136,8 @@ enum ErrorDetailLevel {
   Unspecified
 };
 
+enum OutputStyleTy { LLVM, JSON, UNKNOWN };
+
 OptionCategory DwarfDumpCategory("Specific Options");
 static list<std::string>
     InputFilenames(Positional, desc("<input object files or .dSYM bundles>"),
@@ -334,6 +337,11 @@ static opt<bool> Verbose("verbose",
                          cat(DwarfDumpCategory));
 static alias VerboseAlias("v", desc("Alias for --verbose."), aliasopt(Verbose),
                           cat(DwarfDumpCategory), cl::NotHidden);
+static opt<std::string>
+    OutputStyleOpt("output-style", init("LLVM"),
+                   desc("Specify the format of the output (LLVM or JSON)"),
+                   cat(DwarfDumpCategory));
+static OutputStyleTy OutputStyle = LLVM;
 static opt<bool>
     ShowVariableCoverage("show-variable-coverage",
                          desc("Show per-variable coverage metrics."),
@@ -775,7 +783,19 @@ static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
   // Dump the complete DWARF structure.
   auto DumpOpts = getDumpOpts(DICtx);
   DumpOpts.GetNameForDWARFReg = GetRegName;
-  DICtx.dump(OS, DumpOpts, DumpOffsets);
+  switch (OutputStyle) {
+  case LLVM:
+    DICtx.dump(OS, DumpOpts, DumpOffsets);
+    break;
+  case JSON:
+    WithColor::warning() << "JSON output style is not yet implemented\n";
+    break;
+  case UNKNOWN:
+    WithColor::error() << "--output-style value should be either 'LLVM' or "
+                          "'JSON', but was '"
+                       << OutputStyleOpt << "'\n";
+    return false;
+  }
   return true;
 }
 
@@ -889,6 +909,17 @@ int main(int argc, char **argv) {
       "pretty-print DWARF debug information in object files"
       " and debug info archives.\n");
 
+  OutputStyle = StringSwitch<OutputStyleTy>(OutputStyleOpt)
+                    .Case("LLVM", LLVM)
+                    .Case("JSON", JSON)
+                    .Default(UNKNOWN);
+  if (OutputStyle == UNKNOWN) {
+    WithColor::error(errs(), sys::path::filename(argv[0]))
+        << "--output-style value should be either 'LLVM' or 'JSON', but was '"
+        << OutputStyleOpt << "'\n";
+    return 1;
+  }
+
   // FIXME: Audit interactions between these two options and make them
   //        compatible.
   if (Diff && Verbose) {

>From 08ae6f6eec3d37e418a2a5fd940e7c9b8112d9f8 Mon Sep 17 00:00:00 2001
From: Ajay Wakodikar <ajaywakodikarsocial at gmail.com>
Date: Mon, 24 Aug 2026 12:12:39 -0400
Subject: [PATCH 2/4] [llvm-dwarfdump] Changed the enum format and test file

---
 .../tools/llvm-dwarfdump/output-style.test    |  5 +++++
 llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp  | 22 +++++++++----------
 2 files changed, 16 insertions(+), 11 deletions(-)

diff --git a/llvm/test/tools/llvm-dwarfdump/output-style.test b/llvm/test/tools/llvm-dwarfdump/output-style.test
index b59fc3c392f56..27223f33333b0 100644
--- a/llvm/test/tools/llvm-dwarfdump/output-style.test
+++ b/llvm/test/tools/llvm-dwarfdump/output-style.test
@@ -4,6 +4,11 @@
 
 # LLVM: file format elf64-x86-64
 
+## Show that omitting --output-style is equivalent to passing --output-style=LLVM explicitly.
+# RUN: llvm-dwarfdump %t.o > %t.default.txt
+# RUN: llvm-dwarfdump --output-style=LLVM %t.o > %t.llvm.txt
+# RUN: cmp %t.default.txt %t.llvm.txt
+
 ## Show that --output-style=JSON emits a warning, since JSON output is not yet implemented.
 # RUN: llvm-dwarfdump --output-style=JSON %t.o 2>&1 | FileCheck %s --check-prefix=JSON
 
diff --git a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
index 36d22335d935a..b1260beac4845 100644
--- a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
+++ b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
@@ -136,7 +136,7 @@ enum ErrorDetailLevel {
   Unspecified
 };
 
-enum OutputStyleTy { LLVM, JSON, UNKNOWN };
+enum class OutputStyleKind { LLVM, JSON, Unknown };
 
 OptionCategory DwarfDumpCategory("Specific Options");
 static list<std::string>
@@ -341,7 +341,7 @@ static opt<std::string>
     OutputStyleOpt("output-style", init("LLVM"),
                    desc("Specify the format of the output (LLVM or JSON)"),
                    cat(DwarfDumpCategory));
-static OutputStyleTy OutputStyle = LLVM;
+static OutputStyleKind Style = OutputStyleKind::LLVM;
 static opt<bool>
     ShowVariableCoverage("show-variable-coverage",
                          desc("Show per-variable coverage metrics."),
@@ -783,14 +783,14 @@ static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
   // Dump the complete DWARF structure.
   auto DumpOpts = getDumpOpts(DICtx);
   DumpOpts.GetNameForDWARFReg = GetRegName;
-  switch (OutputStyle) {
-  case LLVM:
+  switch (Style) {
+  case OutputStyleKind::LLVM:
     DICtx.dump(OS, DumpOpts, DumpOffsets);
     break;
-  case JSON:
+  case OutputStyleKind::JSON:
     WithColor::warning() << "JSON output style is not yet implemented\n";
     break;
-  case UNKNOWN:
+  case OutputStyleKind::Unknown:
     WithColor::error() << "--output-style value should be either 'LLVM' or "
                           "'JSON', but was '"
                        << OutputStyleOpt << "'\n";
@@ -909,11 +909,11 @@ int main(int argc, char **argv) {
       "pretty-print DWARF debug information in object files"
       " and debug info archives.\n");
 
-  OutputStyle = StringSwitch<OutputStyleTy>(OutputStyleOpt)
-                    .Case("LLVM", LLVM)
-                    .Case("JSON", JSON)
-                    .Default(UNKNOWN);
-  if (OutputStyle == UNKNOWN) {
+  Style = StringSwitch<OutputStyleKind>(OutputStyleOpt)
+              .Case("LLVM", OutputStyleKind::LLVM)
+              .Case("JSON", OutputStyleKind::JSON)
+              .Default(OutputStyleKind::Unknown);
+  if (Style == OutputStyleKind::Unknown) {
     WithColor::error(errs(), sys::path::filename(argv[0]))
         << "--output-style value should be either 'LLVM' or 'JSON', but was '"
         << OutputStyleOpt << "'\n";

>From 4fb05c7f016088cf7f71211550e84ba80f1e1ce2 Mon Sep 17 00:00:00 2001
From: Ajay Wakodikar <ajaywakodikarsocial at gmail.com>
Date: Wed, 26 Aug 2026 06:25:07 -0400
Subject: [PATCH 3/4] Revert "[llvm-dwarfdump] Changed the enum format and test
 file"

This reverts commit 08ae6f6eec3d37e418a2a5fd940e7c9b8112d9f8.
---
 .../tools/llvm-dwarfdump/output-style.test    |  5 -----
 llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp  | 22 +++++++++----------
 2 files changed, 11 insertions(+), 16 deletions(-)

diff --git a/llvm/test/tools/llvm-dwarfdump/output-style.test b/llvm/test/tools/llvm-dwarfdump/output-style.test
index 27223f33333b0..b59fc3c392f56 100644
--- a/llvm/test/tools/llvm-dwarfdump/output-style.test
+++ b/llvm/test/tools/llvm-dwarfdump/output-style.test
@@ -4,11 +4,6 @@
 
 # LLVM: file format elf64-x86-64
 
-## Show that omitting --output-style is equivalent to passing --output-style=LLVM explicitly.
-# RUN: llvm-dwarfdump %t.o > %t.default.txt
-# RUN: llvm-dwarfdump --output-style=LLVM %t.o > %t.llvm.txt
-# RUN: cmp %t.default.txt %t.llvm.txt
-
 ## Show that --output-style=JSON emits a warning, since JSON output is not yet implemented.
 # RUN: llvm-dwarfdump --output-style=JSON %t.o 2>&1 | FileCheck %s --check-prefix=JSON
 
diff --git a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
index b1260beac4845..36d22335d935a 100644
--- a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
+++ b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
@@ -136,7 +136,7 @@ enum ErrorDetailLevel {
   Unspecified
 };
 
-enum class OutputStyleKind { LLVM, JSON, Unknown };
+enum OutputStyleTy { LLVM, JSON, UNKNOWN };
 
 OptionCategory DwarfDumpCategory("Specific Options");
 static list<std::string>
@@ -341,7 +341,7 @@ static opt<std::string>
     OutputStyleOpt("output-style", init("LLVM"),
                    desc("Specify the format of the output (LLVM or JSON)"),
                    cat(DwarfDumpCategory));
-static OutputStyleKind Style = OutputStyleKind::LLVM;
+static OutputStyleTy OutputStyle = LLVM;
 static opt<bool>
     ShowVariableCoverage("show-variable-coverage",
                          desc("Show per-variable coverage metrics."),
@@ -783,14 +783,14 @@ static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
   // Dump the complete DWARF structure.
   auto DumpOpts = getDumpOpts(DICtx);
   DumpOpts.GetNameForDWARFReg = GetRegName;
-  switch (Style) {
-  case OutputStyleKind::LLVM:
+  switch (OutputStyle) {
+  case LLVM:
     DICtx.dump(OS, DumpOpts, DumpOffsets);
     break;
-  case OutputStyleKind::JSON:
+  case JSON:
     WithColor::warning() << "JSON output style is not yet implemented\n";
     break;
-  case OutputStyleKind::Unknown:
+  case UNKNOWN:
     WithColor::error() << "--output-style value should be either 'LLVM' or "
                           "'JSON', but was '"
                        << OutputStyleOpt << "'\n";
@@ -909,11 +909,11 @@ int main(int argc, char **argv) {
       "pretty-print DWARF debug information in object files"
       " and debug info archives.\n");
 
-  Style = StringSwitch<OutputStyleKind>(OutputStyleOpt)
-              .Case("LLVM", OutputStyleKind::LLVM)
-              .Case("JSON", OutputStyleKind::JSON)
-              .Default(OutputStyleKind::Unknown);
-  if (Style == OutputStyleKind::Unknown) {
+  OutputStyle = StringSwitch<OutputStyleTy>(OutputStyleOpt)
+                    .Case("LLVM", LLVM)
+                    .Case("JSON", JSON)
+                    .Default(UNKNOWN);
+  if (OutputStyle == UNKNOWN) {
     WithColor::error(errs(), sys::path::filename(argv[0]))
         << "--output-style value should be either 'LLVM' or 'JSON', but was '"
         << OutputStyleOpt << "'\n";

>From 583ddfcb9f6ab9679dcd935fc3410508b445193c Mon Sep 17 00:00:00 2001
From: Ajay Wakodikar <ajaywakodikarsocial at gmail.com>
Date: Wed, 26 Aug 2026 06:55:39 -0400
Subject: [PATCH 4/4] [llvm-dwarfdump] Added .debug_abbrev section for
 --output-style format

---
 .../DWARF/DWARFAbbreviationDeclaration.h      |  5 +++
 .../llvm/DebugInfo/DWARF/DWARFContext.h       |  6 +++
 .../llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h   |  9 +++++
 .../DWARF/DWARFAbbreviationDeclaration.cpp    | 15 ++++++++
 llvm/lib/DebugInfo/DWARF/DWARFContext.cpp     | 38 +++++++++++++++++++
 llvm/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp | 20 ++++++++++
 .../tools/llvm-dwarfdump/output-style.test    | 12 +++++-
 llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp  | 27 +++++++------
 8 files changed, 118 insertions(+), 14 deletions(-)

diff --git a/llvm/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h b/llvm/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h
index 451c438a5e4f6..3f593dccaeff1 100644
--- a/llvm/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h
+++ b/llvm/include/llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h
@@ -14,6 +14,7 @@
 #include "llvm/BinaryFormat/Dwarf.h"
 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
 #include "llvm/Support/Compiler.h"
+#include "llvm/Support/JSON.h"
 #include <cassert>
 #include <cstddef>
 #include <cstdint>
@@ -220,6 +221,10 @@ class DWARFAbbreviationDeclaration {
   std::optional<FixedSizeInfo> FixedAttributeSize;
 };
 
+/// Serialize \p Decl as JSON, matching the symbolic tag/attribute/form names
+/// (and unknown-value fallback) used by DWARFAbbreviationDeclaration::dump.
+LLVM_ABI json::Object toJSON(const DWARFAbbreviationDeclaration &Decl);
+
 } // end namespace llvm
 
 #endif // LLVM_DEBUGINFO_DWARF_DWARFABBREVIATIONDECLARATION_H
diff --git a/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h b/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h
index 13837e40b0e53..ff2d98e97be1e 100644
--- a/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h
+++ b/llvm/include/llvm/DebugInfo/DWARF/DWARFContext.h
@@ -160,6 +160,12 @@ class LLVM_ABI DWARFContext : public DIContext {
     dump(OS, DumpOpts, DumpOffsets);
   }
 
+  /// Dump a JSON representation to \p OS. Only sections with JSON support
+  /// implemented are included; if a section without JSON support is
+  /// explicitly requested via \p DumpOpts, a warning is emitted for it.
+  Error dumpJSON(raw_ostream &OS, DIDumpOptions DumpOpts,
+                 std::array<std::optional<uint64_t>, DIDT_ID_Count> DumpOffsets);
+
   bool verify(raw_ostream &OS, DIDumpOptions DumpOpts = {}) override;
 
   using unit_iterator_range = DWARFUnitVector::iterator_range;
diff --git a/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h b/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h
index 63b168f732b02..b3ca24e50a405 100644
--- a/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h
+++ b/llvm/include/llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h
@@ -12,6 +12,7 @@
 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/DataExtractor.h"
+#include "llvm/Support/JSON.h"
 #include <cstdint>
 #include <map>
 #include <optional>
@@ -66,6 +67,9 @@ class DWARFAbbreviationDeclarationSet {
   void clear();
 };
 
+/// Serialize \p Set as a JSON array of its abbreviation declarations.
+LLVM_ABI json::Array toJSON(const DWARFAbbreviationDeclarationSet &Set);
+
 class DWARFDebugAbbrev {
   using DWARFAbbreviationDeclarationSetMap =
       std::map<uint64_t, DWARFAbbreviationDeclarationSet>;
@@ -93,6 +97,11 @@ class DWARFDebugAbbrev {
   }
 };
 
+/// Serialize \p Abbrev as a JSON array, with one entry per abbreviation
+/// table (each an object with an "Offset" and a "Declarations" array).
+/// Parses \p Abbrev first, as dump() does.
+LLVM_ABI json::Array toJSON(const DWARFDebugAbbrev &Abbrev);
+
 } // end namespace llvm
 
 #endif // LLVM_DEBUGINFO_DWARF_DWARFDEBUGABBREV_H
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp b/llvm/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp
index ecdbd004efadb..dd319565e876a 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp
@@ -158,6 +158,21 @@ void DWARFAbbreviationDeclaration::dump(raw_ostream &OS) const {
   OS << '\n';
 }
 
+json::Object llvm::toJSON(const DWARFAbbreviationDeclaration &Decl) {
+  json::Array Attributes;
+  for (const auto &Spec : Decl.attributes()) {
+    json::Object Attr{{"Attribute", formatv("{0}", Spec.Attr).str()},
+                       {"Form", formatv("{0}", Spec.Form).str()}};
+    if (Spec.isImplicitConst())
+      Attr["Value"] = Spec.getImplicitConstValue();
+    Attributes.push_back(std::move(Attr));
+  }
+  return json::Object{{"Code", Decl.getCode()},
+                      {"Tag", formatv("{0}", Decl.getTag()).str()},
+                      {"Children", Decl.hasChildren()},
+                      {"Attributes", std::move(Attributes)}};
+}
+
 std::optional<uint32_t>
 DWARFAbbreviationDeclaration::findAttributeIndex(dwarf::Attribute Attr) const {
   for (uint32_t i = 0, e = AttributeSpecs.size(); i != e; ++i) {
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
index 70ce257a5804a..525fcf2c70f4d 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
@@ -49,9 +49,11 @@
 #include "llvm/Support/Format.h"
 #include "llvm/Support/FormatAdapters.h"
 #include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/JSON.h"
 #include "llvm/Support/LEB128.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
 #include <cstdint>
 #include <deque>
@@ -1341,6 +1343,42 @@ void DWARFContext::dump(
     getDebugNames().dump(OS);
 }
 
+Error DWARFContext::dumpJSON(
+    raw_ostream &OS, DIDumpOptions DumpOpts,
+    std::array<std::optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
+  uint64_t DumpType = DumpOpts.DumpType;
+
+  StringRef Extension = sys::path::extension(DObj->getFileName());
+  bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
+
+  bool Explicit = DumpType != DIDT_All && !IsDWO;
+  bool ExplicitDWO = Explicit && IsDWO;
+  auto shouldDump = [&](bool Explicit, unsigned ID, StringRef Section) {
+    unsigned Mask = 1U << ID;
+    return (DumpType & Mask) && (Explicit || !Section.empty());
+  };
+
+  // Only sections with JSON support implemented are included here; other
+  // sections are silently skipped unless explicitly requested (see the
+  // warning below).
+  json::Object Root;
+  if (shouldDump(Explicit, DIDT_ID_DebugAbbrev, DObj->getAbbrevSection()))
+    Root["DebugAbbrev"] = toJSON(*getDebugAbbrev());
+  if (shouldDump(ExplicitDWO, DIDT_ID_DebugAbbrev, DObj->getAbbrevDWOSection()))
+    Root["DebugAbbrevDWO"] = toJSON(*getDebugAbbrevDWO());
+
+  // Warn if the user explicitly asked for a section that doesn't have JSON
+  // support yet. Don't warn in the default/--all case, since that would be
+  // noisy today and would need updating on every subsequent per-section PR.
+  if (Explicit && (DumpType & ~static_cast<uint64_t>(DIDT_DebugAbbrev)))
+    WithColor::warning() << "--output-style=JSON does not yet support the "
+                             "requested section(s); only .debug_abbrev is "
+                             "currently supported\n";
+
+  OS << formatv("{0}", json::Value(std::move(Root))) << "\n";
+  return Error::success();
+}
+
 DWARFTypeUnit *DWARFContext::getTypeUnitForHash(uint64_t Hash, bool IsDWO) {
   DWARFUnitVector &DWOUnits = State->getDWOUnits();
   if (const auto &TUI = getTUIndex()) {
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp b/llvm/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp
index 1b99e14085e91..5da1cfb8eb711 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp
@@ -71,6 +71,13 @@ void DWARFAbbreviationDeclarationSet::dump(raw_ostream &OS) const {
     Decl.dump(OS);
 }
 
+json::Array llvm::toJSON(const DWARFAbbreviationDeclarationSet &Set) {
+  json::Array Decls;
+  for (const auto &Decl : Set)
+    Decls.push_back(toJSON(Decl));
+  return Decls;
+}
+
 const DWARFAbbreviationDeclaration *
 DWARFAbbreviationDeclarationSet::getAbbreviationDeclaration(
     uint32_t AbbrCode) const {
@@ -154,6 +161,19 @@ void DWARFDebugAbbrev::dump(raw_ostream &OS) const {
   }
 }
 
+json::Array llvm::toJSON(const DWARFDebugAbbrev &Abbrev) {
+  if (Error Err = Abbrev.parse())
+    // FIXME: We should propagate this error or otherwise display it.
+    llvm::consumeError(std::move(Err));
+
+  json::Array Tables;
+  for (const auto &I : Abbrev)
+    Tables.push_back(json::Object{
+        {"Offset", formatv("{0:x+8}", I.first).str()},
+        {"Declarations", toJSON(I.second)}});
+  return Tables;
+}
+
 Expected<const DWARFAbbreviationDeclarationSet *>
 DWARFDebugAbbrev::getAbbreviationDeclarationSet(uint64_t CUAbbrOffset) const {
   const auto End = AbbrDeclSets.end();
diff --git a/llvm/test/tools/llvm-dwarfdump/output-style.test b/llvm/test/tools/llvm-dwarfdump/output-style.test
index b59fc3c392f56..bd67ab09ddc91 100644
--- a/llvm/test/tools/llvm-dwarfdump/output-style.test
+++ b/llvm/test/tools/llvm-dwarfdump/output-style.test
@@ -4,11 +4,19 @@
 
 # LLVM: file format elf64-x86-64
 
-## Show that --output-style=JSON emits a warning, since JSON output is not yet implemented.
+## Show that omitting --output-style is equivalent to passing --output-style=LLVM explicitly.
+# RUN: llvm-dwarfdump %t.o > %t.default.txt
+# RUN: llvm-dwarfdump --output-style=LLVM %t.o > %t.llvm.txt
+# RUN: cmp %t.default.txt %t.llvm.txt
+
+## Show that --output-style=JSON emits a warning for sections without JSON
+## support yet (--debug-abbrev is currently the only section implemented;
+## with no section flags, llvm-dwarfdump implicitly requests --debug-info).
 # RUN: llvm-dwarfdump --output-style=JSON %t.o 2>&1 | FileCheck %s --check-prefix=JSON
 
 #      JSON: file format elf64-x86-64
-# JSON-NEXT: warning: JSON output style is not yet implemented
+# JSON-NEXT: warning: --output-style=JSON does not yet support the requested section(s); only .debug_abbrev is currently supported
+# JSON-NEXT: {}
 
 ## Show that an unrecognized --output-style value is rejected.
 # RUN: not llvm-dwarfdump --output-style=YAML 2>&1 | FileCheck %s --check-prefix=INVALID
diff --git a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
index 36d22335d935a..b4d87b222b093 100644
--- a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
+++ b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
@@ -136,7 +136,7 @@ enum ErrorDetailLevel {
   Unspecified
 };
 
-enum OutputStyleTy { LLVM, JSON, UNKNOWN };
+enum class OutputStyleKind { LLVM, JSON, Unknown };
 
 OptionCategory DwarfDumpCategory("Specific Options");
 static list<std::string>
@@ -341,7 +341,7 @@ static opt<std::string>
     OutputStyleOpt("output-style", init("LLVM"),
                    desc("Specify the format of the output (LLVM or JSON)"),
                    cat(DwarfDumpCategory));
-static OutputStyleTy OutputStyle = LLVM;
+static OutputStyleKind Style = OutputStyleKind::LLVM;
 static opt<bool>
     ShowVariableCoverage("show-variable-coverage",
                          desc("Show per-variable coverage metrics."),
@@ -783,14 +783,17 @@ static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
   // Dump the complete DWARF structure.
   auto DumpOpts = getDumpOpts(DICtx);
   DumpOpts.GetNameForDWARFReg = GetRegName;
-  switch (OutputStyle) {
-  case LLVM:
+  switch (Style) {
+  case OutputStyleKind::LLVM:
     DICtx.dump(OS, DumpOpts, DumpOffsets);
     break;
-  case JSON:
-    WithColor::warning() << "JSON output style is not yet implemented\n";
+  case OutputStyleKind::JSON:
+    if (Error Err = DICtx.dumpJSON(OS, DumpOpts, DumpOffsets)) {
+      WithColor::error() << toString(std::move(Err)) << "\n";
+      return false;
+    }
     break;
-  case UNKNOWN:
+  case OutputStyleKind::Unknown:
     WithColor::error() << "--output-style value should be either 'LLVM' or "
                           "'JSON', but was '"
                        << OutputStyleOpt << "'\n";
@@ -909,11 +912,11 @@ int main(int argc, char **argv) {
       "pretty-print DWARF debug information in object files"
       " and debug info archives.\n");
 
-  OutputStyle = StringSwitch<OutputStyleTy>(OutputStyleOpt)
-                    .Case("LLVM", LLVM)
-                    .Case("JSON", JSON)
-                    .Default(UNKNOWN);
-  if (OutputStyle == UNKNOWN) {
+  Style = StringSwitch<OutputStyleKind>(OutputStyleOpt)
+              .Case("LLVM", OutputStyleKind::LLVM)
+              .Case("JSON", OutputStyleKind::JSON)
+              .Default(OutputStyleKind::Unknown);
+  if (Style == OutputStyleKind::Unknown) {
     WithColor::error(errs(), sys::path::filename(argv[0]))
         << "--output-style value should be either 'LLVM' or 'JSON', but was '"
         << OutputStyleOpt << "'\n";



More information about the llvm-commits mailing list