yams/cmake/ToolchainDetect.cmake
2025-09-04 15:51:26 -04:00

66 lines
2.3 KiB
CMake

include(CheckCXXCompilerFlag)
include(CheckLinkerFlag)
include(CheckIPOSupported)
# Portable IPO/LTO detection (avoid in Debug)
check_ipo_supported(RESULT _YAMS_IPO_OK OUTPUT _YAMS_IPO_MSG)
# Multi-config generators: set per-config; Single-config: respect CMAKE_BUILD_TYPE
if(_YAMS_IPO_OK)
if(CMAKE_CONFIGURATION_TYPES)
foreach(_cfg Release RelWithDebInfo MinSizeRel)
string(TOUPPER "${_cfg}" _CFG_UP)
set("CMAKE_INTERPROCEDURAL_OPTIMIZATION_${_CFG_UP}" ON CACHE BOOL "IPO for ${_cfg}" FORCE)
endforeach()
# Ensure Debug stays off for fast, deterministic testing
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_DEBUG OFF CACHE BOOL "IPO for Debug" FORCE)
else()
if(CMAKE_BUILD_TYPE AND NOT CMAKE_BUILD_TYPE MATCHES "^[Dd]ebug$")
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON)
endif()
endif()
else()
message(STATUS "IPO/LTO not supported: ${_YAMS_IPO_MSG}")
endif()
# Control preferring LLD (-fuse-ld=lld) on ELF platforms (disabled on Apple)
if(NOT DEFINED YAMS_PREFER_LLD)
set(YAMS_PREFER_LLD ON)
endif()
# Prefer LLD when available (ELF platforms)
set(_YAMS_TRY_LLD FALSE)
# Only try LLD when explicitly preferred, not on Apple (Darwin) where -fuse-ld=lld is unsupported
if(YAMS_PREFER_LLD AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
check_linker_flag(CXX "-fuse-ld=lld" _YAMS_LLD_OK)
if(_YAMS_LLD_OK)
add_link_options(-fuse-ld=lld)
set(_YAMS_TRY_LLD TRUE)
message(STATUS "Using LLD via -fuse-ld=lld")
else()
message(STATUS "LLD not available; using default linker")
endif()
endif()
# Prefer ThinLTO under Clang for Release-like configs only
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
if(CMAKE_CONFIGURATION_TYPES)
# Apply per-config using generator expressions
add_link_options($<$<CONFIG:Release,RelWithDebInfo,MinSizeRel>:-flto=thin>)
else()
if(CMAKE_BUILD_TYPE AND NOT CMAKE_BUILD_TYPE MATCHES "^[Dd]ebug$")
add_link_options(-flto=thin)
endif()
endif()
message(STATUS "Clang detected; preferring ThinLTO in Release-like builds")
endif()
# Helpful defaults for Release builds
if(CMAKE_BUILD_TYPE MATCHES "^[Rr]elease$")
add_compile_options(-ffunction-sections -fdata-sections)
if(APPLE)
add_link_options(-Wl,-dead_strip)
elseif(_YAMS_TRY_LLD)
add_link_options(-Wl,--gc-sections)
endif()
endif()