llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
29.43k stars 12.16k forks source link

lld fails to reference static symbols when using LTO #60353

Open bc-lee opened 1 year ago

bc-lee commented 1 year ago

LLVM Version (as of writing):

$ clang-16 --version
Ubuntu clang version 16.0.0 (++20230125042347+9b70a28e0d76-1~exp1~20230125042505.706)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

Dockerfile with LLVM main branch. (It is also reproduced in LLVM 15)

FROM ubuntu:22.04

RUN apt-get update && \
    apt-get install -y curl ca-certificates lsb-release wget software-properties-common gnupg \
      git ninja-build

RUN curl -L https://apt.llvm.org/llvm.sh -o /tmp/llvm.sh && \
    chmod +x /tmp/llvm.sh && \
    /tmp/llvm.sh 16 all

RUN sed -Ei 's/^# deb-src /deb-src /' /etc/apt/sources.list && \
    apt-get update && \
    apt-get build-dep -y openttd

RUN cd /tmp \
    && git clone https://github.com/OpenTTD/OpenTTD \
    && cd OpenTTD \
    && git checkout -f 4dfd6a096f82b6a80629f373b2e2a1f11246891f

RUN cd /tmp/OpenTTD \
    && mkdir build \
    && cd build \
    && cmake .. -G Ninja \
      -DCMAKE_BUILD_TYPE=RelWithDebInfo \
      -DCMAKE_C_COMPILER=/usr/bin/clang-16 \
      -DCMAKE_CXX_COMPILER=/usr/bin/clang++-16 \
      -DCMAKE_AR=/usr/bin/llvm-ar-16 \
      -DCMAKE_RANLIB=/usr/bin/llvm-ranlib-16 \
      -DCMAKE_EXE_LINKER_FLAGS_INIT="-fuse-ld=lld" \
      -DCMAKE_MODULE_LINKER_FLAGS_INIT="-fuse-ld=lld" \
      -DCMAKE_SHARED_LINKER_FLAGS_INIT="-fuse-ld=lld" \
    && ninja

Expected: Link successfully.

Actual: Failed to link.

usr/bin/clang++-16 -O2 -g -DNDEBUG -flto=thin -fuse-ld=lld -rdynamic CMakeFiles/openttd.dir/generated/rev.cpp.o CMakeFiles/openttd.dir/src/script/api/script_accounting.cpp.o ...
ld.lld: error: undefined hidden symbol: _newgrf_textrefstack (.llvm.2775165945019663611)
>>> referenced by newgrf_text.cpp:764 (/tmp/OpenTTD/src/newgrf_text.cpp:764)
>>>               lto.tmp:(DrawVehiclePurchaseInfo(int, int, int, unsigned short, TestedEngineDetails&))
>>> referenced by newgrf_text.cpp:765 (/tmp/OpenTTD/src/newgrf_text.cpp:765)
>>>               lto.tmp:(DrawVehiclePurchaseInfo(int, int, int, unsigned short, TestedEngineDetails&))
>>> referenced by newgrf_text.cpp:766 (/tmp/OpenTTD/src/newgrf_text.cpp:766)
>>>               lto.tmp:(DrawVehiclePurchaseInfo(int, int, int, unsigned short, TestedEngineDetails&))

When I modified the code ( link ) to use __attribute__((used)), the link error went away.

llvmbot commented 1 year ago

@llvm/issue-subscribers-lld-elf