Index: ELF/OutputSections.cpp =================================================================== --- ELF/OutputSections.cpp +++ ELF/OutputSections.cpp @@ -285,7 +285,7 @@ if (auto *ex = dyn_cast(first)) link = ex->getLinkOrderDep()->getParent()->sectionIndex; else if (auto *d = first->getLinkOrderDep()) - link = d->getParent()->sectionIndex; + link = d->getParent() ? d->getParent()->sectionIndex : 0; } if (type == SHT_GROUP) { Index: ELF/Writer.cpp =================================================================== --- ELF/Writer.cpp +++ ELF/Writer.cpp @@ -1491,7 +1491,7 @@ OutputSection *bOut = lb->getParent(); if (aOut != bOut) - return aOut->sectionIndex < bOut->sectionIndex; + return !aOut || (bOut && aOut->sectionIndex < bOut->sectionIndex); return la->outSecOff < lb->outSecOff; } Index: test/ELF/section-metadata.s =================================================================== --- /dev/null +++ test/ELF/section-metadata.s @@ -0,0 +1,34 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64 %s -o %t.o +# RUN: ld.lld --gc-sections --print-gc-sections %t.o -o %t | FileCheck --check-prefix=PRINT %s --implicit-check-not {{.}} +# RUN: llvm-readelf -x .foo %t | FileCheck --check-prefix=HEX-GC %s + +# PRINT: removing unused section {{.*}}:(.bar1) + +# HEX-GC: 0100 + +# RUN: ld.lld -r %t.o -o %t1.o +# RUN: llvm-readelf -x .foo %t1.o | FileCheck --check-prefix=HEX-R %s +# HEX-R: 0001 + +.globl _start +_start: + call foo0 + call foo1 + call .bar0 + +.section .bar0,"a",@progbits +.section .bar1,"a",@progbits + +.section .foo,"ao",@progbits,.bar0,unique,0 +.globl foo0 +foo0: + .byte 0 + +## In the gc case, .bar1 is collected. We assume the linked-to section is SHN_UNDEF, so this +## .foo is placed before the previous one, when they are combined into the output +## section. +.section .foo,"ao",@progbits,.bar1,unique,1 +.globl foo1 +foo1: + .byte 1