Skip to content

[BPF] Handle C++ records in BTF and CO-RE - #233715

Open
maxskokov wants to merge 7 commits into
llvm:mainfrom
maxskokov:bpf-btf-cxx-records
Open

maxskokov wants to merge 7 commits into
llvm:mainfrom
maxskokov:bpf-btf-cxx-records

Conversation

@maxskokov

@maxskokov maxskokov commented Oct 20, 2026 •

Copy link
Copy Markdown

Combines #226717 and #226723, as asked in #226717; follow-up to #226790.

Since #155783 (LLVM 22.1), compiling C++ for BPF with -g hits llvm_unreachable() in BTF emission as soon as a record has a base class, a static data member (DWARF 5) or a method, or is declared with class; #205396 moved the first crash into the offset sort:

struct S { void *p; ~S(); };
long f(S *s) { return (long)s->p; }

A C++ record lists bases, static members and methods among its debug info elements next to its data members, and a record declared with class has DW_TAG_class_type, which the backend did not handle. The CO-RE pass and visitMapDefType() walk the same elements and crash too.

BTF. A non-virtual base becomes an anonymous member of the base type at its offset, as pahole encodes inheritance; virtual bases, static data members and methods are skipped. A class is emitted as a struct (before #155783 it was type 0). A reference becomes a pointer; before, a reference member had type 0.

CO-RE. Since #226790 the DI index of a CO-RE access is an index into the record's debug info elements. The backend takes that element and maps it to its position among the BTF members, built from the same ordered list as BTF, so bases, static members and methods no longer shift the access string. On BPF, clang reports a conversion between a class and its base that the address of a CO-RE access depends on, as the offset of the base, which may differ in the target, would not be relocated. An index that does not refer to a data member, e.g. into a record the debug info only declares, is reported as an error at the access instead of crashing. A class is relocated like a struct; before, an access into a class got offset 0.

Testing

BTF with single and multiple inheritance, an empty base, a method and a static data member, loaded with BPF_BTF_LOAD on Linux 6.12:

compiler base class in BTF kernel
clang 19 member with type_id=0 rejected: "Invalid type_id"
22.1–main (from the source) — llvm_unreachable(): crash with assertions, UB without
this PR anonymous member of the base type accepted

CO-RE; clang 19 with -fstandalone-debug (with plain -g it segfaults on V), the other columns the same with -g and -g -fstandalone-debug:

access clang 19 main this PR
struct S : Base { int x, y; }, &s->y offset 4, 0:1 (that is x) crash offset 8, 0:2
struct V : virtual Base { int v; }, &v->v offset 3, 0:0 crash offset 8, 0:1
class C { public: int x, y; }, &c->y offset 0 crash offset 4

New tests cover these cases, a class and a declared-only class as STRUCT and FWD, a map definition declared as a class, a bit-field in a class, references and the rejected base accesses; they fail on main. The kernel BPF selftests (1060 C programs) compile to identical code and .BTF.ext, and to .BTF with the same content; in 25 of them the types come in a different order, as FWD order is not stable between clang builds.

Known limitations

This fixes a crash that is a regression since 22.1 (#155783); once this lands I'd like to request a backport to 23.x together with #226790.

Assisted-by: Claude Code (Claude Opus 5.5)

@github-actions

Copy link
Copy Markdown

Hello @maxskokov 👋

Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.

  • All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
  • The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
  • Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.

Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.


Frequently asked questions

How do I add reviewers?

This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.

You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.

What if there are no comments?

If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.

Are any special GitHub settings required to contribute to LLVM?

We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.


If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.

Thank you,
The LLVM Community

@maxskokov

Copy link
Copy Markdown
Author

@yonghong-song @tamird

maxskokov added a commit to cpp-bpf/cpp-bpf that referenced this pull request Oct 20, 2026
Add typed maps (CPPBPF_HASH_MAP and friends), spin_guard, ring buffer
reservations that are discarded unless submitted, and CPPBPF_PROG for
BTF-enabled programs with typed arguments, including structs of up to
16 bytes passed by value.

Two tests load programs that use them: basic checks the maps, the lock
and the ring buffer, and args checks the argument mapping of
CPPBPF_PROG against the known arguments of bpf_fentry_test*(). CI
builds clang with llvm/llvm-project#233715 and runs the tests.

Until the libbpf helper definitions compile as C++ upstream (#4), the
test build patches a copy of bpf_helper_defs.h.

Signed-off-by: Maxim Skokov <[email protected]>

@tamird tamird left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The C++ record path still permits incorrect CO-RE relocation and BTF that cannot be loaded. The inline comments give the cases and requested corrections.

Update: additional review findings

  • Use one BTF member-eligibility rule. getDIRecordField repeats isBTFRecordElement's non-static-member rule, while getBTFMemberIndex silently returns Elements.size() if the rules diverge. Keep CO-RE's explicit data-member restriction, reuse the shared BTF eligibility rule, and make a failed lookup explicit.
  • Name the predicate for the representation it tests. isStructTag also accepts DW_TAG_class_type: it means “represented as a BTF struct,” not “is the DWARF structure tag.” isBTFStructTag would make that distinction visible at call sites and match the related BTF helper names.

Validation: Bazel compiled all 27 BPF backend objects at 5b41c48. The BPF source and test subtrees are unchanged at a10f2d0. No behavioral tests were run.

Assisted-by: OpenAI Codex, with delegated review agents.

if (AccessIndex >= Elements.size())
return nullptr;
auto *Field = dyn_cast<DIDerivedType>(Elements[AccessIndex]);
if (!Field || Field->getTag() != dwarf::DW_TAG_member ||

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Inherited CO-RE accesses can silently use the wrong address. For D : A, B, Clang applies the derived-to-base adjustment as an ordinary constant GEP before emitting the field intrinsic for d->b; the relocation is rooted at B. If B moves from offset 4 to 8 in the target layout, relocation can succeed while the program still uses offset 4. This is the inherited-field limitation documented in the description, but it permits wrong code. Please carry the base adjustment through the preserve-access chain and handle it here, or reject unsupported inherited accesses.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with rejecting: clang now reports a CO-RE access through a virtual base or a base at a non-zero offset (clang/test/CodeGenCXX/builtin-preserve-access-index-base.cpp). A base at offset 0 is still allowed, as its address is that of the derived object. Carrying the base through the chain as an access to its anonymous BTF member would make these relocatable; I'd rather do that in a follow-up.

auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
TypeId = addType(std::move(TypeEntry), DTy);
} else if (Tag != dwarf::DW_TAG_member) {
} else if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_inheritance) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Class records with reference data members still crash or produce invalid BTF. This drops DW_TAG_reference_type without registering it; BTFTypeStruct::completeType() then calls getTypeId(), which asserts in assertions-enabled builds and returns type ID 0 in release builds. This existing LLVM fixture shows the metadata shape. Please handle the member type or diagnose it before completing the record.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

auto Tag = CTy->getTag();
switch (Tag) {
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_class_type:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Class templates produce unloadable BTF. A specialization has a debug name such as TC<int>, which BTFTypeStruct::completeType() emits verbatim. The kernel requires a valid struct name, and its character check rejects the angle brackets. Please use a valid representation consistent with CO-RE type identity, or diagnose the unsupported type.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type names now drop the template arguments, as -gsimple-template-names does, which also covers alias templates. Specializations then share a name, which BTF allows. For reference, bpf-next accepts any printable name since bed1986a1932 ("bpf: Allow names of Rust types and functions in BTF"), but released kernels don't.

/// Return the position of Field among the BTF members of record CTy.
static uint64_t getBTFMemberIndex(const DICompositeType *CTy,
const DINode *Field) {
SmallVector<const DINode *, 8> Elements = getBTFRecordElements(CTy);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Every CO-RE access now materializes the member list, and struct/class accesses sort it. This replaces the previous linear, constant-space rank calculation with a sort for each struct access and turns union lookup into a scan, affecting existing C and Rust programs too. Please compute rank using the shared filtering and ordering rules, or cache the mapping while the record is unchanged.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

"CO-RE access index " + Twine(AccessIndex) +
" does not refer to a field of '" + CTy->getName() +
"' in the debug info",
Call->getDebugLoc()));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] For an invalid later access in a chain, this points at the wrong source location: the second traversal updates CInfo from StackElem but leaves Call referring to the first access. Please use the current stack element for the diagnostic. The new nested negative test cannot distinguish the locations because the invalid access is first and both instructions use the same !dbg; add a valid outer access and invalid inner access with distinct locations.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

maxskokov added a commit to cpp-bpf/cpp-bpf that referenced this pull request Oct 20, 2026
Released clang crashes or emits wrong BTF on C++ classes, so users need
clang with llvm/llvm-project#233715 until it is merged. Move the build
from the CI action into scripts/build-clang.sh, so that users get the
same clang as CI, and key the CI cache on the script.

Signed-off-by: Maxim Skokov <[email protected]>
@llvmorg-github-actions llvmorg-github-actions Bot added the clang:codegen IR generation bugs: mangling, exceptions, etc. label Oct 20, 2026
@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-clang-codegen

Author: Maxim Skokov (maxskokov)

Changes

Combines #226717 and #226723, as asked in #226717; follow-up to #226790.

Since #155783 (LLVM 22.1), compiling C++ for BPF with -g hits llvm_unreachable() in BTF emission as soon as a record has a base class, a static data member (DWARF 5) or a method, or is declared with class; #205396 moved the first crash into the offset sort:

struct S { void *p; ~S(); };
long f(S *s) { return (long)s-&gt;p; }

A C++ record lists bases, static members and methods among its debug info elements next to its data members, and a record declared with class has DW_TAG_class_type, which the backend did not handle. The CO-RE pass and visitMapDefType() walk the same elements and crash too.

BTF. A non-virtual base becomes an anonymous member of the base type at its offset, as pahole encodes inheritance; virtual bases, static data members and methods are skipped. A class is emitted as a struct (before #155783 it was type 0).

CO-RE. Since #226790 the DI index of a CO-RE access is an index into the record's debug info elements. The backend takes that element and maps it to its position among the BTF members, built from the same ordered list as BTF, so bases, static members and methods no longer shift the access string. For an inherited field, only its position within the base is relocated. An index that does not refer to a data member, e.g. into a record the debug info only declares, is reported as an error at the access instead of crashing. A class is relocated like a struct; before, an access into a class got offset 0.

Testing

BTF with single and multiple inheritance, an empty base, a method and a static data member, loaded with BPF_BTF_LOAD on Linux 6.12:

compiler base class in BTF kernel
clang 19 member with type_id=0 rejected: "Invalid type_id"
22.1–main (from the source) — llvm_unreachable(): crash with assertions, UB without
this PR anonymous member of the base type accepted

CO-RE; clang 19 with -fstandalone-debug (with plain -g it segfaults on V), the other columns the same with -g and -g -fstandalone-debug:

access clang 19 main this PR
struct S : Base { int x, y; }, &amp;s-&gt;y offset 4, 0:1 (that is x) crash offset 8, 0:2
struct V : virtual Base { int v; }, &amp;v-&gt;v offset 3, 0:0 crash offset 8, 0:1
class C { public: int x, y; }, &amp;c-&gt;y offset 0 crash offset 4

New tests cover these cases, a class and a declared-only class as STRUCT and FWD, a map definition declared as a class, and a bit-field in a class; they fail on main. The kernel BPF selftests (1060 C programs) compile to identical code and .BTF.ext, and to .BTF with the same content; in 25 of them the types come in a different order, as FWD order is not stable between clang builds.

Known limitations

  • bpftool btf dump format c prints an anonymous base member as struct Base;, which only keeps the layout with -fms-extensions and cannot express an empty base overlapping a field. BTF from pahole has the same shape.
  • Classes with a vtable are still rejected by the kernel, as _vptr$X is not a valid BTF name.

This fixes a crash that is a regression since 22.1 (#155783); once this lands I'd like to request a backport to 23.x together with #226790.

Assisted-by: Claude Code (Claude Opus 5.5)


Patch is 61.37 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/233715.diff

11 Files Affected:

  • (modified) clang/lib/CodeGen/CGClass.cpp (+8)
  • (added) clang/test/CodeGenCXX/builtin-preserve-access-index-base.cpp (+36)
  • (modified) llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp (+69-19)
  • (modified) llvm/lib/Target/BPF/BPFCORE.h (+40)
  • (modified) llvm/lib/Target/BPF/BTFDebug.cpp (+40-27)
  • (added) llvm/test/CodeGen/BPF/BTF/class-type.ll (+80)
  • (added) llvm/test/CodeGen/BPF/BTF/cxx-reference-template.ll (+156)
  • (added) llvm/test/CodeGen/BPF/BTF/struct-cxx-elements.ll (+142)
  • (added) llvm/test/CodeGen/BPF/CORE/class-type.ll (+44)
  • (added) llvm/test/CodeGen/BPF/CORE/struct-cxx-fields.ll (+168)
  • (added) llvm/test/CodeGen/BPF/CORE/struct-cxx-fwd-decl.ll (+105)
diff --git a/clang/lib/CodeGen/CGClass.cpp b/clang/lib/CodeGen/CGClass.cpp
index 2901233638ffe..6f99908aee8f5 100644
--- a/clang/lib/CodeGen/CGClass.cpp
+++ b/clang/lib/CodeGen/CGClass.cpp
@@ -315,6 +315,14 @@ Address CodeGenFunction::GetAddressOfBaseClass(
     VBase = nullptr; // we no longer have a virtual step
   }
 
+  // A CO-RE relocation is relative to the record that has the field, so the
+  // offset of its base subobject would not be relocated.
+  if (IsInPreservedAIRegion && (VBase || !NonVirtualOffset.isZero())) {
+    CGM.Error(Loc, "CO-RE access through a virtual base or a base at a "
+                   "non-zero offset not supported");
+    return Value.withElementType(ConvertType((PathEnd[-1])->getType()));
+  }
+
   // Get the base pointer type.
   llvm::Type *BaseValueTy = ConvertType((PathEnd[-1])->getType());
   llvm::Type *PtrTy = llvm::PointerType::get(
diff --git a/clang/test/CodeGenCXX/builtin-preserve-access-index-base.cpp b/clang/test/CodeGenCXX/builtin-preserve-access-index-base.cpp
new file mode 100644
index 0000000000000..cf4b855a9a796
--- /dev/null
+++ b/clang/test/CodeGenCXX/builtin-preserve-access-index-base.cpp
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 -triple bpfel -emit-llvm -debug-info-kind=limited -verify=ok %s -o /dev/null
+// RUN: %clang_cc1 -triple bpfel -emit-llvm -debug-info-kind=limited -verify -DSECOND_BASE %s -o /dev/null
+// RUN: %clang_cc1 -triple bpfel -emit-llvm -debug-info-kind=limited -verify -DVIRTUAL_BASE %s -o /dev/null
+
+// ok-no-diagnostics
+
+// A CO-RE relocation is relative to the record that has the field, so an
+// access through a base class must not need the offset of that base.
+
+struct A { int a; };
+struct B { int b; };
+struct D : A, B { int d; };
+struct V : virtual A { int v; };
+
+unsigned long first_base(D *p) {
+  return (unsigned long)__builtin_preserve_access_index(&p->a);
+}
+
+unsigned long own_field(D *p, V *q) {
+  return (unsigned long)__builtin_preserve_access_index(&p->d) +
+         __builtin_preserve_field_info(q->v, 0);
+}
+
+int outside(D *p, V *q) { return p->b + q->a; }
+
+#ifdef SECOND_BASE
+unsigned long second_base(D *p) {
+  return (unsigned long)__builtin_preserve_access_index(&p->b); // expected-error {{CO-RE access through a virtual base or a base at a non-zero offset not supported}}
+}
+#endif
+
+#ifdef VIRTUAL_BASE
+unsigned virtual_base(V *p) {
+  return __builtin_preserve_field_info(p->a, 0); // expected-error {{CO-RE access through a virtual base or a base at a non-zero offset not supported}}
+}
+#endif
diff --git a/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp b/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
index f5410820bfb49..2c89de026c53f 100644
--- a/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
+++ b/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
@@ -82,6 +82,7 @@
 #include "llvm/BinaryFormat/Dwarf.h"
 #include "llvm/DebugInfo/BTF/BTF.h"
 #include "llvm/IR/DebugInfoMetadata.h"
+#include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/Instructions.h"
@@ -298,6 +299,44 @@ static const DIType * stripQualifiers(const DIType *Ty) {
   return Ty;
 }
 
+/// Return the field that a CO-RE access index, an index into the record's DI
+/// elements, refers to, or null if that element is not a data member.
+static DIDerivedType *getDIRecordField(const DICompositeType *CTy,
+                                       uint64_t AccessIndex) {
+  DINodeArray Elements = CTy->getElements();
+  if (AccessIndex >= Elements.size())
+    return nullptr;
+  auto *Field = dyn_cast<DIDerivedType>(Elements[AccessIndex]);
+  if (!Field || Field->getTag() != dwarf::DW_TAG_member ||
+      Field->isStaticMember())
+    return nullptr;
+  return Field;
+}
+
+/// Return the position of the element at DI index AccessIndex among the BTF
+/// members of record CTy, ordered as getBTFRecordElements() orders them,
+/// without building that list for every access.
+static uint64_t getBTFMemberIndex(const DICompositeType *CTy,
+                                  uint64_t AccessIndex) {
+  DINodeArray Elements = CTy->getElements();
+  bool IsStruct = isStructTag(CTy->getTag());
+  uint64_t Offset = getBTFRecordElementOffset(Elements[AccessIndex]);
+  uint64_t BTFIndex = 0;
+  for (unsigned I = 0; I < Elements.size(); ++I) {
+    if (!isBTFRecordElement(Elements[I]))
+      continue;
+    // Union members keep their DI order, struct members are stably sorted by
+    // offset.
+    bool Before = I < AccessIndex;
+    if (IsStruct) {
+      uint64_t ElementOffset = getBTFRecordElementOffset(Elements[I]);
+      Before = ElementOffset < Offset || (ElementOffset == Offset && Before);
+    }
+    BTFIndex += Before;
+  }
+  return BTFIndex;
+}
+
 static uint32_t calcArraySize(const DICompositeType *CTy, uint32_t StartDim) {
   DINodeArray Elements = CTy->getElements();
   uint32_t DimSize = 1;
@@ -511,13 +550,11 @@ bool BPFAbstractMemberAccess::IsValidAIChain(const MDNode *ParentType,
   assert(PTy && CTy && "ParentType or ChildType is null or not composite");
 
   uint32_t PTyTag = PTy->getTag();
-  assert(PTyTag == dwarf::DW_TAG_array_type ||
-         PTyTag == dwarf::DW_TAG_structure_type ||
+  assert(PTyTag == dwarf::DW_TAG_array_type || isStructTag(PTyTag) ||
          PTyTag == dwarf::DW_TAG_union_type);
 
   uint32_t CTyTag = CTy->getTag();
-  assert(CTyTag == dwarf::DW_TAG_array_type ||
-         CTyTag == dwarf::DW_TAG_structure_type ||
+  assert(CTyTag == dwarf::DW_TAG_array_type || isStructTag(CTyTag) ||
          CTyTag == dwarf::DW_TAG_union_type);
 
   // Multi dimensional arrays, base element should be the same
@@ -528,7 +565,9 @@ bool BPFAbstractMemberAccess::IsValidAIChain(const MDNode *ParentType,
   if (PTyTag == dwarf::DW_TAG_array_type)
     Ty = PTy->getBaseType();
   else
-    Ty = dyn_cast<DIType>(PTy->getElements()[ParentAI]);
+    Ty = getDIRecordField(PTy, ParentAI);
+  if (!Ty)
+    return false;
 
   return dyn_cast<DICompositeType>(stripQualifiers(Ty)) == CTy;
 }
@@ -684,7 +723,7 @@ uint32_t BPFAbstractMemberAccess::GetFieldInfo(uint32_t InfoKind,
       auto *EltTy = stripQualifiers(CTy->getBaseType());
       PatchImm += AccessIndex * calcArraySize(CTy, 1) *
                   (EltTy->getSizeInBits() >> 3);
-    } else if (Tag == dwarf::DW_TAG_structure_type) {
+    } else if (isStructTag(Tag)) {
       auto *MemberTy = cast<DIDerivedType>(CTy->getElements()[AccessIndex]);
       if (!MemberTy->isBitField()) {
         PatchImm += MemberTy->getOffsetInBits() >> 3;
@@ -919,7 +958,7 @@ Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
       }
 
       unsigned CTag = CTy->getTag();
-      if (CTag == dwarf::DW_TAG_structure_type || CTag == dwarf::DW_TAG_union_type) {
+      if (isStructTag(CTag) || CTag == dwarf::DW_TAG_union_type) {
         TypeName = std::string(CTy->getName());
       } else {
         if (HasPreserveFieldInfoCall(CallStack))
@@ -938,6 +977,7 @@ Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
   // and access key construction.
   while (CallStack.size()) {
     auto StackElem = CallStack.top();
+    Call = StackElem.first;
     CInfo = StackElem.second;
     CallStack.pop();
 
@@ -965,19 +1005,21 @@ Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
     // At this stage, it cannot be pointer type.
     auto *CTy = cast<DICompositeType>(stripQualifiers(cast<DIType>(MDN)));
 
+    // For a record, use the position of the field among its BTF members, and
+    // use an array index as is.
     uint64_t BTFIndex = AccessIndex;
-    if (CTy->getTag() == dwarf::DW_TAG_structure_type) {
-      DINodeArray Elements = CTy->getElements();
-      uint64_t Offset = getBTFRecordElementOffset(Elements[AccessIndex]);
-      // Find this element's position in the stable offset order without
-      // sorting the whole record for every CO-RE access.
-      BTFIndex = 0;
-      for (unsigned I = 0; I < Elements.size(); ++I) {
-        uint64_t ElementOffset = getBTFRecordElementOffset(Elements[I]);
-        if (ElementOffset < Offset ||
-            (ElementOffset == Offset && I < AccessIndex))
-          ++BTFIndex;
+    if (isStructTag(CTy->getTag()) ||
+        CTy->getTag() == dwarf::DW_TAG_union_type) {
+      if (!getDIRecordField(CTy, AccessIndex)) {
+        Call->getContext().diagnose(DiagnosticInfoUnsupported(
+            *Call->getFunction(),
+            "CO-RE access index " + Twine(AccessIndex) +
+                " does not refer to a field of '" + CTy->getName() +
+                "' in the debug info",
+            Call->getDebugLoc()));
+        return nullptr;
       }
+      BTFIndex = getBTFMemberIndex(CTy, AccessIndex);
     }
     AccessKey += ":" + std::to_string(BTFIndex);
 
@@ -1074,8 +1116,16 @@ bool BPFAbstractMemberAccess::transformGEPChain(CallInst *Call,
     TypeMeta = computeAccessKey(Call, CInfo, AccessKey, IsInt32Ret);
   } else {
     Base = computeBaseAndAccessKey(Call, CInfo, AccessKey, TypeMeta);
-    if (!Base)
+    if (!Base) {
+      // For a field info call, computeBaseAndAccessKey() only gives up after
+      // reporting an error, so the value of the call does not matter.
+      if (IsInt32Ret) {
+        Call->replaceAllUsesWith(ConstantInt::get(Call->getType(), 0));
+        Call->eraseFromParent();
+        return true;
+      }
       return false;
+    }
   }
 
   BasicBlock *BB = Call->getParent();
diff --git a/llvm/lib/Target/BPF/BPFCORE.h b/llvm/lib/Target/BPF/BPFCORE.h
index 5aa7695c0ecad..0528a20e9b275 100644
--- a/llvm/lib/Target/BPF/BPFCORE.h
+++ b/llvm/lib/Target/BPF/BPFCORE.h
@@ -9,6 +9,8 @@
 #ifndef LLVM_LIB_TARGET_BPF_BPFCORE_H
 #define LLVM_LIB_TARGET_BPF_BPFCORE_H
 
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/BinaryFormat/Dwarf.h"
 #include "llvm/IR/DebugInfoMetadata.h"
@@ -21,10 +23,33 @@ class BasicBlock;
 class Instruction;
 class Module;
 
+/// Whether a record element becomes a BTF member: data members, variant parts
+/// and non-virtual C++ bases, the latter as anonymous members. Virtual bases
+/// have no fixed offset.
+inline bool isBTFRecordElement(const DINode *Element) {
+  switch (Element->getTag()) {
+  case dwarf::DW_TAG_member:
+    return !cast<DIDerivedType>(Element)->isStaticMember();
+  case dwarf::DW_TAG_inheritance:
+    return !cast<DIDerivedType>(Element)->isVirtual();
+  case dwarf::DW_TAG_variant_part:
+    return true;
+  default:
+    return false;
+  }
+}
+
+/// Whether a debug info tag describes a record that BTF represents as a
+/// struct. A C++ record declared with the class keyword is one as well.
+inline bool isStructTag(unsigned Tag) {
+  return Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_class_type;
+}
+
 /// Return the bit offset used to order an element of a BTF structure record.
 inline uint64_t getBTFRecordElementOffset(const DINode *Element) {
   switch (Element->getTag()) {
   case dwarf::DW_TAG_member:
+  case dwarf::DW_TAG_inheritance:
     return cast<DIDerivedType>(Element)->getOffsetInBits();
   case dwarf::DW_TAG_variant_part:
     return cast<DICompositeType>(Element)->getOffsetInBits();
@@ -33,6 +58,21 @@ inline uint64_t getBTFRecordElementOffset(const DINode *Element) {
   }
 }
 
+/// Return the BTF members of a record in BTF order: structure members by
+/// offset (BTF requires nondecreasing offsets), stable for equal offsets.
+inline SmallVector<const DINode *, 8>
+getBTFRecordElements(const DICompositeType *CTy) {
+  SmallVector<const DINode *, 8> Elements;
+  for (const DINode *Element : CTy->getElements())
+    if (isBTFRecordElement(Element))
+      Elements.push_back(Element);
+  if (isStructTag(CTy->getTag()))
+    llvm::stable_sort(Elements, [](const DINode *LHS, const DINode *RHS) {
+      return getBTFRecordElementOffset(LHS) < getBTFRecordElementOffset(RHS);
+    });
+  return Elements;
+}
+
 class BPFCoreSharedInfo {
 public:
   enum BTFTypeIdFlag : uint32_t {
diff --git a/llvm/lib/Target/BPF/BTFDebug.cpp b/llvm/lib/Target/BPF/BTFDebug.cpp
index 7ddeedb838e87..bc5d271f235a9 100644
--- a/llvm/lib/Target/BPF/BTFDebug.cpp
+++ b/llvm/lib/Target/BPF/BTFDebug.cpp
@@ -252,6 +252,13 @@ static bool canUseNocallOptimizedSignature(
   return true;
 }
 
+/// Return the BTF name of a type. Released kernels only accept identifiers as
+/// type names, so a C++ template specialization is named without its template
+/// arguments, as with -gsimple-template-names.
+static StringRef getBTFTypeName(StringRef Name) {
+  return Name.take_front(Name.find('<'));
+}
+
 /// Emit a BTF common type.
 void BTFTypeBase::emitType(MCStreamer &OS) {
   OS.AddComment(std::string(BTFKindStr[Kind]) + "(id = " + std::to_string(Id) +
@@ -264,7 +271,7 @@ void BTFTypeBase::emitType(MCStreamer &OS) {
 
 BTFTypeDerived::BTFTypeDerived(const DIDerivedType *DTy, unsigned Tag,
                                bool NeedsFixup)
-    : DTy(DTy), NeedsFixup(NeedsFixup), Name(DTy->getName()) {
+    : DTy(DTy), NeedsFixup(NeedsFixup), Name(getBTFTypeName(DTy->getName())) {
   switch (Tag) {
   case dwarf::DW_TAG_pointer_type:
     Kind = BTF::BTF_KIND_PTR;
@@ -352,7 +359,8 @@ void BTFTypeDerived::setPointeeType(uint32_t PointeeType) {
 }
 
 /// Represent a struct/union forward declaration.
-BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion) : Name(Name) {
+BTFTypeFwd::BTFTypeFwd(StringRef Name, bool IsUnion)
+    : Name(getBTFTypeName(Name)) {
   Kind = BTF::BTF_KIND_FWD;
   BTFType.Info = IsUnion << 31 | Kind << 24;
   BTFType.Type = 0;
@@ -422,7 +430,7 @@ void BTFTypeEnum::completeType(BTFDebug &BDebug) {
     return;
   IsCompleted = true;
 
-  BTFType.NameOff = BDebug.addString(ETy->getName());
+  BTFType.NameOff = BDebug.addString(getBTFTypeName(ETy->getName()));
 
   DINodeArray Elements = ETy->getElements();
   for (const auto Element : Elements) {
@@ -461,7 +469,7 @@ void BTFTypeEnum64::completeType(BTFDebug &BDebug) {
     return;
   IsCompleted = true;
 
-  BTFType.NameOff = BDebug.addString(ETy->getName());
+  BTFType.NameOff = BDebug.addString(getBTFTypeName(ETy->getName()));
 
   DINodeArray Elements = ETy->getElements();
   for (const auto Element : Elements) {
@@ -537,7 +545,7 @@ void BTFTypeStruct::completeType(BTFDebug &BDebug) {
     return;
   IsCompleted = true;
 
-  BTFType.NameOff = BDebug.addString(STy->getName());
+  BTFType.NameOff = BDebug.addString(getBTFTypeName(STy->getName()));
 
   if (STy->getTag() == dwarf::DW_TAG_variant_part) {
     // Variant parts might have a discriminator, which has its own memory
@@ -566,7 +574,8 @@ void BTFTypeStruct::completeType(BTFDebug &BDebug) {
     struct BTF::BTFMember BTFMember;
 
     switch (Element->getTag()) {
-    case dwarf::DW_TAG_member: {
+    case dwarf::DW_TAG_member:
+    case dwarf::DW_TAG_inheritance: {
       const auto *DDTy = cast<DIDerivedType>(Element);
 
       BTFMember.NameOff = BDebug.addString(DDTy->getName());
@@ -976,14 +985,7 @@ int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
 /// Handle structure/union types.
 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
                                uint32_t &TypeId) {
-  DINodeArray DIElements = CTy->getElements();
-  SmallVector<const DINode *, 8> Elements(DIElements.begin(), DIElements.end());
-  // Structure elements must have nondecreasing offsets in BTF. Preserve DI
-  // order for union and variant-part records.
-  if (CTy->getTag() == dwarf::DW_TAG_structure_type)
-    llvm::stable_sort(Elements, [](const DINode *LHS, const DINode *RHS) {
-      return getBTFRecordElementOffset(LHS) < getBTFRecordElementOffset(RHS);
-    });
+  SmallVector<const DINode *, 8> Elements = getBTFRecordElements(CTy);
   uint32_t VLen = Elements.size();
   // Variant parts might have a discriminator. LLVM DI doesn't consider it as
   // an element and instead keeps it as a separate reference. But we represent
@@ -1022,7 +1024,8 @@ void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
   int FieldNo = 0;
   for (const auto *Element : Elements) {
     switch (Element->getTag()) {
-    case dwarf::DW_TAG_member: {
+    case dwarf::DW_TAG_member:
+    case dwarf::DW_TAG_inheritance: {
       const auto Elem = cast<DIDerivedType>(Element);
       visitTypeEntry(Elem);
       processDeclAnnotations(Elem->getAnnotations(), TypeId, FieldNo);
@@ -1127,13 +1130,14 @@ void BTFDebug::visitCompositeType(const DICompositeType *CTy,
   auto Tag = CTy->getTag();
   switch (Tag) {
   case dwarf::DW_TAG_structure_type:
+  case dwarf::DW_TAG_class_type:
   case dwarf::DW_TAG_union_type:
   case dwarf::DW_TAG_variant_part:
     // Handle forward declaration differently as it does not have members.
     if (CTy->isForwardDecl())
       visitFwdDeclType(CTy, Tag == dwarf::DW_TAG_union_type, TypeId);
     else
-      visitStructType(CTy, Tag == dwarf::DW_TAG_structure_type, TypeId);
+      visitStructType(CTy, isStructTag(Tag), TypeId);
     break;
   case dwarf::DW_TAG_array_type:
     visitArrayType(CTy, TypeId);
@@ -1149,18 +1153,22 @@ void BTFDebug::visitCompositeType(const DICompositeType *CTy,
 bool BTFDebug::IsForwardDeclCandidate(const DIType *Base) {
   if (const auto *CTy = dyn_cast<DICompositeType>(Base)) {
     auto CTag = CTy->getTag();
-    if ((CTag == dwarf::DW_TAG_structure_type ||
-         CTag == dwarf::DW_TAG_union_type) &&
+    if ((isStructTag(CTag) || CTag == dwarf::DW_TAG_union_type) &&
         !CTy->getName().empty() && !CTy->isForwardDecl())
       return true;
   }
   return false;
 }
 
-/// Handle pointer, typedef, const, volatile, restrict and member types.
+/// Handle pointer, reference, typedef, const, volatile, restrict and member
+/// types.
 void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
                                 bool CheckPointer, bool SeenPointer) {
   unsigned Tag = DTy->getTag();
+  // BTF has no references; a C++ reference is represented as a pointer.
+  if (Tag == dwarf::DW_TAG_reference_type ||
+      Tag == dwarf::DW_TAG_rvalue_reference_type)
+    Tag = dwarf::DW_TAG_pointer_type;
 
   if (Tag == dwarf::DW_TAG_atomic_type)
     return visitTypeEntry(DTy->getBaseType(), TypeId, CheckPointer,
@@ -1191,8 +1199,8 @@ void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
   if (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_typedef) {
     int TmpTypeId = genBTFTypeTags(DTy, -1);
     if (TmpTypeId >= 0) {
-      auto TypeDEntry =
-          std::make_unique<BTFTypeDerived>(TmpTypeId, Tag, DTy->getName());
+      auto TypeDEntry = std::make_unique<BTFTypeDerived>(
+          TmpTypeId, Tag, getBTFTypeName(DTy->getName()));
       TypeId = addType(std::move(TypeDEntry), DTy);
     } else {
       auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
@@ -1205,14 +1213,14 @@ void BTFDebug::visitDerivedType(const DIDerivedType *DTy, uint32_t &TypeId,
              Tag == dwarf::DW_TAG_restrict_type) {
     auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
     TypeId = addType(std::move(TypeEntry), DTy);
-  } else if (Tag != dwarf::DW_TAG_member) {
+  } else if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_inheritance) {
     return;
   }
 
-  // Visit base type of pointer, typedef, const, volatile, restrict or
-  // struct/union member.
+  // Visit base type of pointer, typedef, const, volatile, restrict, or
+  // struct/union member or base class.
   uint32_t TempTypeId = 0;
-  if (Tag == dwarf::DW_TAG_member)
+  if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_inheritance)
     visitTypeEntry(DTy->getBaseType(), TempTypeId, true, false);
   else
     visitTypeEntry(DTy->getBaseType(), TempTypeId, CheckPointer, SeenPointer);
@@ -1323,12 +1331,17 @@ void BTFDebug::visitMapDefType(const DIType *Ty, uint32_t &TypeId) {
     // Visit nested map array and jump to the element type
     visitMapDefType(dyn_cast<DICompositeType>(Ty)->getBaseType(), TmpId);
     break;
-  case dwarf::DW_TAG_structure_type: {
+  case dwarf::DW_TAG_structure_type:
+  case dwarf::DW_TAG_class_type: {
     // Visit all struct members to ensure their types are visited.
     const auto *CTy = cast<DICompositeType>(Ty);
     const DINodeArray Elements = CTy->getElements();
     for (const auto *Element : Elements) {
-      const auto *MemberType = cast<DIDerivedType>(Element);
+      // Static data members, metho...
[truncated]

@maxskokov
maxskokov requested a review from tamird October 20, 2026 16:18

@tamird tamird left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of b9494ec.

Validation: git diff --check passed. No current-head build or behavioral tests were run.

Assisted-by: OpenAI Codex, with delegated review agents.

struct V : virtual A { int v; };

unsigned long first_base(D *p) {
return (unsigned long)__builtin_preserve_access_index(&p->a);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This accepted access still has the original wrong-address failure. In the local D : A, B layout, A is at offset 0; in a target D : B, A layout it can be at offset 4. The relocation is rooted at A, so it never relocates the D-to-A step and can still read the bytes at offset 0. Please relocate the base adjustment or reject inherited accesses even when the local base offset is zero; this test should distinguish that case.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. Any CO-RE access through a base class is now rejected, also at offset 0, and the test covers the first base.

Comment thread clang/lib/CodeGen/CGClass.cpp Outdated

// A CO-RE relocation is relative to the record that has the field, so the
// offset of its base subobject would not be relocated.
if (IsInPreservedAIRegion && (VBase || !NonVirtualOffset.isZero())) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This BPF CO-RE restriction is in target-independent C++ codegen. __builtin_preserve_access_index is also supported on x86_64 (see the existing clang/test/CodeGenCXX/builtin-preserve-access-index.cpp run line), so the new check rejects non-BPF preserved accesses through a nonzero or virtual base too. Please confine the restriction to the target or consumer that requires it and cover the non-BPF path.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now only on BPF; the test has an x86_64 run where these accesses still compile.

Comment thread llvm/lib/Target/BPF/BTFDebug.cpp Outdated
/// Return the BTF name of a type. Released kernels only accept identifiers as
/// type names, so a C++ template specialization is named without its template
/// arguments, as with -gsimple-template-names.
static StringRef getBTFTypeName(StringRef Name) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Template CO-RE accesses can still terminate compilation before this emitted-name transformation helps. Clang produces names such as ClassTemplateInlineNamespaceArg<inl::t1> (clang/test/DebugInfo/CXX/template.cpp); a preserved field access embeds that raw DI name in the temporary relocation global. generatePatchImmReloc() then treats the two colons in inl::t1 as its numeric delimiters and calls std::stoull(":"). Please make the relocation-key producer and consumer robust to valid DI names, and add an end-to-end CO-RE test with a qualified template argument.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This crashes released clang too: clang 21 terminates with std::invalid_argument from stoull on the same input, so it isn't from this PR. I'd like to keep this PR to the crash fix I want to backport to 23.x, and handle CO-RE on template specializations (this and the type identity) in a follow-up: #233947.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed that the qualified-name parser crash predates this patch; it can be handled in #233947.

; CHECK-NEXT: 'v' type_id=3 bits_offset=0
; CHECK-NEXT: [3] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
; CHECK-NEXT: [4] PTR '(anon)' type_id=5
; CHECK-NEXT: [5] STRUCT 'TC' size=8 vlen=1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The duplicate TC names here erase the identity CO-RE needs. For template<class T> struct TC { T value; int next; };, TC<int> and TC<long> become the same target name but place next at different offsets. libbpf collects candidates by essential name and rejects conflicting field offsets, so a target containing both specializations makes the relocation ambiguous. Please preserve distinct type identity in a valid BTF representation, or diagnose unsupported template CO-RE use.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, a shared name loses the identity CO-RE needs. That's the same follow-up, #233947: diagnose or support CO-RE on template specializations. The names here make the BTF loadable, and for maps and globals a shared name is fine.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name rewrite itself is introduced by this PR. The kernel change you cited documents LLVM-emitted Rust STRUCT 'NonNull<str>' and extends kernel support for such names; unconditional truncation changes that existing name to NonNull and can break name-based consumers outside C++ too. Please leave name rewriting to #233947, or preserve existing names and distinct specialization identity here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the name rewrite is gone; template names are left to #233947.

auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
TypeId = addType(std::move(TypeEntry), DTy);
} else if (Tag != dwarf::DW_TAG_member) {
} else if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_inheritance) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another legal C++ member type still reaches this silent return: class C { public: int x; int C::*pm; }; C c; produces DW_TAG_ptr_to_member_type. The type is not registered, but BTFTypeStruct::completeType() later asks getTypeId() for it, asserting in an assertions-enabled build or emitting type ID 0 otherwise. Please represent it or diagnose unsupported member types before completing the record.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also there before this PR: clang 21 crashes on the same class. I'd handle it in a follow-up with a representation or a diagnostic instead of type 0: #233948.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: the unsupported member-pointer input predates this patch and is tracked in #233948, so it need not block this regression fix.

if (AccessIndex >= Elements.size())
return nullptr;
auto *Field = dyn_cast<DIDerivedType>(Elements[AccessIndex]);
if (!Field || Field->getTag() != dwarf::DW_TAG_member ||

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please retain the DW_TAG_member restriction but use isBTFRecordElement(Field) for BTF eligibility. This repeats the shared predicate's non-static-member rule, while the rank calculation filters through that predicate. If the rules diverge, CO-RE can compute a rank for a field BTF does not emit.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

bool IsStruct = isStructTag(CTy->getTag());
uint64_t Offset = getBTFRecordElementOffset(Elements[AccessIndex]);
uint64_t BTFIndex = 0;
for (unsigned I = 0; I < Elements.size(); ++I) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sort is gone, but union accesses still scan the entire record even when the selected member is first, and compute an offset they never use. For a union, only eligible elements before AccessIndex can contribute to its BTF rank. Please limit the union path to that prefix and reserve the full offset comparison for structs/classes.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread llvm/lib/Target/BPF/BPFCORE.h Outdated

/// Whether a debug info tag describes a record that BTF represents as a
/// struct. A C++ record declared with the class keyword is one as well.
inline bool isStructTag(unsigned Tag) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please name this for the representation it tests, e.g. isBTFStructTag. It accepts both DWARF structure and class tags because both become BTF structs; isStructTag obscures that distinction at its call sites and differs from the neighboring BTF helper names.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread llvm/lib/Target/BPF/BPFCORE.h Outdated
/// Return the BTF members of a record in BTF order: structure members by
/// offset (BTF requires nondecreasing offsets), stable for equal offsets.
inline SmallVector<const DINode *, 8>
getBTFRecordElements(const DICompositeType *CTy) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getBTFRecordElements() now has only one caller, in BTFDebug.cpp. Please keep the list-building and sorting implementation local to that file, leaving the shared eligibility and offset primitives in this header. That restricts visibility and removes the new ADT dependencies from the shared header.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread llvm/lib/Target/BPF/BTFDebug.cpp Outdated
auto TypeDEntry =
std::make_unique<BTFTypeDerived>(TmpTypeId, Tag, DTy->getName());
auto TypeDEntry = std::make_unique<BTFTypeDerived>(
TmpTypeId, Tag, getBTFTypeName(DTy->getName()));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If type-name rewriting remains, please apply it at the named-type serialization boundary. One BTFTypeDerived constructor rewrites its name internally, while this constructor relies on its caller to do so; pointer and qualified kinds subsequently discard their names. Centralizing the conversion when completeType() adds the name removes that split responsibility. Preserve raw DI names wherever they are still used for type identity or fixups.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@maxskokov

Copy link
Copy Markdown
Author

Thanks! 1d5d3fb addresses the comments on what this PR changes. Pointers to members and CO-RE on template specializations fail the same way in clang 21, so I'd like to keep them out of this PR, which fixes a 22.1 regression I'd like to backport, and handle them in follow-ups: #233947, #233948. @yonghong-song, does that scope work for you?

@maxskokov
maxskokov requested a review from tamird October 20, 2026 18:40

@tamird tamird left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 1d5d3fb.

Validation: git diff --check passed. No build or behavioral tests were run at this head.

Assisted-by: OpenAI Codex, with delegated review agents.

Comment thread clang/lib/CodeGen/CGClass.cpp Outdated
// A BPF CO-RE relocation is relative to the record that has the field, so
// the offset of the base subobject, which may differ in the target, would not
// be relocated.
if (IsInPreservedAIRegion && getTarget().getTriple().isBPF()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rejection needs to track base adjustments on the preserved address path. It misses the inverse conversion: for struct A { int a; }; struct B { int b; }; struct D : A, B { int x; };, __builtin_preserve_access_index(&static_cast<D *>(p)->x) with B *p hardcodes the local B-to-D adjustment of -4 in GetAddressOfDerivedClass(). If the target changes to D : B, A, B moves to offset 0 while x stays at offset 8; the D-rooted relocation still yields an address four bytes short. The same guard also rejects __builtin_preserve_access_index((consume(d), &d->x)) for D *d and void consume(A *), even though the upcast belongs only to the side-effect call. Please reject or relocate base adjustments that contribute to the preserved address, while allowing unrelated conversions.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: the check now walks the address expression of the builtin and reports a conversion between a class and its base, in either direction, on that path. So the downcast is reported and the upcast in the side-effect operand is not; both are in the test, and the check moved out of GetAddressOfBaseClass().

Comment thread llvm/lib/Target/BPF/BTFDebug.cpp Outdated

/// Whether a DI derived type tag becomes a BTF pointer: a pointer, or a C++
/// reference, which BTF has no kind for.
static bool isBTFPointerTag(unsigned Tag) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please apply the same pointer-like rule in sourceArgMatchesIRType(). Dead-argument elimination can retain a C++ reference as an IR pointer while the source debug type remains a reference and the signature is marked DW_CC_nocall. The raw pointer-tag check rejects that pair, so the fallback serializes eliminated source arguments into the BTF function prototype. That prototype disagrees with the actual optimized ABI. Extend the matcher and cover a surviving reference parameter.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, with a test where a reference parameter survives dead-argument elimination; without the change the prototype keeps all three source arguments.

!45 = !DIDerivedType(tag: DW_TAG_member, name: "x", scope: !39, file: !1, line: 5, baseType: !14, size: 32, offset: 128)
!46 = !DIDerivedType(tag: DW_TAG_member, name: "b1", scope: !39, file: !1, line: 5, baseType: !47, size: 64, offset: 192)
!47 = !DIDerivedType(tag: DW_TAG_reference_type, baseType: !48, size: 64)
!48 = !DICompositeType(tag: DW_TAG_structure_type, name: "Big", file: !1, line: 4, size: 128, flags: DIFlagFwdDecl, identifier: "_ZTS3Big")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Big is already a forward declaration in the input, which explains why the first visit registers it and the second bypasses the changed pruning check. IsForwardDeclCandidate() requires a complete DI type, so this FWD assertion cannot distinguish the old raw-pointer check from the new reference-aware check. Please give Big a complete debug definition reachable only through the shared reference node, and retain the expected emitted BTF FWD; -fstandalone-debug can preserve such a complete producer definition.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that was it. The test (now cxx-reference.ll) is built with -fstandalone-debug, and without the visitTypeEntry() change Big becomes a full STRUCT.

Comment thread llvm/lib/Target/BPF/BTFDebug.cpp Outdated
/// Return the BTF name of a type. Released kernels only accept identifiers as
/// type names, so a C++ template specialization is named without its template
/// arguments, as with -gsimple-template-names.
static StringRef getBTFTypeName(StringRef Name) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed that the qualified-name parser crash predates this patch; it can be handled in #233947.

; CHECK-NEXT: 'v' type_id=3 bits_offset=0
; CHECK-NEXT: [3] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
; CHECK-NEXT: [4] PTR '(anon)' type_id=5
; CHECK-NEXT: [5] STRUCT 'TC' size=8 vlen=1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name rewrite itself is introduced by this PR. The kernel change you cited documents LLVM-emitted Rust STRUCT 'NonNull<str>' and extends kernel support for such names; unconditional truncation changes that existing name to NonNull and can break name-based consumers outside C++ too. Please leave name rewriting to #233947, or preserve existing names and distinct specialization identity here.

auto TypeEntry = std::make_unique<BTFTypeDerived>(DTy, Tag, false);
TypeId = addType(std::move(TypeEntry), DTy);
} else if (Tag != dwarf::DW_TAG_member) {
} else if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_inheritance) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: the unsupported member-pointer input predates this patch and is tracked in #233948, so it need not block this regression fix.

@maxskokov
maxskokov requested a review from tamird October 20, 2026 19:25
Comment thread llvm/lib/Target/BPF/BTFDebug.cpp Resolved
A C++ record lists base classes, static data members and methods among
its debug info elements. Since llvm#155783, BTF emission hits
llvm_unreachable() on any record element other than a member or a
variant part, and llvm#205396 moved the crash into the offset sort; the
CO-RE pass and visitMapDefType() crash on them too.

BTF: emit a non-virtual base as an anonymous member of the base type at
its offset, as pahole does, and skip the other elements. Virtual bases
are skipped, as their offset is only known at run time.

CO-RE: fixing BTF alone would turn the crash into a silent miscompile,
since clang numbers the fields of a record while the backend indexed its
elements: for "struct S : Base { int x, y; }", &s->y got the offset of
x. Map the access index to the field and take the access string index
from the same member list BTF is built from. For an inherited field only
its position within the base is relocated; the offset of the base stays
a constant, or is loaded from the vtable for a virtual base. Report an
access into a record the debug info only declares as an error at the
access, and replace a field info call on it with 0.

Assisted-by: Claude Code (Claude Opus 5.5)
The di_index operand of llvm.preserve.{struct,union}.access.index is an
index into the record's debug info elements; llvm#226790 makes clang emit it
that way for C++ records, whose elements also include bases, static data
members, methods and the vtable pointer. Look the element up directly
instead of mapping a field ordinal to it, and only check that it is a
data member before taking its position among the BTF members. An index
that does not refer to one, e.g. into a record the debug info only
declares, is still reported as an error at the access, and no longer
crashes when it is the parent of a nested access.

Assisted-by: Claude Code (Claude Opus 5.5)
A C++ record declared with the class keyword has DW_TAG_class_type in
the debug info. Since llvm#155783, visitCompositeType() hits
llvm_unreachable() on it; before, the class type was emitted as type 0.
The CO-RE pass only computes the field offset for DW_TAG_structure_type,
so an access into a class got the offset 0: for "class C { public: int
x, y; }", &c->y was relocated as offset 0 instead of 4.

Handle DW_TAG_class_type wherever DW_TAG_structure_type is handled, so
that a class becomes a BTF struct (not a union) and is relocated like
one.

Assisted-by: Claude Code (Claude Opus 5.5)
…emplates

Address review:
- Clang reports a CO-RE access through a virtual base or a base at a
  non-zero offset: the relocation is relative to the record with the
  field, so the offset of the base would not be relocated.
- A C++ reference member becomes a BTF pointer instead of a member with
  type 0, which asserted or produced BTF the kernel rejects.
- The BTF name of a template specialization or alias template drops the
  template arguments, as with -gsimple-template-names, since released
  kernels only accept identifiers as type names.
- The BTF index of a CO-RE access is computed in one pass over the
  elements again, without building and sorting the member list.
- The error for an invalid access in a chain points at that access.
Address review:
- Reject a CO-RE access through any base class, also at offset 0: the
  base may be at another offset in the target. Only on BPF, since other
  targets don't relocate these accesses.
- Treat references as pointers also when visiting an already visited
  type, through one isBTFPointerTag() rule.
- Rename isStructTag() to isBTFStructTag() and move
  getBTFRecordElements() into BTFDebug.cpp, its only user.
- Check BTF eligibility of a CO-RE field with isBTFRecordElement(), and
  for a union only count the members before it.
- Drop template arguments from type names only where the name is
  emitted, keeping DI names for type identity and fixups.

Assisted-by: Claude Code (Claude Opus 5.5)
Address review:
- Report a conversion between a class and its base, in either
  direction, that the address of a BPF CO-RE access depends on, found
  by walking the address expression of the builtin, instead of every
  upcast emitted while the address is evaluated. A conversion in an
  operand that only adds side effects is fine now, and a downcast is
  reported too.
- Match a reference parameter like a pointer in
  sourceArgMatchesIRType(), so that a surviving reference keeps the
  optimized BTF prototype of a nocall function.
- Keep the names of template specializations: other producers already
  emit such names, and CO-RE on specializations is left to llvm#233947.
- Test a repeated reference to a record with a complete definition in
  the debug info.

Assisted-by: Claude Code (Claude Opus 5.5)
@maxskokov

Copy link
Copy Markdown
Author

Rebased.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang:codegen IR generation bugs: mangling, exceptions, etc.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants