[llvm] [BPF] Sort BTF struct members by offset (PR #205396)

Tamir Duberstein via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 23 13:02:10 PDT 2026


https://github.com/tamird updated https://github.com/llvm/llvm-project/pull/205396

>From db48f235de844f06ffc2c09cf9b4b492f00adce6 Mon Sep 17 00:00:00 2001
From: Tamir Duberstein <tamird at gmail.com>
Date: Tue, 23 Jun 2026 13:58:45 -0400
Subject: [PATCH] [BPF] Sort BTF struct members by offset

Sort BTF structure elements by their debug offsets. Prevent
source-ordered Rust debug metadata from producing descending member
offsets after rustc chooses a different physical layout, because the
kernel rejects such BTF.

Use the sorted order for member emission, declaration-tag component
indexes, and CO-RE access strings. Keep physical offset calculations on
the original debug indexes so changing BTF order does not change
generated code.

Eliminate the need for the bpf-linker metadata rewrite by enforcing the
ordering in the LLVM BPF backend:

https://github.com/aya-rs/bpf-linker/commit/1007ec7fed03562eb7d08f3e7521094a7e698b95
---
 .../Target/BPF/BPFAbstractMemberAccess.cpp    | 20 +++-
 llvm/lib/Target/BPF/BPFCORE.h                 | 15 +++
 llvm/lib/Target/BPF/BTFDebug.cpp              | 22 +++--
 llvm/lib/Target/BPF/BTFDebug.h                |  6 +-
 .../CodeGen/BPF/BTF/struct-member-order.ll    | 38 ++++++++
 .../CodeGen/BPF/CORE/struct-member-order.ll   | 93 +++++++++++++++++++
 6 files changed, 184 insertions(+), 10 deletions(-)
 create mode 100644 llvm/test/CodeGen/BPF/BTF/struct-member-order.ll
 create mode 100644 llvm/test/CodeGen/BPF/CORE/struct-member-order.ll

diff --git a/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp b/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
index 81303faf77b58..d65726bc59d68 100644
--- a/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
+++ b/llvm/lib/Target/BPF/BPFAbstractMemberAccess.cpp
@@ -77,6 +77,7 @@
 #include "BPF.h"
 #include "BPFCORE.h"
 #include "BPFTargetMachine.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/BinaryFormat/Dwarf.h"
 #include "llvm/DebugInfo/BTF/BTF.h"
 #include "llvm/IR/DebugInfoMetadata.h"
@@ -958,11 +959,26 @@ Value *BPFAbstractMemberAccess::computeBaseAndAccessKey(CallInst *Call,
 
     // Access Index
     uint64_t AccessIndex = CInfo.AccessIndex;
-    AccessKey += ":" + std::to_string(AccessIndex);
-
     MDNode *MDN = CInfo.Metadata;
     // At this stage, it cannot be pointer type.
     auto *CTy = cast<DICompositeType>(stripQualifiers(cast<DIType>(MDN)));
+
+    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;
+      }
+    }
+    AccessKey += ":" + std::to_string(BTFIndex);
+
     PatchImm = GetFieldInfo(InfoKind, CTy, AccessIndex, PatchImm,
                             CInfo.RecordAlignment);
   }
diff --git a/llvm/lib/Target/BPF/BPFCORE.h b/llvm/lib/Target/BPF/BPFCORE.h
index f46a8ef62a7fa..5aa7695c0ecad 100644
--- a/llvm/lib/Target/BPF/BPFCORE.h
+++ b/llvm/lib/Target/BPF/BPFCORE.h
@@ -10,7 +10,10 @@
 #define LLVM_LIB_TARGET_BPF_BPFCORE_H
 
 #include "llvm/ADT/StringRef.h"
