1# SPDX-License-Identifier: Apache-2.0
2#
3# Copyright (c) 2022, Nordic Semiconductor ASA
4# Copyright (c) 2023, Intel Corporation
5
6# FindGnuLd module for locating LLVM lld linker.
7#
8# The module defines the following variables:
9#
10# 'LLVMLLD_LINKER'
11# Path to LLVM lld linker
12# Set to 'LLVMLLD_LINKER-NOTFOUND' if ld was not found.
13#
14# 'LlvmLld_FOUND', 'LLVMLLD_FOUND'
15# True if LLVM lld was found.
16#
17# 'LLVMLLD_VERSION_STRING'
18# The version of LLVM lld.
19
20# See if the compiler has a preferred linker
21execute_process(COMMAND ${CMAKE_C_COMPILER} --print-prog-name=ld.lld
22                OUTPUT_VARIABLE LLVMLLD_LINKER
23                OUTPUT_STRIP_TRAILING_WHITESPACE)
24
25if(NOT EXISTS "${LLVMLLD_LINKER}")
26  # Need to clear it or else find_program() won't replace the value.
27  set(LLVMLLD_LINKER)
28
29  if(DEFINED TOOLCHAIN_HOME)
30    # Search for linker under TOOLCHAIN_HOME if it is defined
31    # to limit which linker to use, or else we would be using
32    # host tools.
33    set(LLD_SEARCH_PATH PATHS ${TOOLCHAIN_HOME} NO_DEFAULT_PATH)
34  endif()
35
36  # Note that, although there is lld, it cannot be used directly
37  # as it would complain about it not being a generic linker,
38  # and asks you to use ld.lld instead. So do not search for lld.
39  find_program(LLVMLLD_LINKER ld.lld ${LLD_SEARCH_PATH})
40endif()
41
42if(LLVMLLD_LINKER)
43  # Parse the 'ld.lld --version' output to find the installed version.
44  execute_process(
45    COMMAND
46    ${LLVMLLD_LINKER} --version
47    OUTPUT_VARIABLE llvmlld_version_output
48    ERROR_VARIABLE  llvmlld_error_output
49    RESULT_VARIABLE llvmlld_status
50    )
51
52  set(LLVMLLD_VERSION_STRING)
53  if(${llvmlld_status} EQUAL 0)
54    # Extract GNU ld version. Different distros have their
55    # own version scheme so we need to account for that.
56    # Examples:
57    # - "GNU ld (GNU Binutils for Ubuntu) 2.34"
58    # - "GNU ld (Zephyr SDK 0.15.2) 2.38"
59    # - "GNU ld (Gentoo 2.39 p5) 2.39.0"
60    string(REGEX MATCH
61           "LLD ([0-9]+[.][0-9]+[.]?[0-9]*).*"
62           out_var ${llvmlld_version_output})
63    set(LLVMLLD_VERSION_STRING ${CMAKE_MATCH_1})
64  endif()
65endif()
66
67find_package_handle_standard_args(LlvmLld
68                                  REQUIRED_VARS LLVMLLD_LINKER
69                                  VERSION_VAR LLVMLLD_VERSION_STRING
70)
71