[llvm] [DebugInfo] Fix compact DWARF expression failure handling (PR #213391)

Eric Christopher via llvm-commits llvm-commits at lists.llvm.org
Fri Jul 31 17:55:08 PDT 2026


https://github.com/echristo created https://github.com/llvm/llvm-project/pull/213391

printDwarfExpressionCompact has two pre-existing failure paths that silently produce bad output.

The register-name callback is optional, but the short DW_OP_reg* and DW_OP_breg* paths call it directly, so a missing callback falls over. Use resolveRegName for every register form and report an unknown register only after both name-resolution paths fail.

DW_OP_entry_value has the same problem: it ignores a failed recursive print, wraps the partial output in entry(...), and returns true. Print entry-value subexpressions into a temporary buffer and propagate failure before adding entry(...), so a failed subexpression can't come back as successful output.

While here, GetRegName in llvm-objdump has a latent ordering issue: it writes an unknown-register diagnostic as soon as target lookup misses, even though resolveRegName can still decode an ASCII-packed virtual-register name. There's no natural in-tree input that hits this today -- LLVM emits text PTX and there's no NVPTX disassembler -- but a future out-of-tree disassembler using the same encoding would otherwise print a valid %r1 as "<unknown register 2454065>%r1". Keep GetRegName lookup-only and let the compact printer own the diagnostic.

The llvm-objdump test makes the theoretical path testable by putting NVPTX's packed value for %r1 in ARM DWARF, so target lookup misses before packed-name decoding succeeds. Add target-independent unit coverage for missing callbacks, unknown registers, and nested failures.

Tested via make check.

Assisted by AI.

>From bf8f980129f27b6f1e3a1a5f5bbe3b4cba4ac8d5 Mon Sep 17 00:00:00 2001
From: Eric Christopher <echristopher at nvidia.com>
Date: Thu, 23 Jul 2026 21:57:44 -0700
Subject: [PATCH] [DebugInfo] Fix compact DWARF expression failure handling

This fixes two pre-existing failure paths in printDwarfExpressionCompact.
The register-name callback is optional, but the short DW_OP_reg* and
DW_OP_breg* paths call it directly. DW_OP_entry_value also ignores a failed
recursive print, then wraps the partial output in entry(...) and can return
true for an unprintable subexpression.

Use resolveRegName for every register form and report an unknown register only
after name resolution fails. Print entry-value subexpressions into a temporary
buffer and propagate their failure before adding entry(...), so the diagnostic
is kept and a failed subexpression cannot become successful output.

This also avoids a theoretical callback issue in llvm-objdump. Its GetRegName
callback writes an unknown-register diagnostic as soon as target lookup misses,
even though resolveRegName can still decode an ASCII-packed virtual-register
name. There is no natural in-tree input for this today: LLVM emits text PTX and
llvm-objdump has no NVPTX disassembler. A future or out-of-tree disassemblable
target using the same encoding could otherwise print a valid %r1 as
"<unknown register 2454065>%r1".

Keep GetRegName lookup-only and let the compact printer own the diagnostic
after both name-resolution paths fail. The llvm-objdump test makes the
theoretical path testable by putting NVPTX's packed value for %r1 in ARM DWARF,
which makes target lookup miss before packed-name decoding succeeds.

Add target-independent unit coverage for missing callbacks, unknown registers,
and nested failures.
---
 .../DWARF/DWARFExpressionPrinter.cpp          |  37 +++--
 .../ELF/ARM/debug-vars-ascii-packed-reg.s     |  50 ++++++
 llvm/tools/llvm-objdump/SourcePrinter.cpp     |   5 +-
 .../DWARFExpressionCompactPrinterTest.cpp     | 149 ++++++++++++------
 4 files changed, 183 insertions(+), 58 deletions(-)
 create mode 100644 llvm/test/tools/llvm-objdump/ELF/ARM/debug-vars-ascii-packed-reg.s

diff --git a/llvm/lib/DebugInfo/DWARF/DWARFExpressionPrinter.cpp b/llvm/lib/DebugInfo/DWARF/DWARFExpressionPrinter.cpp
index ac9350b5b2f52..7a80ae027db1e 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFExpressionPrinter.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFExpressionPrinter.cpp
@@ -287,6 +287,14 @@ static bool printCompactDWARFExpr(
     return false;
   };
 
+  // Keep the diagnostic in the compact printer so every register form reports
+  // failure only after resolveRegName has tried to get a target name and decode
+  // an ASCII-packed name.
+  auto UnknownRegister = [](raw_ostream &OS, uint64_t DwarfRegNum) -> bool {
+    OS << "<unknown register " << DwarfRegNum << ">";
+    return false;
+  };
+
   while (I != E) {
     const DWARFExpression::Operation &Op = *I;
     uint8_t Opcode = Op.getCode();
@@ -298,7 +306,7 @@ static bool printCompactDWARFExpr(
       std::string RegName =
           resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
       if (RegName.empty())
-        return false;
+        return UnknownRegister(OS, DwarfRegNum);
       raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
       S << RegName;
       break;
@@ -309,7 +317,7 @@ static bool printCompactDWARFExpr(
       std::string RegName =
           resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
       if (RegName.empty())
-        return false;
+        return UnknownRegister(OS, DwarfRegNum);
       raw_svector_ostream S(Stack.emplace_back().String);
       S << RegName;
       if (Offset)
@@ -323,10 +331,19 @@ static bool printCompactDWARFExpr(
       uint64_t SubExprLength = Op.getRawOperand(0);
       DWARFExpression::iterator SubExprEnd = I.skipBytes(SubExprLength);
       ++I;
+
+      SmallString<16> SubExpr;
+      raw_svector_ostream SubExprOS(SubExpr);
+      // Keep the subexpression separate so we can copy its diagnostic on
+      // failure without leaving a partial entry(...) in the output.
+      if (!printCompactDWARFExpr(SubExprOS, I, SubExprEnd,
+                                 GetNameForDWARFReg)) {
+        OS << SubExprOS.str();
+        return false;
+      }
+
       raw_svector_ostream S(Stack.emplace_back().String);
-      S << "entry(";
-      printCompactDWARFExpr(S, I, SubExprEnd, GetNameForDWARFReg);
-      S << ")";
+      S << "entry(" << SubExprOS.str() << ")";
       I = SubExprEnd;
       continue;
     }
@@ -351,18 +368,20 @@ static bool printCompactDWARFExpr(
         // DW_OP_reg<N>: A register, with the register num implied by the
         // opcode. Printed as the plain register name.
         uint64_t DwarfRegNum = Opcode - dwarf::DW_OP_reg0;
-        auto RegName = GetNameForDWARFReg(DwarfRegNum, false);
+        std::string RegName =
+            resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
         if (RegName.empty())
-          return false;
+          return UnknownRegister(OS, DwarfRegNum);
         raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
         S << RegName;
       } else if (Opcode >= dwarf::DW_OP_breg0 &&
                  Opcode <= dwarf::DW_OP_breg31) {
         int DwarfRegNum = Opcode - dwarf::DW_OP_breg0;
         int64_t Offset = Op.getRawOperand(0);
-        auto RegName = GetNameForDWARFReg(DwarfRegNum, false);
+        std::string RegName =
+            resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
         if (RegName.empty())
-          return false;
+          return UnknownRegister(OS, DwarfRegNum);
         raw_svector_ostream S(Stack.emplace_back().String);
         S << RegName;
         if (Offset)
diff --git a/llvm/test/tools/llvm-objdump/ELF/ARM/debug-vars-ascii-packed-reg.s b/llvm/test/tools/llvm-objdump/ELF/ARM/debug-vars-ascii-packed-reg.s
new file mode 100644
index 0000000000000..6a4fc7fa7e816
--- /dev/null
+++ b/llvm/test/tools/llvm-objdump/ELF/ARM/debug-vars-ascii-packed-reg.s
@@ -0,0 +1,50 @@
+## NVPTX packs virtual register names into DWARF register numbers, but its text
+## PTX output does not exercise llvm-objdump's disassembler. Put the packed
+## value for "%r1" in an ARM object to make the target lookup miss. Compact
+## printing must produce "%r1" without first emitting
+## "<unknown register 2454065>".
+##
+## Keep both instructions; llvm-objdump does not render this live range with
+## only one.
+
+# RUN: llvm-mc -triple armv8a--none-eabi < %s -filetype=obj -o %t.o
+# RUN: llvm-objdump %t.o -d --debug-vars=ascii | FileCheck %s \
+# RUN:   --implicit-check-not="<unknown register"
+
+# CHECK: x = %r1
+
+	.text
+	.arch	armv8-a
+foo:
+.Lfunc_begin0:
+	ldr	r0, [r0]
+	bx	lr
+.Lfunc_end0:
+
+	.section	.debug_abbrev,"",%progbits
+	@ DW_TAG_compile_unit with children and no attributes.
+	.byte	1, 17, 1, 0, 0
+	@ DW_TAG_subprogram with DW_AT_low_pc and DW_AT_high_pc.
+	.byte	2, 46, 1, 17, 1, 18, 6, 0, 0
+	@ DW_TAG_variable with DW_AT_location and DW_AT_name.
+	.byte	3, 52, 0, 2, 24, 3, 8, 0, 0
+	.byte	0                  @ end of abbreviation table
+
+	.section	.debug_info,"",%progbits
+	.long	.Lcu_end0-.Lcu_post_length0 @ unit length
+.Lcu_post_length0:
+	.short	4                  @ DWARF version
+	.long	.debug_abbrev      @ abbreviation table offset
+	.byte	4                  @ address size
+
+	.byte	1                  @ DW_TAG_compile_unit
+	.byte	2                  @ DW_TAG_subprogram
+	.long	.Lfunc_begin0      @ DW_AT_low_pc
+	.long	.Lfunc_end0-.Lfunc_begin0 @ DW_AT_high_pc
+	.byte	3                  @ DW_TAG_variable
+	.byte	5, 0x90            @ exprloc length, DW_OP_regx
+	.uleb128 0x257231      @ ASCII-packed "%r1"
+	.asciz	"x"                @ DW_AT_name
+	.byte	0                  @ end of subprogram children
+	.byte	0                  @ end of CU
+.Lcu_end0:
diff --git a/llvm/tools/llvm-objdump/SourcePrinter.cpp b/llvm/tools/llvm-objdump/SourcePrinter.cpp
index ea325aca22784..b1adf62798379 100644
--- a/llvm/tools/llvm-objdump/SourcePrinter.cpp
+++ b/llvm/tools/llvm-objdump/SourcePrinter.cpp
@@ -188,12 +188,13 @@ void LiveVariable::print(raw_ostream &OS, const MCRegisterInfo &MRI) const {
   DataExtractor Data(LocExpr.Expr, Unit->getContext().isLittleEndian());
   DWARFExpression Expression(Data, Unit->getAddressByteSize());
 
-  auto GetRegName = [&MRI, &OS](uint64_t DwarfRegNum, bool IsEH) -> StringRef {
+  // Return an empty name for a target lookup miss so the compact printer can
+  // decode an ASCII-packed name before reporting the register as unknown.
+  auto GetRegName = [&MRI](uint64_t DwarfRegNum, bool IsEH) -> StringRef {
     if (std::optional<MCRegister> LLVMRegNum =
             MRI.getLLVMRegNum(DwarfRegNum, IsEH))
       if (const char *RegName = MRI.getName(*LLVMRegNum))
         return StringRef(RegName);
-    OS << "<unknown register " << DwarfRegNum << ">";
     return {};
   };
 
diff --git a/llvm/unittests/DebugInfo/DWARF/DWARFExpressionCompactPrinterTest.cpp b/llvm/unittests/DebugInfo/DWARF/DWARFExpressionCompactPrinterTest.cpp
index b0011047c7b13..5f3bf0fc3fd06 100644
--- a/llvm/unittests/DebugInfo/DWARF/DWARFExpressionCompactPrinterTest.cpp
+++ b/llvm/unittests/DebugInfo/DWARF/DWARFExpressionCompactPrinterTest.cpp
@@ -12,12 +12,8 @@
 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
 #include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
 #include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
-#include "llvm/MC/MCInstrInfo.h"
-#include "llvm/MC/MCRegisterInfo.h"
-#include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/DataExtractor.h"
 #include "llvm/Support/LEB128.h"
-#include "llvm/Support/TargetSelect.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 
@@ -31,53 +27,61 @@ static void appendULEB128(SmallVectorImpl<uint8_t> &V, uint64_t Val) {
   V.append(Buf, Buf + N);
 }
 
-class DWARFExpressionCompactPrinterTest : public ::testing::Test {
-public:
-  std::unique_ptr<MCRegisterInfo> MRI;
-
-  DWARFExpressionCompactPrinterTest() {
-    InitializeAllTargets();
-    InitializeAllTargetMCs();
-    InitializeAllAsmPrinters();
-
-    Triple TT("armv8a-linux-gnueabi");
-    std::string ErrorStr;
-
-    const Target *TheTarget = TargetRegistry::lookupTarget(TT, ErrorStr);
+// Use a fixed map so these tests don't depend on which targets are built into
+// the unit test binary. Unmapped values cover failed target lookups and
+// ASCII-packed names.
+static StringRef getTestRegisterName(uint64_t DwarfRegNum, bool) {
+  switch (DwarfRegNum) {
+  case 0:
+    return "R0";
+  case 10:
+    return "R10";
+  case 13:
+    return "SP";
+  case 256:
+    return "D0";
+  default:
+    return {};
+  }
+}
 
-    if (!TheTarget)
-      return;
+static void expectCompactPrintFailureWithoutRegNames(ArrayRef<uint8_t> ExprData,
+                                                     StringRef Expected) {
+  std::string Result;
+  raw_string_ostream OS(Result);
+  DataExtractor DE(ExprData, true);
+  DWARFExpression Expr(DE, 8);
 
-    MRI.reset(TheTarget->createMCRegInfo(TT));
-  }
+  EXPECT_FALSE(printDwarfExpressionCompact(&Expr, OS));
+  EXPECT_EQ(OS.str(), Expected);
+}
 
+class DWARFExpressionCompactPrinterTest : public ::testing::Test {
+public:
   void TestExprPrinter(ArrayRef<uint8_t> ExprData, StringRef Expected);
+  void TestExprPrinterFailure(ArrayRef<uint8_t> ExprData, StringRef Expected);
 };
 } // namespace
 
 void DWARFExpressionCompactPrinterTest::TestExprPrinter(
     ArrayRef<uint8_t> ExprData, StringRef Expected) {
-  // If we didn't build ARM, do not run the test.
-  if (!MRI)
-    GTEST_SKIP();
-
-  // Print the expression, passing in the subprogram DIE, and check that the
-  // result is as expected.
   std::string Result;
   raw_string_ostream OS(Result);
   DataExtractor DE(ExprData, true);
   DWARFExpression Expr(DE, 8);
 
-  auto GetRegName = [&](uint64_t DwarfRegNum, bool IsEH) -> StringRef {
-    if (std::optional<MCRegister> LLVMRegNum =
-            this->MRI->getLLVMRegNum(DwarfRegNum, IsEH))
-      if (const char *RegName = this->MRI->getName(*LLVMRegNum))
-        return llvm::StringRef(RegName);
-    OS << "<unknown register " << DwarfRegNum << ">";
-    return {};
-  };
+  EXPECT_TRUE(printDwarfExpressionCompact(&Expr, OS, getTestRegisterName));
+  EXPECT_EQ(OS.str(), Expected);
+}
+
+void DWARFExpressionCompactPrinterTest::TestExprPrinterFailure(
+    ArrayRef<uint8_t> ExprData, StringRef Expected) {
+  std::string Result;
+  raw_string_ostream OS(Result);
+  DataExtractor DE(ExprData, true);
+  DWARFExpression Expr(DE, 8);
 
-  printDwarfExpressionCompact(&Expr, OS, GetRegName);
+  EXPECT_FALSE(printDwarfExpressionCompact(&Expr, OS, getTestRegisterName));
   EXPECT_EQ(OS.str(), Expected);
 }
 
@@ -93,10 +97,23 @@ TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_regx) {
   TestExprPrinter({DW_OP_regx, 0x80, 0x02}, "D0");
 }
 
+// Register 100 has neither a target name nor an ASCII-packed name, so check
+// that DW_OP_regx reports it as unknown and returns false.
+TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_regx_unknown) {
+  TestExprPrinterFailure({DW_OP_regx, 0x64}, "<unknown register 100>");
+}
+
 TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_breg0) {
   TestExprPrinter({DW_OP_breg0, 0x04}, "[R0+4]");
 }
 
+// With no register callback, the short register form must report register 0 as
+// unknown and return false without calling GetNameForDWARFReg.
+TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_reg0_no_callback) {
+  expectCompactPrintFailureWithoutRegNames({DW_OP_reg0},
+                                           "<unknown register 0>");
+}
+
 TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_breg0_large_offset) {
   TestExprPrinter({DW_OP_breg0, 0x80, 0x02}, "[R0+256]");
 }
@@ -117,6 +134,20 @@ TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_bregx) {
   TestExprPrinter({DW_OP_bregx, 0x0d, 0x28}, "[SP+40]");
 }
 
+// DW_OP_bregx uses the same two lookups, so check that it reports register 100
+// as unknown and returns false when neither finds a name.
+TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_bregx_unknown) {
+  TestExprPrinterFailure({DW_OP_bregx, 0x64, 0x00},
+                         "<unknown register 100>");
+}
+
+// With no register callback, the short base-register form must also report
+// register 0 as unknown and return false without calling GetNameForDWARFReg.
+TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_breg0_no_callback) {
+  expectCompactPrintFailureWithoutRegNames({DW_OP_breg0, 0x00},
+                                           "<unknown register 0>");
+}
+
 TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_stack_value) {
   TestExprPrinter({DW_OP_breg13, 0x04, DW_OP_stack_value}, "SP+4");
 }
