Skip to content

[Clang] Fix preserved C++ field indices - #226790

Merged
yonghong-song merged 2 commits into
llvm:mainfrom
tamird:clang-preserve-access-index
Oct 19, 2026
Merged

yonghong-song merged 2 commits into
llvm:mainfrom
tamird:clang-preserve-access-index

Conversation

@tamird

@tamird tamird commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Since 048493f, preserved field accesses have used source field ordinals
as debug-info indices. 4754814 accounted for omitted unnamed bitfields,
but C++ debug info also contains bases, static members and vtable
pointers. For "struct S : Base { int x, y; }", the index for y therefore
identifies x. BPF CO-RE uses that index to select the field and its offset.

Record each field's index while emitting its debug info and return it
with the record type. Complete the record and its bases for these
accesses: limited and constructor debug modes can otherwise leave only
forward declarations, without the layout needed for relocation.

Assisted-by: OpenAI Codex

@llvmorg-github-actions llvmorg-github-actions Bot added clang Clang issues not falling into any other category clang:codegen IR generation bugs: mangling, exceptions, etc. debuginfo labels Sep 27, 2026
@llvmorg-github-actions

llvmorg-github-actions Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-debuginfo

@llvm/pr-subscribers-clang

Author: Tamir Duberstein (tamird)

Changes

This separates the Clang producer issue identified while reviewing #226717 from BTF’s handling of C++ record elements. The intrinsic contract is unchanged, and the producer correction can be reviewed independently of the backend changes.

Assisted-by: OpenAI Codex


Full diff: https://github.com/llvm/llvm-project/pull/226790.diff

5 Files Affected:

  • (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+16-5)
  • (modified) clang/lib/CodeGen/CGDebugInfo.h (+6-2)
  • (modified) clang/lib/CodeGen/CGExpr.cpp (+13-33)
  • (modified) clang/lib/CodeGen/CodeGenFunction.h (-3)
  • (added) clang/test/CodeGenCXX/builtin-preserve-access-index.cpp (+68)
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp
index b6418753a6a65..42fc602ac1a8c 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -2108,6 +2108,7 @@ void CGDebugInfo::CollectRecordLambdaFields(
 
     llvm::DIFile *VUnit = getOrCreateFile(Loc);
 
+    FieldIndexCache[*Field] = elements.size();
     elements.push_back(createFieldType(
         GetLambdaCaptureName(Capture), Field->getType(), Loc,
         Field->getAccess(), FieldOffset, Align, VUnit, RecordTy, CXXDecl));
@@ -2228,6 +2229,7 @@ void CGDebugInfo::CollectRecordNormalField(
                         OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
   }
 
+  FieldIndexCache[field] = elements.size();
   elements.push_back(FieldType);
 }
 
@@ -3087,11 +3089,20 @@ void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
   EltTys.push_back(VPtrMember);
 }
 
-llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
-                                                 SourceLocation Loc) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
-  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
-  return T;
+std::pair<llvm::DIType *, unsigned>
+CGDebugInfo::getOrCreateRecordField(QualType Ty, const FieldDecl *Field) {
+  const RecordDecl *RD = Field->getParent();
+  // Preserve-access intrinsics need complete layouts, including base classes.
+  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
+    CXXRD->forallBases([this](const CXXRecordDecl *Base) {
+      completeClass(Base);
+      return true;
+    });
+  completeClass(RD);
+  llvm::DIType *T = getOrCreateStandaloneType(Ty, RD->getLocation());
+  auto I = FieldIndexCache.find(Field);
+  assert(I != FieldIndexCache.end() && "Missing field debug information");
+  return {T, I->second};
 }
 
 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 8a46e3f0e60bb..fca587517a035 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -103,6 +103,9 @@ class CGDebugInfo {
   /// Cache of previously constructed Types.
   llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
 
+  /// DI element indices used by preserve-access intrinsics.
+  llvm::DenseMap<const FieldDecl *, unsigned> FieldIndexCache;
+
   /// Cache that maps VLA types to size expressions for that type,
   /// represented by instantiated Metadata nodes.
   llvm::SmallDenseMap<QualType, llvm::Metadata *> SizeExprCache;
@@ -623,8 +626,9 @@ class CGDebugInfo {
   /// Emit C++ namespace alias.
   llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
 
-  /// Emit record type's standalone debug info.
-  llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
+  /// Emit complete record debug info and return the field's element index.
+  std::pair<llvm::DIType *, unsigned>
+  getOrCreateRecordField(QualType Ty, const FieldDecl *Field);
 
   /// Emit an Objective-C interface type standalone debug info.
   llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 4a481c01f6a68..fe90ae0af73c2 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -5851,23 +5851,6 @@ LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
   return EmitLValueForLambdaField(Field, CXXABIThisValue);
 }
 
-/// Get the field index in the debug info. The debug info structure/union
-/// will ignore the unnamed bitfields.
-unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
-                                             unsigned FieldIndex) {
-  unsigned I = 0, Skipped = 0;
-
-  for (auto *F : Rec->getDefinition()->fields()) {
-    if (I == FieldIndex)
-      break;
-    if (F->isUnnamedBitField())
-      Skipped++;
-    I++;
-  }
-
-  return FieldIndex - Skipped;
-}
-
 /// Get the address of a zero-sized field within a record. The resulting
 /// address doesn't necessarily have the right type.
 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
