[llvm] [BPF] Support for `DW_TAG_variant_part` in BTF generation (PR #155783)

Michal R via llvm-commits llvm-commits at lists.llvm.org
Tue Oct 7 00:17:22 PDT 2025


================
@@ -301,21 +303,61 @@ void BTFTypeStruct::completeType(BTFDebug &BDebug) {
 
   BTFType.NameOff = BDebug.addString(STy->getName());
 
+  uint64_t InitialOffset = 0;
+  if (STy->getTag() == dwarf::DW_TAG_variant_part) {
+    // Variant parts have a discriminator, which has its own memory location at
+    // the beginning, and variants, which share the memory location afterwards.
+    // LLVM DI doesn't consider discriminator as an element and instead keeps
+    // it as a separate reference.
+    // To keep BTF simple, let's represent the structure as an union with
+    // discriminator as the first element and apply offsets to the other
+    // elements.
+    struct BTF::BTFMember Discriminator;
+    const auto *DDTy = STy->getDiscriminator();
+
+    InitialOffset += DDTy->getOffsetInBits() + DDTy->getSizeInBits();
----------------
vadorovsky wrote:

My worry is that we don't do the offset computation correctly, the BTF relocations done on variant parts won't work. Hypocritical of me given that I didn't get it right here (I'm very sorry, I'm still new to LLVM and compilers), but I really want to do it right. I'm planning to add BTF relocations for Rust BPF programs eventually (we want to emit them it in [bpf-linker](https://github.com/aya-rs/bpf-linker), given that we traverse patch bc/IR there) and it would be bad if I have to add yet another LLVM patch to fix it post-factum.

Regarding stability - I think the variant parts annotated with `#[repr(C)]` are guaranteed to be stable. `#[repr(Rust)]` could change the layout any time,  but I think it's fair to require the usage of `#[repr(C)]` in BPF programs.

https://github.com/llvm/llvm-project/pull/155783


More information about the llvm-commits mailing list