1include(CMakePushCheckState)
2include(CheckSymbolExists)
3
4# Because compiler-rt spends a lot of time setting up custom compile flags,
5# define a handy helper function for it. The compile flags setting in CMake
6# has serious issues that make its syntax challenging at best.
7function(set_target_compile_flags target)
8  set(argstring "")
9  foreach(arg ${ARGN})
10    set(argstring "${argstring} ${arg}")
11  endforeach()
12  set_property(TARGET ${target} PROPERTY COMPILE_FLAGS "${argstring}")
13endfunction()
14
15function(set_target_link_flags target)
16  set(argstring "")
17  foreach(arg ${ARGN})
18    set(argstring "${argstring} ${arg}")
19  endforeach()
20  set_property(TARGET ${target} PROPERTY LINK_FLAGS "${argstring}")
21endfunction()
22
23# Set the variable var_PYBOOL to True if var holds a true-ish string,
24# otherwise set it to False.
25macro(pythonize_bool var)
26  if (${var})
27    set(${var}_PYBOOL True)
28  else()
29    set(${var}_PYBOOL False)
30  endif()
31endmacro()
32
33# Appends value to all lists in ARGN, if the condition is true.
34macro(append_list_if condition value)
35  if(${condition})
36    foreach(list ${ARGN})
37      list(APPEND ${list} ${value})
38    endforeach()
39  endif()
40endmacro()
41
42# Appends value to all strings in ARGN, if the condition is true.
43macro(append_string_if condition value)
44  if(${condition})
45    foreach(str ${ARGN})
46      set(${str} "${${str}} ${value}")
47    endforeach()
48  endif()
49endmacro()
50
51macro(append_rtti_flag polarity list)
52  if(${polarity})
53    append_list_if(COMPILER_RT_HAS_FRTTI_FLAG -frtti ${list})
54    append_list_if(COMPILER_RT_HAS_GR_FLAG /GR ${list})
55  else()
56    append_list_if(COMPILER_RT_HAS_FNO_RTTI_FLAG -fno-rtti ${list})
57    append_list_if(COMPILER_RT_HAS_GR_FLAG /GR- ${list})
58  endif()
59endmacro()
60
61macro(append_have_file_definition filename varname list)
62  check_include_file("${filename}" "${varname}")
63  if (NOT ${varname})
64    set("${varname}" 0)
65  endif()
66  list(APPEND ${list} "${varname}=${${varname}}")
67endmacro()
68
69macro(list_intersect output input1 input2)
70  set(${output})
71  foreach(it ${${input1}})
72    list(FIND ${input2} ${it} index)
73    if( NOT (index EQUAL -1))
74      list(APPEND ${output} ${it})
75    endif()
76  endforeach()
77endmacro()
78
79function(list_replace input_list old new)
80  set(replaced_list)
81  foreach(item ${${input_list}})
82    if(${item} STREQUAL ${old})
83      list(APPEND replaced_list ${new})
84    else()
85      list(APPEND replaced_list ${item})
86    endif()
87  endforeach()
88  set(${input_list} "${replaced_list}" PARENT_SCOPE)
89endfunction()
90
91# Takes ${ARGN} and puts only supported architectures in @out_var list.
92function(filter_available_targets out_var)
93  set(archs ${${out_var}})
94  foreach(arch ${ARGN})
95    list(FIND COMPILER_RT_SUPPORTED_ARCH ${arch} ARCH_INDEX)
96    if(NOT (ARCH_INDEX EQUAL -1) AND CAN_TARGET_${arch})
97      list(APPEND archs ${arch})
98    endif()
99  endforeach()
100  set(${out_var} ${archs} PARENT_SCOPE)
101endfunction()
102
103# Add $arch as supported with no additional flags.
104macro(add_default_target_arch arch)
105  set(TARGET_${arch}_CFLAGS "")
106  set(CAN_TARGET_${arch} 1)
107  list(APPEND COMPILER_RT_SUPPORTED_ARCH ${arch})
108endmacro()
109
110function(check_compile_definition def argstring out_var)
111  if("${def}" STREQUAL "")
112    set(${out_var} TRUE PARENT_SCOPE)
113    return()
114  endif()
115  cmake_push_check_state()
116  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${argstring}")
117  check_symbol_exists(${def} "" ${out_var})
118  cmake_pop_check_state()
119endfunction()
120
121# test_target_arch(<arch> <def> <target flags...>)
122# Checks if architecture is supported: runs host compiler with provided
123# flags to verify that:
124#   1) <def> is defined (if non-empty)
125#   2) simple file can be successfully built.
126# If successful, saves target flags for this architecture.
127macro(test_target_arch arch def)
128  set(TARGET_${arch}_CFLAGS ${ARGN})
129  set(TARGET_${arch}_LINK_FLAGS ${ARGN})
130  set(argstring "")
131  foreach(arg ${ARGN})
132    set(argstring "${argstring} ${arg}")
133  endforeach()
134  check_compile_definition("${def}" "${argstring}" HAS_${arch}_DEF)
135  if(NOT DEFINED CAN_TARGET_${arch})
136    if(NOT HAS_${arch}_DEF)
137      set(CAN_TARGET_${arch} FALSE)
138    elseif(TEST_COMPILE_ONLY)
139      try_compile_only(CAN_TARGET_${arch} ${TARGET_${arch}_CFLAGS})
140    else()
141      set(FLAG_NO_EXCEPTIONS "")
142      if(COMPILER_RT_HAS_FNO_EXCEPTIONS_FLAG)
143        set(FLAG_NO_EXCEPTIONS " -fno-exceptions ")
144      endif()
145      set(SAVED_CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS})
146      set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${argstring}")
147      try_compile(CAN_TARGET_${arch} ${CMAKE_BINARY_DIR} ${SIMPLE_SOURCE}
148                  COMPILE_DEFINITIONS "${TARGET_${arch}_CFLAGS} ${FLAG_NO_EXCEPTIONS}"
149                  OUTPUT_VARIABLE TARGET_${arch}_OUTPUT)
150      set(CMAKE_EXE_LINKER_FLAGS ${SAVED_CMAKE_EXE_LINKER_FLAGS})
151    endif()
152  endif()
153  if(${CAN_TARGET_${arch}})
154    list(APPEND COMPILER_RT_SUPPORTED_ARCH ${arch})
155  elseif("${COMPILER_RT_DEFAULT_TARGET_ARCH}" STREQUAL "${arch}" AND
156         COMPILER_RT_HAS_EXPLICIT_DEFAULT_TARGET_TRIPLE)
157    # Bail out if we cannot target the architecture we plan to test.
158    message(FATAL_ERROR "Cannot compile for ${arch}:\n${TARGET_${arch}_OUTPUT}")
159  endif()
160endmacro()
161
162macro(detect_target_arch)
163  check_symbol_exists(__arm__ "" __ARM)
164  check_symbol_exists(__aarch64__ "" __AARCH64)
165  check_symbol_exists(__x86_64__ "" __X86_64)
166  check_symbol_exists(__i386__ "" __I386)
167  check_symbol_exists(__mips__ "" __MIPS)
168  check_symbol_exists(__mips64__ "" __MIPS64)
169  check_symbol_exists(__powerpc64__ "" __PPC64)
170  check_symbol_exists(__powerpc64le__ "" __PPC64LE)
171  check_symbol_exists(__riscv "" __RISCV)
172  check_symbol_exists(__s390x__ "" __S390X)
173  check_symbol_exists(__wasm32__ "" __WEBASSEMBLY32)
174  check_symbol_exists(__wasm64__ "" __WEBASSEMBLY64)
175  if(__ARM)
176    add_default_target_arch(arm)
177  elseif(__AARCH64)
178    add_default_target_arch(aarch64)
179  elseif(__X86_64)
180    add_default_target_arch(x86_64)
181  elseif(__I386)
182    add_default_target_arch(i386)
183  elseif(__MIPS64) # must be checked before __MIPS
184    add_default_target_arch(mips64)
185  elseif(__MIPS)
186    add_default_target_arch(mips)
187  elseif(__PPC64)
188    add_default_target_arch(powerpc64)
189  elseif(__PPC64LE)
190    add_default_target_arch(powerpc64le)
191  elseif(__RISCV)
192    if(CMAKE_SIZEOF_VOID_P EQUAL "4")
193      add_default_target_arch(riscv32)
194    elseif(CMAKE_SIZEOF_VOID_P EQUAL "8")
195      add_default_target_arch(riscv64)
196    else()
197      message(FATAL_ERROR "Unsupport XLEN for RISC-V")
198    endif()
199  elseif(__S390X)
200    add_default_target_arch(s390x)
201  elseif(__WEBASSEMBLY32)
202    add_default_target_arch(wasm32)
203  elseif(__WEBASSEMBLY64)
204    add_default_target_arch(wasm64)
205  endif()
206endmacro()
207
208macro(load_llvm_config)
209  if (NOT LLVM_CONFIG_PATH)
210    find_program(LLVM_CONFIG_PATH "llvm-config"
211                 DOC "Path to llvm-config binary")
212    if (NOT LLVM_CONFIG_PATH)
213      message(FATAL_ERROR "llvm-config not found: specify LLVM_CONFIG_PATH")
214    endif()
215  endif()
216  execute_process(
217    COMMAND ${LLVM_CONFIG_PATH} "--obj-root" "--bindir" "--libdir" "--src-root"
218    RESULT_VARIABLE HAD_ERROR
219    OUTPUT_VARIABLE CONFIG_OUTPUT)
220  if (HAD_ERROR)
221    message(FATAL_ERROR "llvm-config failed with status ${HAD_ERROR}")
222  endif()
223  string(REGEX REPLACE "[ \t]*[\r\n]+[ \t]*" ";" CONFIG_OUTPUT ${CONFIG_OUTPUT})
224  list(GET CONFIG_OUTPUT 0 BINARY_DIR)
225  list(GET CONFIG_OUTPUT 1 TOOLS_BINARY_DIR)
226  list(GET CONFIG_OUTPUT 2 LIBRARY_DIR)
227  list(GET CONFIG_OUTPUT 3 MAIN_SRC_DIR)
228
229  set(LLVM_BINARY_DIR ${BINARY_DIR} CACHE PATH "Path to LLVM build tree")
230  set(LLVM_TOOLS_BINARY_DIR ${TOOLS_BINARY_DIR} CACHE PATH "Path to llvm/bin")
231  set(LLVM_LIBRARY_DIR ${LIBRARY_DIR} CACHE PATH "Path to llvm/lib")
232  set(LLVM_MAIN_SRC_DIR ${MAIN_SRC_DIR} CACHE PATH "Path to LLVM source tree")
233
234  # Make use of LLVM CMake modules.
235  # --cmakedir is supported since llvm r291218 (4.0 release)
236  execute_process(
237    COMMAND ${LLVM_CONFIG_PATH} --cmakedir
238    RESULT_VARIABLE HAD_ERROR
239    OUTPUT_VARIABLE CONFIG_OUTPUT)
240  if(NOT HAD_ERROR)
241    string(STRIP "${CONFIG_OUTPUT}" LLVM_CMAKE_PATH_FROM_LLVM_CONFIG)
242    file(TO_CMAKE_PATH ${LLVM_CMAKE_PATH_FROM_LLVM_CONFIG} LLVM_CMAKE_PATH)
243  else()
244    file(TO_CMAKE_PATH ${LLVM_BINARY_DIR} LLVM_BINARY_DIR_CMAKE_STYLE)
245    set(LLVM_CMAKE_PATH "${LLVM_BINARY_DIR_CMAKE_STYLE}/lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm")
246  endif()
247
248  list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_PATH}")
249  # Get some LLVM variables from LLVMConfig.
250  include("${LLVM_CMAKE_PATH}/LLVMConfig.cmake")
251
252  set(LLVM_LIBRARY_OUTPUT_INTDIR
253    ${LLVM_BINARY_DIR}/${CMAKE_CFG_INTDIR}/lib${LLVM_LIBDIR_SUFFIX})
254endmacro()
255
256macro(construct_compiler_rt_default_triple)
257  if(COMPILER_RT_DEFAULT_TARGET_ONLY)
258    if(DEFINED COMPILER_RT_DEFAULT_TARGET_TRIPLE)
259      message(FATAL_ERROR "COMPILER_RT_DEFAULT_TARGET_TRIPLE isn't supported when building for default target only")
260    endif()
261    set(COMPILER_RT_DEFAULT_TARGET_TRIPLE ${CMAKE_C_COMPILER_TARGET})
262  else()
263    set(COMPILER_RT_DEFAULT_TARGET_TRIPLE ${TARGET_TRIPLE} CACHE STRING
264          "Default triple for which compiler-rt runtimes will be built.")
265  endif()
266
267  if(DEFINED COMPILER_RT_TEST_TARGET_TRIPLE)
268    # Backwards compatibility: this variable used to be called
269    # COMPILER_RT_TEST_TARGET_TRIPLE.
270    set(COMPILER_RT_DEFAULT_TARGET_TRIPLE ${COMPILER_RT_TEST_TARGET_TRIPLE})
271  endif()
272
273  string(REPLACE "-" ";" TARGET_TRIPLE_LIST ${COMPILER_RT_DEFAULT_TARGET_TRIPLE})
274  list(GET TARGET_TRIPLE_LIST 0 COMPILER_RT_DEFAULT_TARGET_ARCH)
275  list(GET TARGET_TRIPLE_LIST 1 COMPILER_RT_DEFAULT_TARGET_OS)
276  list(LENGTH TARGET_TRIPLE_LIST TARGET_TRIPLE_LIST_LENGTH)
277  if(TARGET_TRIPLE_LIST_LENGTH GREATER 2)
278    list(GET TARGET_TRIPLE_LIST 2 COMPILER_RT_DEFAULT_TARGET_ABI)
279  endif()
280  # Determine if test target triple is specified explicitly, and doesn't match the
281  # default.
282  if(NOT COMPILER_RT_DEFAULT_TARGET_TRIPLE STREQUAL TARGET_TRIPLE)
283    set(COMPILER_RT_HAS_EXPLICIT_DEFAULT_TARGET_TRIPLE TRUE)
284  else()
285    set(COMPILER_RT_HAS_EXPLICIT_DEFAULT_TARGET_TRIPLE FALSE)
286  endif()
287endmacro()
288
289# Filter out generic versions of routines that are re-implemented in
290# architecture specific manner.  This prevents multiple definitions of the
291# same symbols, making the symbol selection non-deterministic.
292function(filter_builtin_sources output_var exclude_or_include excluded_list)
293  if(exclude_or_include STREQUAL "EXCLUDE")
294    set(filter_action GREATER)
295    set(filter_value -1)
296  elseif(exclude_or_include STREQUAL "INCLUDE")
297    set(filter_action LESS)
298    set(filter_value 0)
299  else()
300    message(FATAL_ERROR "filter_builtin_sources called without EXCLUDE|INCLUDE")
301  endif()
302
303  set(intermediate ${ARGN})
304  foreach (_file ${intermediate})
305    get_filename_component(_name_we ${_file} NAME_WE)
306    list(FIND ${excluded_list} ${_name_we} _found)
307    if(_found ${filter_action} ${filter_value})
308      list(REMOVE_ITEM intermediate ${_file})
309    elseif(${_file} MATCHES ".*/.*\\.S" OR ${_file} MATCHES ".*/.*\\.c")
310      get_filename_component(_name ${_file} NAME)
311      string(REPLACE ".S" ".c" _cname "${_name}")
312      list(REMOVE_ITEM intermediate ${_cname})
313    endif ()
314  endforeach ()
315  set(${output_var} ${intermediate} PARENT_SCOPE)
316endfunction()
317
318function(get_compiler_rt_target arch variable)
319  if(ANDROID AND ${arch} STREQUAL "i386")
320    set(target "i686${COMPILER_RT_OS_SUFFIX}-${COMPILER_RT_DEFAULT_TARGET_OS}")
321  else()
322    set(target "${arch}-${COMPILER_RT_DEFAULT_TARGET_OS}")
323  endif()
324  if(COMPILER_RT_DEFAULT_TARGET_ABI)
325    set(target "${target}-${COMPILER_RT_DEFAULT_TARGET_ABI}")
326  endif()
327  set(${variable} ${target} PARENT_SCOPE)
328endfunction()
329
330function(get_compiler_rt_install_dir arch install_dir)
331  if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
332    get_compiler_rt_target(${arch} target)
333    set(${install_dir} ${COMPILER_RT_INSTALL_PATH}/${target}/lib PARENT_SCOPE)
334  else()
335    set(${install_dir} ${COMPILER_RT_LIBRARY_INSTALL_DIR} PARENT_SCOPE)
336  endif()
337endfunction()
338
339function(get_compiler_rt_output_dir arch output_dir)
340  if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
341    get_compiler_rt_target(${arch} target)
342    set(${output_dir} ${COMPILER_RT_OUTPUT_DIR}/${target}/lib PARENT_SCOPE)
343  else()
344    set(${output_dir} ${COMPILER_RT_LIBRARY_OUTPUT_DIR} PARENT_SCOPE)
345  endif()
346endfunction()
347
348# compiler_rt_process_sources(
349#   <OUTPUT_VAR>
350#   <SOURCE_FILE> ...
351#  [ADDITIONAL_HEADERS <header> ...]
352# )
353#
354# Process the provided sources and write the list of new sources
355# into `<OUTPUT_VAR>`.
356#
357# ADDITIONAL_HEADERS     - Adds the supplied header to list of sources for IDEs.
358#
359# This function is very similar to `llvm_process_sources()` but exists here
360# because we need to support standalone builds of compiler-rt.
361function(compiler_rt_process_sources OUTPUT_VAR)
362  cmake_parse_arguments(
363    ARG
364    ""
365    ""
366    "ADDITIONAL_HEADERS"
367    ${ARGN}
368  )
369  set(sources ${ARG_UNPARSED_ARGUMENTS})
370  set(headers "")
371  if (XCODE OR MSVC_IDE OR CMAKE_EXTRA_GENERATOR)
372    # For IDEs we need to tell CMake about header files.
373    # Otherwise they won't show up in UI.
374    set(headers ${ARG_ADDITIONAL_HEADERS})
375    list(LENGTH headers headers_length)
376    if (${headers_length} GREATER 0)
377      set_source_files_properties(${headers}
378        PROPERTIES HEADER_FILE_ONLY ON)
379    endif()
380  endif()
381  set("${OUTPUT_VAR}" ${sources} ${headers} PARENT_SCOPE)
382endfunction()
383