@@ -132,13 +163,34 @@ TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_entry_value_mem) {
       "entry([SP+16])");
 }
 
+// A failed register lookup inside DW_OP_entry_value must keep the nested
+// diagnostic and fail the enclosing expression before printing entry(...).
+TEST_F(DWARFExpressionCompactPrinterTest,
+       Test_OP_entry_value_unknown_register) {
+  TestExprPrinterFailure(
+      {DW_OP_entry_value, 0x02, DW_OP_regx, 0x64, DW_OP_stack_value},
+      "<unknown register 100>");
+}
+
+// Use an opcode the compact printer does not handle to check that
+// DW_OP_entry_value keeps the nested diagnostic and propagates the failure.
+TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_entry_value_unknown_op) {
+  TestExprPrinterFailure(
+      {DW_OP_entry_value, 0x02, DW_OP_const1u, 0x01, DW_OP_stack_value},
+      "<unknown op DW_OP_const1u (8)>");
+}
+
+// DW_OP_nop leaves the stack empty, so compact printing must emit the
+// stack-size diagnostic and return false.
 TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_nop) {
-  TestExprPrinter({DW_OP_nop}, "<stack of size 0, expected 1>");
+  TestExprPrinterFailure({DW_OP_nop}, "<stack of size 0, expected 1>");
 }
 
