From eeb27331dce40068705354643ce91a39f4ff1b64 Mon Sep 17 00:00:00 2001 From: Slava Zakharin Date: Fri, 14 Mar 2025 08:26:03 -0700 Subject: [PATCH] [flang-rt] Use --as-needed for linking flang-rt libraries. (#130856) This change makes sure that there is no unnecessary library dependencies like libc++/libstdc++. --- flang-rt/CMakeLists.txt | 6 ++++++ flang-rt/cmake/modules/AddFlangRT.cmake | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/flang-rt/CMakeLists.txt b/flang-rt/CMakeLists.txt index 9bc40e111c6b..a0b998dc3abd 100644 --- a/flang-rt/CMakeLists.txt +++ b/flang-rt/CMakeLists.txt @@ -244,6 +244,12 @@ check_cxx_compiler_flag("-UTESTFLAG" FLANG_RT_SUPPORTS_UNDEFINE_FLAG) # Check whether -fno-lto is supported. check_cxx_compiler_flag(-fno-lto FLANG_RT_HAS_FNO_LTO_FLAG) +# Check whether -Wl,--as-needed is supported. +check_linker_flag(C "LINKER:--as-needed" LINKER_SUPPORTS_AS_NEEDED) +if (LINKER_SUPPORTS_AS_NEEDED) + set(LINKER_AS_NEEDED_OPT "LINKER:--as-needed") +endif() + # Different platform may have different name for the POSIX thread library. # For example, libpthread.a on AIX. Search for it as it is needed when # building the shared flang_rt.runtime.so. diff --git a/flang-rt/cmake/modules/AddFlangRT.cmake b/flang-rt/cmake/modules/AddFlangRT.cmake index 2292732daba6..999128fcd55f 100644 --- a/flang-rt/cmake/modules/AddFlangRT.cmake +++ b/flang-rt/cmake/modules/AddFlangRT.cmake @@ -145,6 +145,20 @@ function (add_flangrt_library name) if (Threads_FOUND) target_link_libraries(${name_shared} PUBLIC Threads::Threads) endif () + + # Special dependencies handling for shared libraries only: + # + # flang-rt libraries must not depend on libc++/libstdc++, + # so set the linker language to C to avoid the unnecessary + # library dependence. Note that libc++/libstdc++ may still + # come through CMAKE_CXX_IMPLICIT_LINK_LIBRARIES. + set_target_properties(${name_shared} PROPERTIES LINKER_LANGUAGE C) + # Use --as-needed to avoid unnecessary dependencies. + if (LINKER_AS_NEEDED_OPT) + target_link_options(${name_shared} BEFORE PRIVATE + "${LINKER_AS_NEEDED_OPT}" + ) + endif() endif () if (libtargets)