diff --git a/lld/MachO/SymbolTable.cpp b/lld/MachO/SymbolTable.cpp --- a/lld/MachO/SymbolTable.cpp +++ b/lld/MachO/SymbolTable.cpp @@ -184,10 +184,18 @@ bool wasInserted; std::tie(s, wasInserted) = insert(name, file); - if (wasInserted) + if (wasInserted) { replaceSymbol(s, file, sym); - else if (isa(s) || (isa(s) && s->isWeakDef())) + } else if (isa(s)) { file->fetch(sym); + } else if (auto *dysym = dyn_cast(s)) { + if (dysym->isWeakDef()) { + if (dysym->getRefState() != RefState::Unreferenced) + file->fetch(sym); + else + replaceSymbol(s, file, sym); + } + } return s; } diff --git a/lld/test/MachO/weak-definition-direct-fetch.s b/lld/test/MachO/weak-definition-direct-fetch.s --- a/lld/test/MachO/weak-definition-direct-fetch.s +++ b/lld/test/MachO/weak-definition-direct-fetch.s @@ -55,7 +55,7 @@ # RUN: %lld -lSystem -o %t/nonweak-weak-archives %t/foo.a %t/weakfoo.a %t/test.o # RUN: llvm-objdump --macho --lazy-bind --syms %t/nonweak-weak-archives | FileCheck %s --check-prefix=PREFER-NONWEAK-OBJECT -## The remaining lines test symbol pairs of different types. +## The next 5 chunks test symbol pairs of different types. ## (Weak) archive symbols take precedence over weak dylib symbols. # RUN: %lld -lSystem -o %t/weak-dylib-weak-ar -L%t -lweakfoo %t/weakfoo.a %t/test.o @@ -87,6 +87,16 @@ # RUN: %lld -lSystem -o %t/nonweak-ar-weak-obj %t/foo.a %t/weakfoo.o %t/test.o # RUN: llvm-objdump --macho --lazy-bind --syms %t/nonweak-ar-weak-obj | FileCheck %s --check-prefix=PREFER-WEAK-OBJECT +## Regression test: A weak dylib symbol that isn't referenced by an undefined +## symbol should not cause an archive symbol to get loaded. +# RUN: %lld -dylib -lSystem -o %t/weak-ar-weak-unref-dylib -L%t %t/weakfoo.a -lweakfoo +# RUN: llvm-objdump --macho --lazy-bind --syms %t/weak-ar-weak-unref-dylib | FileCheck %s --check-prefix=NO-SYM +# RUN: %lld -dylib -lSystem -o %t/weak-unref-dylib-weak-ar -L%t -lweakfoo %t/weakfoo.a +# RUN: llvm-objdump --macho --lazy-bind --syms %t/weak-unref-dylib-weak-ar | FileCheck %s --check-prefix=NO-SYM + +# NO-SYM: SYMBOL TABLE: +# NO-SYM-NOT: _foo + #--- foo.s .globl _foo .section __TEXT,nonweak