+// DW_OP_LLVM_nop leaves the stack empty as well, so it must emit the same
+// diagnostic and return false.
 TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_LLVM_nop) {
-  TestExprPrinter({DW_OP_LLVM_user, DW_OP_LLVM_nop},
-                  "<stack of size 0, expected 1>");
+  TestExprPrinterFailure({DW_OP_LLVM_user, DW_OP_LLVM_nop},
+                         "<stack of size 0, expected 1>");
 }
 
 TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_nop_OP_reg) {
@@ -149,14 +201,16 @@ TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_LLVM_nop_OP_reg) {
   TestExprPrinter({DW_OP_LLVM_user, DW_OP_LLVM_nop, DW_OP_reg0}, "R0");
 }
 
+// An unhandled DW_OP_LLVM_user subopcode must print both opcode names and
+// values, then return false.
 TEST_F(DWARFExpressionCompactPrinterTest, Test_OP_LLVM_user_unknown_subop) {
-  TestExprPrinter({DW_OP_LLVM_user, DW_OP_LLVM_form_aspace_address},
-                  "<unknown op DW_OP_LLVM_user (233) subop "
-                  "DW_OP_LLVM_form_aspace_address (2)>");
+  TestExprPrinterFailure({DW_OP_LLVM_user, DW_OP_LLVM_form_aspace_address},
+                         "<unknown op DW_OP_LLVM_user (233) subop "
+                         "DW_OP_LLVM_form_aspace_address (2)>");
 }
 