@@ -5930,14 +5913,14 @@ static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
 static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
                                         Address addr, const FieldDecl *field) {
   const RecordDecl *rec = field->getParent();
-  llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
-      base.getType(), rec->getLocation());
+  auto [DbgInfo, DIIndex] =
+      CGF.getDebugInfo()->getOrCreateRecordField(base.getType(), field);
 
   unsigned idx =
       CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
 
-  return CGF.Builder.CreatePreserveStructAccessIndex(
-      addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
+  return CGF.Builder.CreatePreserveStructAccessIndex(addr, idx, DIIndex,
+                                                     DbgInfo);
 }
 
 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
@@ -5989,11 +5972,10 @@ LValue CodeGenFunction::EmitLValueForField(LValue base, const FieldDecl *field,
             Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
         }
       } else {
-        llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
-            getContext().getCanonicalTagType(rec), rec->getLocation());
-        Addr = Builder.CreatePreserveStructAccessIndex(
-            Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
-            DbgInfo);
+        auto [DbgInfo, DIIndex] = getDebugInfo()->getOrCreateRecordField(
+            getContext().getCanonicalTagType(rec), field);
+        Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx, DIIndex,
+                                                       DbgInfo);
       }
     }
     const unsigned SS =
@@ -6069,13 +6051,11 @@ LValue CodeGenFunction::EmitLValueForField(LValue base, const FieldDecl *field,
     if (IsInPreservedAIRegion ||
         (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
       // Remember the original union field index
-      llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
-          rec->getLocation());
-      addr =
-          Address(Builder.CreatePreserveUnionAccessIndex(
-                      addr.emitRawPointer(*this),
-                      getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
-                  addr.getElementType(), addr.getAlignment());
+      auto [DbgInfo, DIIndex] =
+          getDebugInfo()->getOrCreateRecordField(base.getType(), field);
+      addr = Address(Builder.CreatePreserveUnionAccessIndex(
+                         addr.emitRawPointer(*this), DIIndex, DbgInfo),
+                     addr.getElementType(), addr.getAlignment());
     }
 
     if (FieldType->isReferenceType())
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 653e883012229..fe0704e517a95 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -3491,9 +3491,6 @@ class CodeGenFunction : public CodeGenTypeCache {
   /// Converts Location to a DebugLoc, if debug information is enabled.
   llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
 
-  /// Get the record field index as represented in debug info.
-  unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
-
   //===--------------------------------------------------------------------===//
   //                            Declaration Emission
   //===--------------------------------------------------------------------===//
diff --git a/clang/test/CodeGenCXX/builtin-preserve-access-index.cpp b/clang/test/CodeGenCXX/builtin-preserve-access-index.cpp
new file mode 100644
index 0000000000000..2a8fbb1562f8a
--- /dev/null
+++ b/clang/test/CodeGenCXX/builtin-preserve-access-index.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang_cc1 -triple bpfel -emit-llvm -debug-info-kind=limited -disable-llvm-passes %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64 -emit-llvm -debug-info-kind=limited -disable-llvm-passes %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple bpfel -emit-llvm -debug-info-kind=constructor -disable-llvm-passes %s -o - | FileCheck %s
+
+struct Base {
+  Base();
+  int base;
+};
+struct Record : Base {
+  static int first;
+  int field;
+  static int second;
+  unsigned bits : 3;
+  void method();
+};
+union Union {
+  int first;
+  static int member;
+  long second;
+};
+struct Dynamic {
+  virtual void method();
+  int field;
+};
+
+int *field(Record *p) {
+  return __builtin_preserve_access_index(&p->field);
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 1, i32 2), {{.*}}!llvm.preserve.access.index ![[RECORD:[0-9]+]]
+
+unsigned bits(Record *p) {
+  return __builtin_preserve_access_index(p->bits);
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 2, i32 4), {{.*}}!llvm.preserve.access.index ![[RECORD]]
+
+long *member(Union *p) {
+  return __builtin_preserve_access_index(&p->second);
+}
+// CHECK: call ptr @llvm.preserve.union.access.index.p0.p0({{.*}}, i32 2), {{.*}}!llvm.preserve.access.index ![[UNION:[0-9]+]]
+
+int *dynamic(Dynamic *p) {
+  return __builtin_preserve_access_index(&p->field);
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 1, i32 1), {{.*}}!llvm.preserve.access.index ![[DYNAMIC:[0-9]+]]
+
+int lambda(int a, int b) {
+  return [a, b] { return __builtin_preserve_access_index(b); }();
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 1, i32 1), {{.*}}!llvm.preserve.access.index ![[LAMBDA:[0-9]+]]
+
+// The intrinsic indices refer to the complete DI element lists, including
+// bases, static members, and the vtable pointer before the accessed fields.
+// CHECK-DAG: ![[RECORD]] = distinct !DICompositeType({{.*}}name: "Record", {{.*}}elements: ![[RECORD_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[RECORD_ELEMENTS]] = !{!{{[0-9]+}}, !{{[0-9]+}}, ![[FIELD:[0-9]+]], !{{[0-9]+}}, ![[BITS:[0-9]+]], !{{[0-9]+}}}
+// CHECK-DAG: ![[FIELD]] = !DIDerivedType(tag: DW_TAG_member, name: "field"
+// CHECK-DAG: ![[BITS]] = !DIDerivedType(tag: DW_TAG_member, name: "bits"
+// CHECK-DAG: ![[UNION]] = distinct !DICompositeType({{.*}}name: "Union", {{.*}}elements: ![[UNION_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[UNION_ELEMENTS]] = !{!{{[0-9]+}}, !{{[0-9]+}}, ![[SECOND:[0-9]+]]}
+// CHECK-DAG: ![[SECOND]] = !DIDerivedType(tag: DW_TAG_member, name: "second"
+// CHECK-DAG: ![[DYNAMIC]] = distinct !DICompositeType({{.*}}name: "Dynamic", {{.*}}elements: ![[DYNAMIC_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[DYNAMIC_ELEMENTS]] = !{!{{[0-9]+}}, ![[DYNAMIC_FIELD:[0-9]+]], !{{[0-9]+}}}
+// CHECK-DAG: ![[DYNAMIC_FIELD]] = !DIDerivedType(tag: DW_TAG_member, name: "field"
+// CHECK-DAG: ![[LAMBDA]] = distinct !DICompositeType({{.*}}elements: ![[LAMBDA_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[LAMBDA_ELEMENTS]] = !{!{{[0-9]+}}, ![[CAPTURE:[0-9]+]]}
+// CHECK-DAG: ![[CAPTURE]] = !DIDerivedType(tag: DW_TAG_member, name: "b"
+// CHECK-DAG: !DICompositeType({{.*}}name: "Base", {{.*}}elements: ![[BASE_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[BASE_ELEMENTS]] = !{![[BASE_FIELD:[0-9]+]], !{{[0-9]+}}}
+// CHECK-DAG: ![[BASE_FIELD]] = !DIDerivedType(tag: DW_TAG_member, name: "base"

@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-clang-codegen

Author: Tamir Duberstein (tamird)

Changes

This separates the Clang producer issue identified while reviewing #226717 from BTF’s handling of C++ record elements. The intrinsic contract is unchanged, and the producer correction can be reviewed independently of the backend changes.

Assisted-by: OpenAI Codex


Full diff: https://github.com/llvm/llvm-project/pull/226790.diff

5 Files Affected:

  • (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+16-5)
  • (modified) clang/lib/CodeGen/CGDebugInfo.h (+6-2)
  • (modified) clang/lib/CodeGen/CGExpr.cpp (+13-33)
  • (modified) clang/lib/CodeGen/CodeGenFunction.h (-3)
  • (added) clang/test/CodeGenCXX/builtin-preserve-access-index.cpp (+68)
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp
index b6418753a6a65..42fc602ac1a8c 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -2108,6 +2108,7 @@ void CGDebugInfo::CollectRecordLambdaFields(
 
     llvm::DIFile *VUnit = getOrCreateFile(Loc);
 
+    FieldIndexCache[*Field] = elements.size();
     elements.push_back(createFieldType(
         GetLambdaCaptureName(Capture), Field->getType(), Loc,
         Field->getAccess(), FieldOffset, Align, VUnit, RecordTy, CXXDecl));
@@ -2228,6 +2229,7 @@ void CGDebugInfo::CollectRecordNormalField(
                         OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
   }
 
+  FieldIndexCache[field] = elements.size();
   elements.push_back(FieldType);
 }
 
@@ -3087,11 +3089,20 @@ void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
   EltTys.push_back(VPtrMember);
 }
 
-llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
-                                                 SourceLocation Loc) {
-  assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
-  llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
-  return T;
+std::pair<llvm::DIType *, unsigned>
+CGDebugInfo::getOrCreateRecordField(QualType Ty, const FieldDecl *Field) {
+  const RecordDecl *RD = Field->getParent();
+  // Preserve-access intrinsics need complete layouts, including base classes.
+  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
+    CXXRD->forallBases([this](const CXXRecordDecl *Base) {
+      completeClass(Base);
+      return true;
+    });
+  completeClass(RD);
+  llvm::DIType *T = getOrCreateStandaloneType(Ty, RD->getLocation());
+  auto I = FieldIndexCache.find(Field);
+  assert(I != FieldIndexCache.end() && "Missing field debug information");
+  return {T, I->second};
 }
 
 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 8a46e3f0e60bb..fca587517a035 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -103,6 +103,9 @@ class CGDebugInfo {
   /// Cache of previously constructed Types.
   llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
 
+  /// DI element indices used by preserve-access intrinsics.
+  llvm::DenseMap<const FieldDecl *, unsigned> FieldIndexCache;
+
   /// Cache that maps VLA types to size expressions for that type,
   /// represented by instantiated Metadata nodes.
   llvm::SmallDenseMap<QualType, llvm::Metadata *> SizeExprCache;
@@ -623,8 +626,9 @@ class CGDebugInfo {
   /// Emit C++ namespace alias.
   llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
 
-  /// Emit record type's standalone debug info.
-  llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
+  /// Emit complete record debug info and return the field's element index.
+  std::pair<llvm::DIType *, unsigned>
+  getOrCreateRecordField(QualType Ty, const FieldDecl *Field);
 
   /// Emit an Objective-C interface type standalone debug info.
   llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 4a481c01f6a68..fe90ae0af73c2 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -5851,23 +5851,6 @@ LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
   return EmitLValueForLambdaField(Field, CXXABIThisValue);
 }
 
-/// Get the field index in the debug info. The debug info structure/union
-/// will ignore the unnamed bitfields.
-unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
-                                             unsigned FieldIndex) {
-  unsigned I = 0, Skipped = 0;
-
-  for (auto *F : Rec->getDefinition()->fields()) {
-    if (I == FieldIndex)
-      break;
-    if (F->isUnnamedBitField())
-      Skipped++;
-    I++;
-  }
-
-  return FieldIndex - Skipped;
-}
-
 /// Get the address of a zero-sized field within a record. The resulting
 /// address doesn't necessarily have the right type.
 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
@@ -5930,14 +5913,14 @@ static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
 static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
                                         Address addr, const FieldDecl *field) {
   const RecordDecl *rec = field->getParent();
-  llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
-      base.getType(), rec->getLocation());
+  auto [DbgInfo, DIIndex] =
+      CGF.getDebugInfo()->getOrCreateRecordField(base.getType(), field);
 
   unsigned idx =
       CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
 
-  return CGF.Builder.CreatePreserveStructAccessIndex(
-      addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
+  return CGF.Builder.CreatePreserveStructAccessIndex(addr, idx, DIIndex,
+                                                     DbgInfo);
 }
 
 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
@@ -5989,11 +5972,10 @@ LValue CodeGenFunction::EmitLValueForField(LValue base, const FieldDecl *field,
             Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
         }
       } else {
-        llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
-            getContext().getCanonicalTagType(rec), rec->getLocation());
-        Addr = Builder.CreatePreserveStructAccessIndex(
-            Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
-            DbgInfo);
+        auto [DbgInfo, DIIndex] = getDebugInfo()->getOrCreateRecordField(
+            getContext().getCanonicalTagType(rec), field);
+        Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx, DIIndex,
+                                                       DbgInfo);
       }
     }
     const unsigned SS =
