[lld] [ELF] --gc-sections: keep a plain .gcc_except_table with its function (PR #229377)

via llvm-commits llvm-commits at lists.llvm.org
Tue Oct 6 04:01:30 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-backend-risc-v

@llvm/pr-subscribers-lld-elf

Author: Xeonacid (Xeonacid)

<details>
<summary>Changes</summary>

GCC -ffunction-sections -fexceptions emits one .gcc_except_table.<func> per function, with only SHF_ALLOC. The FDE in .eh_frame points at both the function and that table. LLD treated the table as reachable from .eh_frame, then followed relocations in the table back to the function. On RISC-V those relocations are R_RISCV_SET_ULEB128 and R_RISCV_SUB_ULEB128, which GCC emits because -mrelax leaves the call-site lengths unknown until link time. An unreferenced function was therefore kept, and an undefined symbol referenced only from that function failed the link. The same edge exists on other targets whenever the table has a relocation to its function.

GNU ld records the FDE on the text section it describes, and marks the LSDA only while that section is being marked. _bfd_elf_parse_eh_frame chains the FDE onto the section [1]. _bfd_elf_gc_mark follows that chain only for a section it is marking [2], and _bfd_elf_gc_mark_fdes marks the FDE relocations, including the LSDA [3]. An unreferenced function therefore drops both sections together.

Do the same here. A non-group, non-SHF_LINK_ORDER LSDA is added to the function's dependentSections instead of being enqueued from the FDE. If an FDE does not describe an executable section, the previous behavior remains.

This discards an unused plain .gcc_except_table even when it has no relocation back to the function. That table was previously retained. Nothing reads it once its function is gone, and the output .eh_frame drops the FDE of a dead function.

[1] https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=bfd/elf-eh-frame.c;hb=e838ff7efdee2779adec99567e88b59ab0e5d4d2#l933
[2] https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=bfd/elflink.c;hb=e838ff7efdee2779adec99567e88b59ab0e5d4d2#l14227
[3] https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=bfd/elf-eh-frame.c;hb=e838ff7efdee2779adec99567e88b59ab0e5d4d2#l1174

Assisted-by: Grok 4.7 (xhigh)

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


4 Files Affected:

- (modified) lld/ELF/MarkLive.cpp (+50-12) 
- (added) lld/test/ELF/gc-sections-lsda-reloc.s (+43) 
- (modified) lld/test/ELF/gc-sections-lsda.s (+9-3) 
- (modified) lld/test/ELF/riscv-reloc-leb128.s (+5-2) 


``````````diff
diff --git a/lld/ELF/MarkLive.cpp b/lld/ELF/MarkLive.cpp
index f5179bb2c60d0..8c760c797560c 100644
--- a/lld/ELF/MarkLive.cpp
+++ b/lld/ELF/MarkLive.cpp
@@ -194,12 +194,12 @@ void MarkLive<ELFT, TrackWhyLive>::resolveReloc(InputSectionBase &sec,
 // The last kind of relocation cannot keep the referred section alive, or they
 // would keep everything alive in a common object file. In fact, each FDE is
 // alive if the section it refers to is alive.
-// To keep things simple, in here we just ignore the last relocation kind. The
-// other two keep the referred section alive.
 //
-// A possible improvement would be to fully process .eh_frame in the middle of
-// the gc pass. With that we would be able to also gc some sections holding
-// LSDAs and personality functions if we found that they were unused.
+// A non-group, non-SHF_LINK_ORDER LSDA is not a GC root either. Record it as a
+// dependent of the function the FDE describes, and retain it only when that
+// function is retained. Relocations inside the LSDA, such as the
+// R_RISCV_{SET,SUB}_ULEB128 pairs GCC emits under -mrelax, are then not
+// followed for a function nothing else references.
 template <class ELFT, bool TrackWhyLive>
 void MarkLive<ELFT, TrackWhyLive>::scanEhFrameSection(EhInputSection &eh) {
   if (TrackWhyLive)
@@ -214,9 +214,47 @@ void MarkLive<ELFT, TrackWhyLive>::scanEhFrameSection(EhInputSection &eh) {
     if (firstRelI == (unsigned)-1)
       continue;
     uint64_t pieceEnd = fde.inputOff + fde.size;
-    for (size_t j = firstRelI, end2 = rels.size();
-         j < end2 && rels[j].offset < pieceEnd; ++j)
-      resolveReloc(eh, rels[j], true);
+    auto forEachRel = [&](auto fn) {
+      for (size_t j = firstRelI, end2 = rels.size();
+           j < end2 && rels[j].offset < pieceEnd; ++j)
+        fn(rels[j]);
+    };
+
+    // The described function is the executable section an FDE relocation
+    // points at. There is normally one, and it is the first relocation.
+    InputSection *func = nullptr;
+    forEachRel([&](const Relocation &rel) {
+      if (func)
+        return;
+      if (auto *d = dyn_cast<Defined>(rel.sym))
+        if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
+          if (sec->flags & SHF_EXECINSTR)
+            func = sec;
+    });
+
+    // No described function, for example an FDE left behind by ld.gold -r.
+    // Keep the historical behavior and retain the LSDA from the FDE.
+    if (!func) {
+      forEachRel([&](const Relocation &rel) { resolveReloc(eh, rel, true); });
+      continue;
+    }
+
+    forEachRel([&](const Relocation &rel) {
+      auto *d = dyn_cast<Defined>(rel.sym);
+      auto *sec = d ? dyn_cast_or_null<InputSection>(d->section) : nullptr;
+      if (sec && ((sec->flags & (SHF_EXECINSTR | SHF_LINK_ORDER)) ||
+                  sec->nextInSectionGroup)) {
+        rel.sym->setFlags(USED);
+        return;
+      }
+      if (sec) {
+        rel.sym->setFlags(USED);
+        if (!is_contained(func->dependentSections, sec))
+          func->dependentSections.push_back(sec);
+        return;
+      }
+      resolveReloc(eh, rel, true);
+    });
   }
 }
 
@@ -397,10 +435,10 @@ void MarkLive<ELFT, TrackWhyLive>::run() {
     markSymbol(ctx.symtab->cmseSymMap[symName].acleSeSym, "ARM CMSE symbol");
   }
 
-  // Mark .eh_frame sections as live because there are usually no relocations
-  // that point to .eh_frames. Otherwise, the garbage collector would drop
-  // all of them. We also want to preserve personality routines and LSDA
-  // referenced by .eh_frame sections, so we scan them for that here.
+  // There are usually no relocations pointing to .eh_frame. Scan CIEs for
+  // personality routines, and attach each FDE's LSDA to the function it
+  // describes. FDEs of discarded functions are dropped when the output
+  // .eh_frame is built.
   for (EhInputSection *eh : ctx.ehInputSections)
     scanEhFrameSection(*eh);
   // See markUsedSymbols.
diff --git a/lld/test/ELF/gc-sections-lsda-reloc.s b/lld/test/ELF/gc-sections-lsda-reloc.s
new file mode 100644
index 0000000000000..61ee315bc26f3
--- /dev/null
+++ b/lld/test/ELF/gc-sections-lsda-reloc.s
@@ -0,0 +1,43 @@
+# REQUIRES: x86
+# RUN: llvm-mc %s -o %t.o -filetype=obj -triple=x86_64-pc-linux
+
+## GCC -ffunction-sections -fexceptions gives each function a
+## .gcc_except_table.<func> that is not in a group and does not have
+## SHF_LINK_ORDER. On RISC-V -mrelax the table contains R_RISCV_SET_ULEB128 /
+## R_RISCV_SUB_ULEB128 relocations back to the function. The .quad below is
+## that edge on x86_64: the table points at the function, and the function
+## calls an undefined symbol.
+##
+## --gc-sections drops both sections when the function is unreferenced, so the
+## undefined symbol does not fail the link. Referencing the function keeps the
+## table and still reports the undefined symbol.
+
+# RUN: ld.lld --gc-sections --print-gc-sections -u live %t.o -o /dev/null | \
+# RUN:   FileCheck %s --check-prefix=GC
+# RUN: not ld.lld --gc-sections -u dead %t.o -o /dev/null 2>&1 | \
+# RUN:   FileCheck %s --check-prefix=UNDEF
+
+# GC-NOT: .text.live
+# GC:     removing unused section {{.*}}.o:(.text.dead)
+# GC:     removing unused section {{.*}}.o:(.gcc_except_table.dead)
+# GC-NOT: .text.live
+
+# UNDEF:      error: undefined symbol: missing
+# UNDEF-NEXT: >>> referenced by {{.*}}:(.text.dead+{{.*}})
+
+.globl live, dead
+.section .text.live,"ax", at progbits
+live:
+  ret
+
+.section .text.dead,"ax", at progbits
+dead:
+  .cfi_startproc
+  call missing
+  ret
+  .cfi_lsda 0x1b,.Llsda
+  .cfi_endproc
+
+.section .gcc_except_table.dead,"a", at progbits
+.Llsda:
+  .quad dead
diff --git a/lld/test/ELF/gc-sections-lsda.s b/lld/test/ELF/gc-sections-lsda.s
index 997e7c94f9b4e..c3f9b7a27136e 100644
--- a/lld/test/ELF/gc-sections-lsda.s
+++ b/lld/test/ELF/gc-sections-lsda.s
@@ -12,13 +12,19 @@
 # CHECK-NEXT: removing unused section {{.*}}.o:(.gcc_except_table._Z6comdatv)
 # CHECK-NEXT: removing unused section {{.*}}.o:(.gcc_except_table._Z9linkorderv)
 
-## An unused non-group non-SHF_LINK_ORDER .gcc_except_table is not discarded.
+## An unused non-group non-SHF_LINK_ORDER .gcc_except_table is discarded with
+## its function. The FDE describes the function; it does not keep either live.
 
 # RUN: ld.lld --gc-sections --print-gc-sections -u _Z6comdatv -u _Z9linkorderv %t.o -o /dev/null | \
-# RUN:   FileCheck /dev/null --implicit-check-not=.gcc_except_table
+# RUN:   FileCheck %s --check-prefix=PLAIN
+
+# PLAIN:     removing unused section {{.*}}.o:(.text._Z3foov)
+# PLAIN:     removing unused section {{.*}}.o:(.gcc_except_table._Z3foov)
+# PLAIN-NOT: .gcc_except_table._Z6comdatv
+# PLAIN-NOT: .gcc_except_table._Z9linkorderv
 
 ## If the text sections are live, the .gcc_except_table sections are retained as
-## well because they are referenced by .eh_frame pieces.
+## well.
 
 # RUN: ld.lld --gc-sections --print-gc-sections -u _Z3foov -u _Z6comdatv -u _Z9linkorderv %t.o -o /dev/null | \
 # RUN:   FileCheck %s --check-prefix=KEEP
diff --git a/lld/test/ELF/riscv-reloc-leb128.s b/lld/test/ELF/riscv-reloc-leb128.s
index 3c84ca7d04daa..b6a925507373d 100644
--- a/lld/test/ELF/riscv-reloc-leb128.s
+++ b/lld/test/ELF/riscv-reloc-leb128.s
@@ -78,11 +78,14 @@
 # PREEMPTABLE: error: relocation R_RISCV_SUB_ULEB128 cannot be used against symbol 'w1'; recompile with -fPIC
 
 #--- a.s
+.section .text.w,"axR"
+## This FDE must describe .text.w. .text.w is SHF_GNU_RETAIN, so its
+## .gcc_except_table stays live under --gc-sections. A .cfi_startproc
+## before this section would describe an empty .text instead, and that
+## table would be discarded with it.
 .cfi_startproc
 .cfi_lsda 0x1b,.LLSDA0
 .cfi_endproc
-
-.section .text.w,"axR"
 w1:
   call foo    # 4 bytes after relaxation
 w2:

``````````

</details>


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


More information about the llvm-commits mailing list