-// NVPTX encodes virtual register names as a packed uint64_t DWARF register
-// number; llvm-dwarfdump must still print the string when MC has no mapping.
+// NVPTX packs virtual register names into DWARF register numbers, so compact
+// printing without a callback must recover the name and return true.
 TEST(NVPTXPackedRegister, Compact_DW_OP_regx_NoMRI) {
   SmallVector<uint8_t, 16> Enc;
   Enc.push_back(DW_OP_regx);
@@ -167,8 +221,7 @@ TEST(NVPTXPackedRegister, Compact_DW_OP_regx_NoMRI) {
   DataExtractor DE(Enc, true);
   DWARFExpression Expr(DE, 8);
 
-  printDwarfExpressionCompact(&Expr, OS, nullptr);
-
+  EXPECT_TRUE(printDwarfExpressionCompact(&Expr, OS, nullptr));
   EXPECT_EQ(OS.str(), "%rd2");
 }
 
@@ -199,7 +252,9 @@ TEST(NVPTXPackedRegister, Full_DW_OP_regx_CallbackMiss) {
   DWARFExpression Expr(DE, 8);
 
   DIDumpOptions DumpOpts;
-  DumpOpts.GetNameForDWARFReg = [](uint64_t, bool) -> StringRef { return {}; };
+  // getTestRegisterName misses this packed value, so the full printer still
+  // needs to recover the name from the register number.
+  DumpOpts.GetNameForDWARFReg = getTestRegisterName;
 
   printDwarfExpression(&Expr, OS, DumpOpts, nullptr);
 



More information about the llvm-commits mailing list