+#include "llvm/BinaryFormat/Dwarf.h"
+#include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/Instructions.h"
+#include "llvm/Support/ErrorHandling.h"
 
 namespace llvm {
 
@@ -18,6 +21,18 @@ class BasicBlock;
 class Instruction;
 class Module;
 
+/// 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:
+    return cast<DIDerivedType>(Element)->getOffsetInBits();
+  case dwarf::DW_TAG_variant_part:
+    return cast<DICompositeType>(Element)->getOffsetInBits();
+  default:
+    llvm_unreachable("Unexpected DI tag of a struct element");
+  }
+}
+
 class BPFCoreSharedInfo {
 public:
   enum BTFTypeIdFlag : uint32_t {
diff --git a/llvm/lib/Target/BPF/BTFDebug.cpp b/llvm/lib/Target/BPF/BTFDebug.cpp
index 3a9d461bc5b93..53cd46f614b78 100644
--- a/llvm/lib/Target/BPF/BTFDebug.cpp
+++ b/llvm/lib/Target/BPF/BTFDebug.cpp
@@ -14,6 +14,8 @@
 #include "BPF.h"
 #include "BPFCORE.h"
 #include "MCTargetDesc/BPFMCTargetDesc.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/BinaryFormat/Dwarf.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/CodeGen/AsmPrinter.h"
@@ -519,9 +521,11 @@ void BTFTypeArray::emitType(MCStreamer &OS) {
 }
 
 /// Represent either a struct or a union.
-BTFTypeStruct::BTFTypeStruct(const DICompositeType *STy, bool IsStruct,
+BTFTypeStruct::BTFTypeStruct(const DICompositeType *STy,
+                             ArrayRef<const DINode *> Elements, bool IsStruct,
                              bool HasBitField, uint32_t Vlen)
-    : STy(STy), HasBitField(HasBitField) {
+    : STy(STy), Elements(Elements.begin(), Elements.end()),
+      HasBitField(HasBitField) {
   Kind = IsStruct ? BTF::BTF_KIND_STRUCT : BTF::BTF_KIND_UNION;
   BTFType.Size = roundupToBytes(STy->getSizeInBits());
   BTFType.Info = (HasBitField << 31) | (Kind << 24) | Vlen;
@@ -557,7 +561,6 @@ void BTFTypeStruct::completeType(BTFDebug &BDebug) {
   }
 
   // Add struct/union members.
-  const DINodeArray Elements = STy->getElements();
   for (const auto *Element : Elements) {
     struct BTF::BTFMember BTFMember;
 
@@ -972,7 +975,14 @@ int BTFDebug::genBTFTypeTags(const DIDerivedType *DTy, int BaseTypeId) {
 /// Handle structure/union types.
 void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
                                uint32_t &TypeId) {
-  const DINodeArray Elements = CTy->getElements();
+  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);
+    });
   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
@@ -999,8 +1009,8 @@ void BTFDebug::visitStructType(const DICompositeType *CTy, bool IsStruct,
     }
   }
 
-  auto TypeEntry =
-      std::make_unique<BTFTypeStruct>(CTy, IsStruct, HasBitField, VLen);
+  auto TypeEntry = std::make_unique<BTFTypeStruct>(CTy, Elements, IsStruct,
+                                                   HasBitField, VLen);
   StructTypes.push_back(TypeEntry.get());
   TypeId = addType(std::move(TypeEntry), CTy);
 
diff --git a/llvm/lib/Target/BPF/BTFDebug.h b/llvm/lib/Target/BPF/BTFDebug.h
index ec139138627a7..b29a0cb88624d 100644
--- a/llvm/lib/Target/BPF/BTFDebug.h
+++ b/llvm/lib/Target/BPF/BTFDebug.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_LIB_TARGET_BPF_BTFDEBUG_H
 #define LLVM_LIB_TARGET_BPF_BTFDEBUG_H
 
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/CodeGen/DebugHandlerBase.h"
@@ -125,12 +126,13 @@ class BTFTypeArray : public BTFTypeBase {
 /// Handle struct/union type.
 class BTFTypeStruct : public BTFTypeBase {
   const DICompositeType *STy;
+  std::vector<const DINode *> Elements;
   bool HasBitField;
   std::vector<struct BTF::BTFMember> Members;
 
 public:
-  BTFTypeStruct(const DICompositeType *STy, bool IsStruct, bool HasBitField,
-                uint32_t NumMembers);
+  BTFTypeStruct(const DICompositeType *STy, ArrayRef<const DINode *> Elements,
+                bool IsStruct, bool HasBitField, uint32_t NumMembers);
   uint32_t getSize() override {
     return BTFTypeBase::getSize() + Members.size() * BTF::BTFMemberSize;
   }
diff --git a/llvm/test/CodeGen/BPF/BTF/struct-member-order.ll b/llvm/test/CodeGen/BPF/BTF/struct-member-order.ll
new file mode 100644
index 0000000000000..4d26013ff7c5f
--- /dev/null
+++ b/llvm/test/CodeGen/BPF/BTF/struct-member-order.ll
@@ -0,0 +1,38 @@
+; RUN: llc -mtriple=bpfel -filetype=obj -o %t1 %s
+; RUN: llvm-objcopy --dump-section='.BTF'=%t2 %t1
+; RUN: %python %p/print_btf.py %t2 | FileCheck %s
+; RUN: llc -mtriple=bpfeb -filetype=obj -o %t1 %s
+; RUN: llvm-objcopy --dump-section='.BTF'=%t2 %t1
+; RUN: %python %p/print_btf.py %t2 | FileCheck %s
+
+; Some languages preserve source order in DI even when the compiler lays out
+; fields in a different order. BTF requires struct member offsets to be
+; nondecreasing. The declaration tag must follow the reordered member.
+
+; CHECK:      [1] STRUCT 's' size=8 vlen=2
+; CHECK-NEXT:         'first' type_id=2 bits_offset=0
+; CHECK-NEXT:         'second' type_id=2 bits_offset=32
+; CHECK-NEXT: [2] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
+; CHECK-NEXT: [3] DECL_TAG 'second_tag' type_id=1 component_idx=1
+
+%struct.s = type { i32, i32 }
+
+ at value = global %struct.s zeroinitializer, align 4, !dbg !0
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!13, !14}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "value", scope: !2, file: !3, line: 1, type: !5, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_Rust, file: !3, producer: "rustc", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, globals: !4)
+!3 = !DIFile(filename: "test.rs", directory: "/")
+!4 = !{!0}
+!5 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "s", file: !3, line: 1, size: 64, elements: !6)
+!6 = !{!9, !7}
+!7 = !DIDerivedType(tag: DW_TAG_member, name: "first", scope: !5, file: !3, line: 1, baseType: !8, size: 32)
+!8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!9 = !DIDerivedType(tag: DW_TAG_member, name: "second", scope: !5, file: !3, line: 1, baseType: !8, size: 32, offset: 32, annotations: !10)
+!10 = !{!11}
+!11 = !{!"btf_decl_tag", !"second_tag"}
+!13 = !{i32 2, !"Debug Info Version", i32 3}
+!14 = !{i32 2, !"Dwarf Version", i32 4}
diff --git a/llvm/test/CodeGen/BPF/CORE/struct-member-order.ll b/llvm/test/CodeGen/BPF/CORE/struct-member-order.ll
new file mode 100644
index 0000000000000..1980843a6ad28
--- /dev/null
+++ b/llvm/test/CodeGen/BPF/CORE/struct-member-order.ll
@@ -0,0 +1,93 @@
+; RUN: opt -O2 %s | llc -mtriple=bpfel -filetype=asm -o - | FileCheck %s
+
+; The physical GEP index and DI member index differ because the DI elements are
+; in source order while the struct is laid out in offset order. The immediate
+; still comes from the original DI member, but the CO-RE access string must use
+; that member's position in BTF. Members with equal offsets retain DI order.
+
+; CHECK-LABEL: test:
+; CHECK:       [[TEST_RELOC:.Ltmp[0-9]+]]:
+; CHECK-NEXT:  r2 = 4
+; CHECK-LABEL: test_equal_offset:
+; CHECK:       [[EQUAL_RELOC:.Ltmp[0-9]+]]:
+; CHECK-NEXT:  r2 = 0
+
+; CHECK:       .section        .BTF
+; CHECK:       .long   [[#]]                    # BTF_KIND_STRUCT(id = [[STRUCT_ID:.*]])
+; CHECK:       .ascii  ".text"                  # string offset=[[TEXT:.*]]
+; CHECK:       .ascii  "0:2"                    # string offset=[[TEST_ACCESS:.*]]
+; CHECK:       .ascii  "0:1"                    # string offset=[[EQUAL_ACCESS:.*]]
+
+; CHECK:       .section        .BTF.ext
+; CHECK:       .long   [[#]]                    # FieldReloc
+; CHECK-NEXT:  .long   [[TEXT]]
+; CHECK-NEXT:  .long   2
+; CHECK-NEXT:  .long   [[TEST_RELOC]]
+; CHECK-NEXT:  .long   [[STRUCT_ID]]
+; CHECK-NEXT:  .long   [[TEST_ACCESS]]
+; CHECK-NEXT:  .long   0
+; CHECK-NEXT:  .long   [[EQUAL_RELOC]]
+; CHECK-NEXT:  .long   [[STRUCT_ID]]
+; CHECK-NEXT:  .long   [[EQUAL_ACCESS]]
+; CHECK-NEXT:  .long   0
+
+target triple = "bpf"
+
+%struct.s = type { i32, i32 }
+
+define dso_local i32 @test(ptr %arg) local_unnamed_addr !dbg !7 {
+entry:
+  call void @llvm.dbg.value(metadata ptr %arg, metadata !17, metadata !DIExpression()), !dbg !18
+  %field = tail call ptr @llvm.preserve.struct.access.index.p0.p0.ss(ptr elementtype(%struct.s) %arg, i32 1, i32 0), !dbg !19, !llvm.preserve.access.index !12
+  %call = tail call i32 @get_value(ptr %field), !dbg !20
+  ret i32 %call, !dbg !21
+}
+
+define dso_local i32 @test_equal_offset(ptr %arg) local_unnamed_addr !dbg !23 {
+entry:
+  call void @llvm.dbg.value(metadata ptr %arg, metadata !24, metadata !DIExpression()), !dbg !25
+  %field = tail call ptr @llvm.preserve.struct.access.index.p0.p0.ss(ptr elementtype(%struct.s) %arg, i32 0, i32 2), !dbg !26, !llvm.preserve.access.index !12
+  %call = tail call i32 @get_value(ptr %field), !dbg !27
+  ret i32 %call, !dbg !28
+}
+
+declare dso_local i32 @get_value(ptr) local_unnamed_addr
+
+declare ptr @llvm.preserve.struct.access.index.p0.p0.ss(ptr, i32 immarg, i32 immarg)
+
+declare void @llvm.dbg.value(metadata, metadata, metadata)
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_Rust, file: !1, producer: "rustc", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "test.rs", directory: "/")
+!2 = !{}
+!3 = !{i32 2, !"Dwarf Version", i32 4}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+!6 = !{!"rustc"}
+!7 = distinct !DISubprogram(name: "test", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !16)
+!8 = !DISubroutineType(types: !9)
+!9 = !{!10, !11}
+!10 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+!11 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !12, size: 64)
+!12 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "s", file: !1, line: 1, size: 64, elements: !13)
+!13 = !{!15, !14, !22}
+!14 = !DIDerivedType(tag: DW_TAG_member, name: "first", scope: !12, file: !1, line: 1, baseType: !10, size: 32)
+!15 = !DIDerivedType(tag: DW_TAG_member, name: "second", scope: !12, file: !1, line: 1, baseType: !10, size: 32, offset: 32)
+!16 = !{!17}
+!17 = !DILocalVariable(name: "arg", arg: 1, scope: !7, file: !1, line: 1, type: !11)
+!18 = !DILocation(line: 0, scope: !7)
+!19 = !DILocation(line: 1, column: 1, scope: !7)
+!20 = !DILocation(line: 1, column: 1, scope: !7)
+!21 = !DILocation(line: 1, column: 1, scope: !7)
+!22 = !DIDerivedType(tag: DW_TAG_member, name: "also_first", scope: !12, file: !1, line: 1, baseType: !10, size: 32)
+!23 = distinct !DISubprogram(name: "test_equal_offset", scope: !1, file: !1, line: 2, type: !8, scopeLine: 2, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !29)
+!24 = !DILocalVariable(name: "arg", arg: 1, scope: !23, file: !1, line: 2, type: !11)
+!25 = !DILocation(line: 0, scope: !23)
+!26 = !DILocation(line: 2, column: 1, scope: !23)
+!27 = !DILocation(line: 2, column: 1, scope: !23)
+!28 = !DILocation(line: 2, column: 1, scope: !23)
+!29 = !{!24}



More information about the llvm-commits mailing list