@@ -6069,13 +6051,11 @@ LValue CodeGenFunction::EmitLValueForField(LValue base, const FieldDecl *field,
     if (IsInPreservedAIRegion ||
         (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
       // Remember the original union field index
-      llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
-          rec->getLocation());
-      addr =
-          Address(Builder.CreatePreserveUnionAccessIndex(
-                      addr.emitRawPointer(*this),
-                      getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
-                  addr.getElementType(), addr.getAlignment());
+      auto [DbgInfo, DIIndex] =
+          getDebugInfo()->getOrCreateRecordField(base.getType(), field);
+      addr = Address(Builder.CreatePreserveUnionAccessIndex(
+                         addr.emitRawPointer(*this), DIIndex, DbgInfo),
+                     addr.getElementType(), addr.getAlignment());
     }
 
     if (FieldType->isReferenceType())
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 653e883012229..fe0704e517a95 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -3491,9 +3491,6 @@ class CodeGenFunction : public CodeGenTypeCache {
   /// Converts Location to a DebugLoc, if debug information is enabled.
   llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
 
-  /// Get the record field index as represented in debug info.
-  unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
-
   //===--------------------------------------------------------------------===//
   //                            Declaration Emission
   //===--------------------------------------------------------------------===//
diff --git a/clang/test/CodeGenCXX/builtin-preserve-access-index.cpp b/clang/test/CodeGenCXX/builtin-preserve-access-index.cpp
new file mode 100644
index 0000000000000..2a8fbb1562f8a
--- /dev/null
+++ b/clang/test/CodeGenCXX/builtin-preserve-access-index.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang_cc1 -triple bpfel -emit-llvm -debug-info-kind=limited -disable-llvm-passes %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64 -emit-llvm -debug-info-kind=limited -disable-llvm-passes %s -o - | FileCheck %s
+// RUN: %clang_cc1 -triple bpfel -emit-llvm -debug-info-kind=constructor -disable-llvm-passes %s -o - | FileCheck %s
+
+struct Base {
+  Base();
+  int base;
+};
+struct Record : Base {
+  static int first;
+  int field;
+  static int second;
+  unsigned bits : 3;
+  void method();
+};
+union Union {
+  int first;
+  static int member;
+  long second;
+};
+struct Dynamic {
+  virtual void method();
+  int field;
+};
+
+int *field(Record *p) {
+  return __builtin_preserve_access_index(&p->field);
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 1, i32 2), {{.*}}!llvm.preserve.access.index ![[RECORD:[0-9]+]]
+
+unsigned bits(Record *p) {
+  return __builtin_preserve_access_index(p->bits);
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 2, i32 4), {{.*}}!llvm.preserve.access.index ![[RECORD]]
+
+long *member(Union *p) {
+  return __builtin_preserve_access_index(&p->second);
+}
+// CHECK: call ptr @llvm.preserve.union.access.index.p0.p0({{.*}}, i32 2), {{.*}}!llvm.preserve.access.index ![[UNION:[0-9]+]]
+
+int *dynamic(Dynamic *p) {
+  return __builtin_preserve_access_index(&p->field);
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 1, i32 1), {{.*}}!llvm.preserve.access.index ![[DYNAMIC:[0-9]+]]
+
+int lambda(int a, int b) {
+  return [a, b] { return __builtin_preserve_access_index(b); }();
+}
+// CHECK: call ptr @llvm.preserve.struct.access.index.p0.p0({{.*}}, i32 1, i32 1), {{.*}}!llvm.preserve.access.index ![[LAMBDA:[0-9]+]]
+
+// The intrinsic indices refer to the complete DI element lists, including
+// bases, static members, and the vtable pointer before the accessed fields.
+// CHECK-DAG: ![[RECORD]] = distinct !DICompositeType({{.*}}name: "Record", {{.*}}elements: ![[RECORD_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[RECORD_ELEMENTS]] = !{!{{[0-9]+}}, !{{[0-9]+}}, ![[FIELD:[0-9]+]], !{{[0-9]+}}, ![[BITS:[0-9]+]], !{{[0-9]+}}}
+// CHECK-DAG: ![[FIELD]] = !DIDerivedType(tag: DW_TAG_member, name: "field"
+// CHECK-DAG: ![[BITS]] = !DIDerivedType(tag: DW_TAG_member, name: "bits"
+// CHECK-DAG: ![[UNION]] = distinct !DICompositeType({{.*}}name: "Union", {{.*}}elements: ![[UNION_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[UNION_ELEMENTS]] = !{!{{[0-9]+}}, !{{[0-9]+}}, ![[SECOND:[0-9]+]]}
+// CHECK-DAG: ![[SECOND]] = !DIDerivedType(tag: DW_TAG_member, name: "second"
+// CHECK-DAG: ![[DYNAMIC]] = distinct !DICompositeType({{.*}}name: "Dynamic", {{.*}}elements: ![[DYNAMIC_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[DYNAMIC_ELEMENTS]] = !{!{{[0-9]+}}, ![[DYNAMIC_FIELD:[0-9]+]], !{{[0-9]+}}}
+// CHECK-DAG: ![[DYNAMIC_FIELD]] = !DIDerivedType(tag: DW_TAG_member, name: "field"
+// CHECK-DAG: ![[LAMBDA]] = distinct !DICompositeType({{.*}}elements: ![[LAMBDA_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[LAMBDA_ELEMENTS]] = !{!{{[0-9]+}}, ![[CAPTURE:[0-9]+]]}
+// CHECK-DAG: ![[CAPTURE]] = !DIDerivedType(tag: DW_TAG_member, name: "b"
+// CHECK-DAG: !DICompositeType({{.*}}name: "Base", {{.*}}elements: ![[BASE_ELEMENTS:[0-9]+]]
+// CHECK-DAG: ![[BASE_ELEMENTS]] = !{![[BASE_FIELD:[0-9]+]], !{{[0-9]+}}}
+// CHECK-DAG: ![[BASE_FIELD]] = !DIDerivedType(tag: DW_TAG_member, name: "base"

@tamird

tamird commented Sep 27, 2026

Copy link
Copy Markdown
Member Author

This was extracted while reviewing #226717 to separate the Clang producer fix from BTF’s handling of C++ record elements. The intrinsic contract is unchanged, and the producer correction can be reviewed independently of the backend changes.

Assisted-by: OpenAI Codex

Since 048493f, preserved field accesses have used source field ordinals
as debug-info indices. 4754814 accounted for omitted unnamed bitfields,
but C++ debug info also contains bases, static members and vtable
pointers. For "struct S : Base { int x, y; }", the index for y therefore
identifies x. BPF CO-RE uses that index to select the field and its offset.

Record each field's index while emitting its debug info and return it
with the record type. Complete the record and its bases for these
accesses: limited and constructor debug modes can otherwise leave only
forward declarations, without the layout needed for relocation.

Assisted-by: OpenAI Codex
@tamird
tamird force-pushed the clang-preserve-access-index branch from efd179e to 8d2ddd3 Compare September 27, 2026 15:14
maxskokov added a commit to maxskokov/llvm-project that referenced this pull request Sep 27, 2026
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)

@slinder1 slinder1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm not a clang dev, but the approach makes sense to me.

It seems like the simplest way to ensure the field indexing remains in sync between the preserve path and the rest of codegen, but it does still require ensuring you complete the right types before making the field DbgInfo and recording the index. I didn't think or look to hard to be confident that just walking the bases via forallBases is sufficient, and that's the part I'd wait for someone more familiar to comment on.

The naming of some of the methods seems a bit generic, when they are only used in the bpf paths. I imagine they used to be used for regular DI codegen, and this path is just the last user?

Comment thread clang/lib/CodeGen/CGDebugInfo.cpp Resolved
Comment thread clang/lib/CodeGen/CGDebugInfo.cpp Resolved
Name the debug-info helper for its preserve-access purpose and document
its returned record type and field index. Extend the existing C++ test
to require complete metadata for an indirect base in limited and
constructor debug modes.

Assisted-by: OpenAI Codex

@tamird tamird left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

On the base traversal: forallBases() visits indirect bases as well. 6881981 extends the existing test to Record : Base : GrandBase and checks complete metadata for both ancestors in limited and constructor debug modes. All 13 preserve-access tests pass with the rebuilt Clang.

Assisted-by: OpenAI Codex

Comment thread clang/lib/CodeGen/CGDebugInfo.cpp Resolved
Comment thread clang/lib/CodeGen/CGDebugInfo.cpp Resolved

@slinder1 slinder1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, thanks!

Ideally someone with a bit more history in clang could also review

@tamird

tamird commented Sep 30, 2026

Copy link
Copy Markdown
Member Author

Would be great if @yonghong-song could take a look.

@tamird

tamird commented Oct 5, 2026

Copy link
Copy Markdown
Member Author

@eddyb would you like to review? I'm gonna need someone to merge this for me.

@yonghong-song

Copy link
Copy Markdown
Contributor

@tamird I looked at your pull request, I think your implementation is correct
at least for the current front-end change.

But I don't know you final goal.
First, bpf does not support general C++ codes. It may support some C++ but I guess
we are not there yet.
Second, what is your goal here? I guess you want to support CO-RE relocation for
C++ with bpf clang-side intrinsic's. Note that the attribute 'preserve_access_index'
and 'preserve_static_offset' for C only plus a few others like btf_decl_tag/btf_type_tag/bpf_fastcall.
So your eventual goal is to support C++ for full (close to full) features?
But this could be very complicated?

I would be great to explain the motivation, steps, and eventual goal, before going
deep implementing for C++ for llvm bpf. Alexei does have a C++ bpf prog example
with exception handling:
https://lore.kernel.org/bpf/[email protected]/
which means we could expand C++ in bpf. But still some future plan will be helpful.

@yonghong-song

Copy link
Copy Markdown
Contributor

cc @eddyz87 @4ast

@tamird

tamird commented Oct 19, 2026

Copy link
Copy Markdown
Member Author

@yonghong-song the final goal is @maxskokov's -- this PR is just fixing a bug observed during review of his #226717 and #226723

@yonghong-song

Copy link
Copy Markdown
Contributor

I built the kernel/selftests with this pull request and it didn't have any impact on kernel/bpf. This is expected since we mostly use C and people didn't do CO-RE relocation for C++ yet. I will merge this so to make follow-up CO-RE work in backend easier.

@yonghong-song
yonghong-song merged commit da9657b into llvm:main Oct 19, 2026
10 checks passed
@tamird
tamird deleted the clang-preserve-access-index branch October 19, 2026 16:37
@yonghong-song

Copy link
Copy Markdown
Contributor

@maxskokov For pull request #226717 and #226723, I can cherry pick #226717 on top of #226790. But I cannot cherry-pick #226723 on top of #226717 successfully. So I suggest you merge these two commits since I see they are in the same code base.
I will review after your new pull request.

@maxskokov

Copy link
Copy Markdown

@yonghong-song The goal isn't full C++ support in BPF. It's that C++ code which already compiles for BPF doesn't crash the backend, doesn't get silently wrong CO-RE offsets, and produces BTF the kernel accepts. Alexei's C++ example with exceptions is the kind of code I have in mind.
Planned steps, in this order:

  1. The combined [BPF] Handle C++ record elements in BTF and CO-RE #226717 + [BPF] Treat class records as structs in BTF and CO-RE #226723. Since 22.1.0, any C++ record with a method, base or static member, and any class, hits UNREACHABLE in BTFDebug with -g. CO-RE on such records was wrong even before: for struct S : Base { int x, y; }, &s->y got x's offset (4 instead of 8) since at least clang 19, and class got offset 0. With this, BTF for these records loads on 6.12, where clang 19's was rejected.
  2. sret and by-reference args in BTF FUNC_PROTO. A global function returning a record over 16 bytes has an sret pointer as its first arg, but BTF shows the source signature, so the verifier rejects it. The PR names the sret param __sret and marks by-reference records with arg:nonnull; kfunc externs keep the source prototype.
  3. Escaping invalid characters in BTF names (template names like Box<int>, _vptr$X), which the kernel rejects today, using bpf-linker's scheme.
  4. ABI: passing and returning C++ records over 16 bytes and non-trivial records by reference, as the C++ ABI requires. With the current ABI, a non-trivial argument gets destroyed twice and a returned record with a self-pointer breaks; the verifier can't see either. -fclang-abi-compat=23 keeps the old behavior. This builds on your bpf-next changes for struct args and returns up to 16 bytes.

Steps 2 and 3 are ready, and step 4 depends on 2. I've tested them on 6.12 and bpf-next 7.3-rc2. For the ABI change, would you prefer a PR or an RFC on Discourse first?
Once you're fine with the plan, I'll combine #226717 and #226723 into a new PR.

@yonghong-song

Copy link
Copy Markdown
Contributor

@yonghong-song The goal isn't full C++ support in BPF. It's that C++ code which already compiles for BPF doesn't crash the backend, doesn't get silently wrong CO-RE offsets, and produces BTF the kernel accepts. Alexei's C++ example with exceptions is the kind of code I have in mind. Planned steps, in this order:

1. The combined [[BPF] Handle C++ record elements in BTF and CO-RE #226717](https://github.com/llvm/llvm-project/pull/226717) + [[BPF] Treat class records as structs in BTF and CO-RE #226723](https://github.com/llvm/llvm-project/pull/226723). Since 22.1.0, any C++ record with a method, base or static member, and any `class`, hits UNREACHABLE in BTFDebug with `-g`. CO-RE on such records was wrong even before: for `struct S : Base { int x, y; }`, `&s->y` got `x`'s offset (4 instead of 8) since at least clang 19, and `class` got offset 0. With this, BTF for these records loads on 6.12, where clang 19's was rejected.

This is related to CO-RE and we should handle this first. This is the followup for #226790.

2. sret and by-reference args in BTF FUNC_PROTO. A global function returning a record over 16 bytes has an sret pointer as its first arg, but BTF shows the source signature, so the verifier rejects it. The PR names the sret param `__sret` and marks by-reference records with `arg:nonnull`; kfunc externs keep the source prototype.

Such a case should be really rare. Currently bpf does not support it. I remembered I did some accounting for kernel functions. The kernel functions roughtly ~65000 functions, and the number of functions having either return value or argument value is less than 100. So it should be rare. This can be a separate discussion in llvm and kernel side.

3. Escaping invalid characters in BTF names (template names like `Box<int>`, `_vptr$X`), which the kernel rejects today, using bpf-linker's scheme.

From user's perspective, the name should be the same as in the source...

4. ABI: passing and returning C++ records over 16 bytes and non-trivial records by reference, as the C++ ABI requires. With the current ABI, a non-trivial argument gets destroyed twice and a returned record with a self-pointer breaks; the verifier can't see either. `-fclang-abi-compat=23` keeps the old behavior. This builds on your bpf-next changes for struct args and returns up to 16 bytes.

Since this is for bpf programs, the ABI should follow bpf calling convention. I am not sure whether we need to expand bpf calling convention for c++.

Steps 2 and 3 are ready, and step 4 depends on 2. I've tested them on 6.12 and bpf-next 7.3-rc2. For the ABI change, would you prefer a PR or an RFC on Discourse first? Once you're fine with the plan, I'll combine #226717 and #226723 into a new PR.

We should finish item 1 first. The rest of them about names and '> 16' arguments or return values can be next.

yonghong-song pushed a commit to maxskokov/llvm-project that referenced this pull request Oct 20, 2026
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)
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. clang Clang issues not falling into any other category debuginfo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants