xref: /netbsd-src/external/apache2/llvm/dist/llvm/cmake/modules/AddLLVM.cmake (revision 82d56013d7b633d116a93943de88e08335357a7c)
1include(LLVMDistributionSupport)
2include(LLVMProcessSources)
3include(LLVM-Config)
4include(DetermineGCCCompatible)
5
6function(llvm_update_compile_flags name)
7  get_property(sources TARGET ${name} PROPERTY SOURCES)
8  if("${sources}" MATCHES "\\.c(;|$)")
9    set(update_src_props ON)
10  endif()
11
12  list(APPEND LLVM_COMPILE_CFLAGS " ${LLVM_COMPILE_FLAGS}")
13
14  # LLVM_REQUIRES_EH is an internal flag that individual targets can use to
15  # force EH
16  if(LLVM_REQUIRES_EH OR LLVM_ENABLE_EH)
17    if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
18      message(AUTHOR_WARNING "Exception handling requires RTTI. Enabling RTTI for ${name}")
19      set(LLVM_REQUIRES_RTTI ON)
20    endif()
21    if(MSVC)
22      list(APPEND LLVM_COMPILE_FLAGS "/EHsc")
23    endif()
24  else()
25    if(LLVM_COMPILER_IS_GCC_COMPATIBLE)
26      list(APPEND LLVM_COMPILE_FLAGS "-fno-exceptions")
27      if(NOT LLVM_ENABLE_UNWIND_TABLES)
28        list(APPEND LLVM_COMPILE_FLAGS "-fno-unwind-tables")
29        list(APPEND LLVM_COMPILE_FLAGS "-fno-asynchronous-unwind-tables")
30      endif()
31    elseif(MSVC)
32      list(APPEND LLVM_COMPILE_DEFINITIONS _HAS_EXCEPTIONS=0)
33      list(APPEND LLVM_COMPILE_FLAGS "/EHs-c-")
34    elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
35      list(APPEND LLVM_COMPILE_FLAGS "-qnoeh")
36    endif()
37  endif()
38
39  # LLVM_REQUIRES_RTTI is an internal flag that individual
40  # targets can use to force RTTI
41  set(LLVM_CONFIG_HAS_RTTI YES CACHE INTERNAL "")
42  if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
43    set(LLVM_CONFIG_HAS_RTTI NO CACHE INTERNAL "")
44    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_RTTI=0)
45    if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
46      list(APPEND LLVM_COMPILE_FLAGS "-fno-rtti")
47    elseif (MSVC)
48      list(APPEND LLVM_COMPILE_FLAGS "/GR-")
49    elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
50      list(APPEND LLVM_COMPILE_FLAGS "-qnortti")
51    endif ()
52  elseif(MSVC)
53    list(APPEND LLVM_COMPILE_FLAGS "/GR")
54  endif()
55
56  # Assume that;
57  #   - LLVM_COMPILE_FLAGS is list.
58  #   - PROPERTY COMPILE_FLAGS is string.
59  string(REPLACE ";" " " target_compile_flags " ${LLVM_COMPILE_FLAGS}")
60  string(REPLACE ";" " " target_compile_cflags " ${LLVM_COMPILE_CFLAGS}")
61
62  if(update_src_props)
63    foreach(fn ${sources})
64      get_filename_component(suf ${fn} EXT)
65      if("${suf}" STREQUAL ".cpp")
66        set_property(SOURCE ${fn} APPEND_STRING PROPERTY
67          COMPILE_FLAGS "${target_compile_flags}")
68      endif()
69      if("${suf}" STREQUAL ".c")
70        set_property(SOURCE ${fn} APPEND_STRING PROPERTY
71          COMPILE_FLAGS "${target_compile_cflags}")
72      endif()
73    endforeach()
74  else()
75    # Update target props, since all sources are C++.
76    set_property(TARGET ${name} APPEND_STRING PROPERTY
77      COMPILE_FLAGS "${target_compile_flags}")
78  endif()
79
80  set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS ${LLVM_COMPILE_DEFINITIONS})
81endfunction()
82
83function(add_llvm_symbol_exports target_name export_file)
84  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
85    set(native_export_file "${target_name}.exports")
86    add_custom_command(OUTPUT ${native_export_file}
87      COMMAND sed -e "s/^/_/" < ${export_file} > ${native_export_file}
88      DEPENDS ${export_file}
89      VERBATIM
90      COMMENT "Creating export file for ${target_name}")
91    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
92                 LINK_FLAGS " -Wl,-exported_symbols_list,\"${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}\"")
93  elseif(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
94    # FIXME: `-Wl,-bE:` bypasses whatever handling there is in the build
95    # compiler driver to defer to the specified export list.
96    set(native_export_file "${export_file}")
97    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
98                 LINK_FLAGS " -Wl,-bE:${export_file}")
99  elseif(LLVM_HAVE_LINK_VERSION_SCRIPT)
100    # Gold and BFD ld require a version script rather than a plain list.
101    set(native_export_file "${target_name}.exports")
102    # FIXME: Don't write the "local:" line on OpenBSD.
103    # in the export file, also add a linker script to version LLVM symbols (form: LLVM_N.M)
104    add_custom_command(OUTPUT ${native_export_file}
105      COMMAND echo "LLVM_${LLVM_VERSION_MAJOR} {" > ${native_export_file}
106      COMMAND grep -q "[[:alnum:]]" ${export_file} && echo "  global:" >> ${native_export_file} || :
107      COMMAND sed -e "s/$/;/" -e "s/^/    /" < ${export_file} >> ${native_export_file}
108      COMMAND echo "  local: *;" >> ${native_export_file}
109      COMMAND echo "};" >> ${native_export_file}
110      DEPENDS ${export_file}
111      VERBATIM
112      COMMENT "Creating export file for ${target_name}")
113    if (${LLVM_LINKER_IS_SOLARISLD})
114      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
115                   LINK_FLAGS "  -Wl,-M,\"${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}\"")
116    else()
117      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
118                   LINK_FLAGS "  -Wl,--version-script,\"${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}\"")
119    endif()
120  else()
121    set(native_export_file "${target_name}.def")
122
123    add_custom_command(OUTPUT ${native_export_file}
124      COMMAND "${Python3_EXECUTABLE}" -c "import sys;print(''.join(['EXPORTS\\n']+sys.stdin.readlines(),))"
125        < ${export_file} > ${native_export_file}
126      DEPENDS ${export_file}
127      VERBATIM
128      COMMENT "Creating export file for ${target_name}")
129    set(export_file_linker_flag "${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
130    if(MSVC)
131      set(export_file_linker_flag "/DEF:\"${export_file_linker_flag}\"")
132    endif()
133    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
134                 LINK_FLAGS " ${export_file_linker_flag}")
135  endif()
136
137  add_custom_target(${target_name}_exports DEPENDS ${native_export_file})
138  set_target_properties(${target_name}_exports PROPERTIES FOLDER "Misc")
139
140  get_property(srcs TARGET ${target_name} PROPERTY SOURCES)
141  foreach(src ${srcs})
142    get_filename_component(extension ${src} EXT)
143    if(extension STREQUAL ".cpp")
144      set(first_source_file ${src})
145      break()
146    endif()
147  endforeach()
148
149  # Force re-linking when the exports file changes. Actually, it
150  # forces recompilation of the source file. The LINK_DEPENDS target
151  # property only works for makefile-based generators.
152  # FIXME: This is not safe because this will create the same target
153  # ${native_export_file} in several different file:
154  # - One where we emitted ${target_name}_exports
155  # - One where we emitted the build command for the following object.
156  # set_property(SOURCE ${first_source_file} APPEND PROPERTY
157  #   OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file})
158
159  set_property(DIRECTORY APPEND
160    PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${native_export_file})
161
162  add_dependencies(${target_name} ${target_name}_exports)
163
164  # Add dependency to *_exports later -- CMake issue 14747
165  list(APPEND LLVM_COMMON_DEPENDS ${target_name}_exports)
166  set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE)
167endfunction(add_llvm_symbol_exports)
168
169if (NOT DEFINED LLVM_LINKER_DETECTED)
170  if(APPLE)
171    execute_process(
172      COMMAND "${CMAKE_LINKER}" -v
173      ERROR_VARIABLE stderr
174      )
175    if("${stderr}" MATCHES "PROJECT:ld64")
176      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
177      set(LLVM_LINKER_IS_LD64 YES CACHE INTERNAL "")
178      message(STATUS "Linker detection: ld64")
179    else()
180      set(LLVM_LINKER_DETECTED NO CACHE INTERNAL "")
181      message(STATUS "Linker detection: unknown")
182    endif()
183  elseif(NOT WIN32)
184    # Detect what linker we have here
185    if( LLVM_USE_LINKER )
186      set(command ${CMAKE_C_COMPILER} -fuse-ld=${LLVM_USE_LINKER} -Wl,--version)
187    else()
188      separate_arguments(flags UNIX_COMMAND "${CMAKE_EXE_LINKER_FLAGS}")
189      set(command ${CMAKE_C_COMPILER} ${flags} -Wl,--version)
190    endif()
191    execute_process(
192      COMMAND ${command}
193      OUTPUT_VARIABLE stdout
194      ERROR_VARIABLE stderr
195      )
196    if("${stdout}" MATCHES "GNU gold")
197      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
198      set(LLVM_LINKER_IS_GOLD YES CACHE INTERNAL "")
199      message(STATUS "Linker detection: GNU Gold")
200    elseif("${stdout}" MATCHES "^LLD")
201      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
202      set(LLVM_LINKER_IS_LLD YES CACHE INTERNAL "")
203      message(STATUS "Linker detection: LLD")
204    elseif("${stdout}" MATCHES "GNU ld")
205      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
206      set(LLVM_LINKER_IS_GNULD YES CACHE INTERNAL "")
207      message(STATUS "Linker detection: GNU ld")
208    elseif("${stderr}" MATCHES "Solaris Link Editors" OR
209           "${stdout}" MATCHES "Solaris Link Editors")
210      set(LLVM_LINKER_DETECTED YES CACHE INTERNAL "")
211      set(LLVM_LINKER_IS_SOLARISLD YES CACHE INTERNAL "")
212      message(STATUS "Linker detection: Solaris ld")
213    else()
214      set(LLVM_LINKER_DETECTED NO CACHE INTERNAL "")
215      message(STATUS "Linker detection: unknown")
216    endif()
217  endif()
218endif()
219
220function(add_link_opts target_name)
221  get_llvm_distribution(${target_name} in_distribution in_distribution_var)
222  if(NOT in_distribution)
223    # Don't LTO optimize targets that aren't part of any distribution.
224    if (LLVM_ENABLE_LTO)
225      # We may consider avoiding LTO altogether by using -fembed-bitcode
226      # and teaching the linker to select machine code from .o files, see
227      # https://lists.llvm.org/pipermail/llvm-dev/2021-April/149843.html
228      if((UNIX OR MINGW) AND LLVM_USE_LINKER STREQUAL "lld")
229        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
230                      LINK_FLAGS " -Wl,--lto-O0")
231      elseif(LINKER_IS_LLD_LINK)
232        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
233                      LINK_FLAGS " /opt:lldlto=0")
234      endif()
235    endif()
236  endif()
237
238  # Don't use linker optimizations in debug builds since it slows down the
239  # linker in a context where the optimizations are not important.
240  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
241
242    # Pass -O3 to the linker. This enabled different optimizations on different
243    # linkers.
244    if(NOT (CMAKE_SYSTEM_NAME MATCHES "Darwin|SunOS|AIX|OS390" OR WIN32) AND in_distribution)
245      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
246                   LINK_FLAGS " -Wl,-O3")
247    endif()
248
249    if(NOT LLVM_NO_DEAD_STRIP)
250      if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
251        # ld64's implementation of -dead_strip breaks tools that use plugins.
252        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
253                     LINK_FLAGS " -Wl,-dead_strip")
254      elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
255        # Support for ld -z discard-unused=sections was only added in
256        # Solaris 11.4.
257        include(LLVMCheckLinkerFlag)
258        llvm_check_linker_flag(CXX "-Wl,-z,discard-unused=sections" LINKER_SUPPORTS_Z_DISCARD_UNUSED)
259        if (LINKER_SUPPORTS_Z_DISCARD_UNUSED)
260          set_property(TARGET ${target_name} APPEND_STRING PROPERTY
261                       LINK_FLAGS " -Wl,-z,discard-unused=sections")
262        endif()
263      elseif(NOT MSVC AND NOT CMAKE_SYSTEM_NAME MATCHES "OpenBSD|AIX|OS390")
264        # TODO Revisit this later on z/OS.
265        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
266                     LINK_FLAGS " -Wl,--gc-sections")
267      endif()
268    else() #LLVM_NO_DEAD_STRIP
269      if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
270        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
271                     LINK_FLAGS " -Wl,-bnogc")
272      endif()
273    endif()
274  endif()
275
276  if(ARG_SUPPORT_PLUGINS AND ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
277    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
278                 LINK_FLAGS " -Wl,-brtl")
279  endif()
280endfunction(add_link_opts)
281
282# Set each output directory according to ${CMAKE_CONFIGURATION_TYPES}.
283# Note: Don't set variables CMAKE_*_OUTPUT_DIRECTORY any more,
284# or a certain builder, for eaxample, msbuild.exe, would be confused.
285function(set_output_directory target)
286  cmake_parse_arguments(ARG "" "BINARY_DIR;LIBRARY_DIR" "" ${ARGN})
287
288  # module_dir -- corresponding to LIBRARY_OUTPUT_DIRECTORY.
289  # It affects output of add_library(MODULE).
290  if(WIN32 OR CYGWIN)
291    # DLL platform
292    set(module_dir ${ARG_BINARY_DIR})
293  else()
294    set(module_dir ${ARG_LIBRARY_DIR})
295  endif()
296  if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
297    foreach(build_mode ${CMAKE_CONFIGURATION_TYPES})
298      string(TOUPPER "${build_mode}" CONFIG_SUFFIX)
299      if(ARG_BINARY_DIR)
300        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} bi ${ARG_BINARY_DIR})
301        set_target_properties(${target} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${bi})
302      endif()
303      if(ARG_LIBRARY_DIR)
304        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} li ${ARG_LIBRARY_DIR})
305        set_target_properties(${target} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${li})
306      endif()
307      if(module_dir)
308        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} mi ${module_dir})
309        set_target_properties(${target} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${mi})
310      endif()
311    endforeach()
312  else()
313    if(ARG_BINARY_DIR)
314      set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ARG_BINARY_DIR})
315    endif()
316    if(ARG_LIBRARY_DIR)
317      set_target_properties(${target} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${ARG_LIBRARY_DIR})
318    endif()
319    if(module_dir)
320      set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${module_dir})
321    endif()
322  endif()
323endfunction()
324
325# If on Windows and building with MSVC, add the resource script containing the
326# VERSIONINFO data to the project.  This embeds version resource information
327# into the output .exe or .dll.
328# TODO: Enable for MinGW Windows builds too.
329#
330function(add_windows_version_resource_file OUT_VAR)
331  set(sources ${ARGN})
332  if (MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
333    set(resource_file ${LLVM_SOURCE_DIR}/resources/windows_version_resource.rc)
334    if(EXISTS ${resource_file})
335      set(sources ${sources} ${resource_file})
336      source_group("Resource Files" ${resource_file})
337      set(windows_resource_file ${resource_file} PARENT_SCOPE)
338    endif()
339  endif(MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
340
341  set(${OUT_VAR} ${sources} PARENT_SCOPE)
342endfunction(add_windows_version_resource_file)
343
344# set_windows_version_resource_properties(name resource_file...
345#   VERSION_MAJOR int
346#     Optional major version number (defaults to LLVM_VERSION_MAJOR)
347#   VERSION_MINOR int
348#     Optional minor version number (defaults to LLVM_VERSION_MINOR)
349#   VERSION_PATCHLEVEL int
350#     Optional patchlevel version number (defaults to LLVM_VERSION_PATCH)
351#   VERSION_STRING
352#     Optional version string (defaults to PACKAGE_VERSION)
353#   PRODUCT_NAME
354#     Optional product name string (defaults to "LLVM")
355#   )
356function(set_windows_version_resource_properties name resource_file)
357  cmake_parse_arguments(ARG
358    ""
359    "VERSION_MAJOR;VERSION_MINOR;VERSION_PATCHLEVEL;VERSION_STRING;PRODUCT_NAME"
360    ""
361    ${ARGN})
362
363  if (NOT DEFINED ARG_VERSION_MAJOR)
364    set(ARG_VERSION_MAJOR ${LLVM_VERSION_MAJOR})
365  endif()
366
367  if (NOT DEFINED ARG_VERSION_MINOR)
368    set(ARG_VERSION_MINOR ${LLVM_VERSION_MINOR})
369  endif()
370
371  if (NOT DEFINED ARG_VERSION_PATCHLEVEL)
372    set(ARG_VERSION_PATCHLEVEL ${LLVM_VERSION_PATCH})
373  endif()
374
375  if (NOT DEFINED ARG_VERSION_STRING)
376    set(ARG_VERSION_STRING ${PACKAGE_VERSION})
377  endif()
378
379  if (NOT DEFINED ARG_PRODUCT_NAME)
380    set(ARG_PRODUCT_NAME "LLVM")
381  endif()
382
383  set_property(SOURCE ${resource_file}
384               PROPERTY COMPILE_FLAGS /nologo)
385  set_property(SOURCE ${resource_file}
386               PROPERTY COMPILE_DEFINITIONS
387               "RC_VERSION_FIELD_1=${ARG_VERSION_MAJOR}"
388               "RC_VERSION_FIELD_2=${ARG_VERSION_MINOR}"
389               "RC_VERSION_FIELD_3=${ARG_VERSION_PATCHLEVEL}"
390               "RC_VERSION_FIELD_4=0"
391               "RC_FILE_VERSION=\"${ARG_VERSION_STRING}\""
392               "RC_INTERNAL_NAME=\"${name}\""
393               "RC_PRODUCT_NAME=\"${ARG_PRODUCT_NAME}\""
394               "RC_PRODUCT_VERSION=\"${ARG_VERSION_STRING}\"")
395endfunction(set_windows_version_resource_properties)
396
397# llvm_add_library(name sources...
398#   SHARED;STATIC
399#     STATIC by default w/o BUILD_SHARED_LIBS.
400#     SHARED by default w/  BUILD_SHARED_LIBS.
401#   OBJECT
402#     Also create an OBJECT library target. Default if STATIC && SHARED.
403#   MODULE
404#     Target ${name} might not be created on unsupported platforms.
405#     Check with "if(TARGET ${name})".
406#   DISABLE_LLVM_LINK_LLVM_DYLIB
407#     Do not link this library to libLLVM, even if
408#     LLVM_LINK_LLVM_DYLIB is enabled.
409#   OUTPUT_NAME name
410#     Corresponds to OUTPUT_NAME in target properties.
411#   DEPENDS targets...
412#     Same semantics as add_dependencies().
413#   LINK_COMPONENTS components...
414#     Same as the variable LLVM_LINK_COMPONENTS.
415#   LINK_LIBS lib_targets...
416#     Same semantics as target_link_libraries().
417#   ADDITIONAL_HEADERS
418#     May specify header files for IDE generators.
419#   SONAME
420#     Should set SONAME link flags and create symlinks
421#   NO_INSTALL_RPATH
422#     Suppress default RPATH settings in shared libraries.
423#   PLUGIN_TOOL
424#     The tool (i.e. cmake target) that this plugin will link against
425#   COMPONENT_LIB
426#      This is used to specify that this is a component library of
427#      LLVM which means that the source resides in llvm/lib/ and it is a
428#      candidate for inclusion into libLLVM.so.
429#   )
430function(llvm_add_library name)
431  cmake_parse_arguments(ARG
432    "MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME;NO_INSTALL_RPATH;COMPONENT_LIB"
433    "OUTPUT_NAME;PLUGIN_TOOL;ENTITLEMENTS;BUNDLE_PATH"
434    "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
435    ${ARGN})
436  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
437  if(ARG_ADDITIONAL_HEADERS)
438    # Pass through ADDITIONAL_HEADERS.
439    set(ARG_ADDITIONAL_HEADERS ADDITIONAL_HEADERS ${ARG_ADDITIONAL_HEADERS})
440  endif()
441  if(ARG_OBJLIBS)
442    set(ALL_FILES ${ARG_OBJLIBS})
443  else()
444    llvm_process_sources(ALL_FILES ${ARG_UNPARSED_ARGUMENTS} ${ARG_ADDITIONAL_HEADERS})
445  endif()
446
447  if(ARG_MODULE)
448    if(ARG_SHARED OR ARG_STATIC)
449      message(WARNING "MODULE with SHARED|STATIC doesn't make sense.")
450    endif()
451    # Plugins that link against a tool are allowed even when plugins in general are not
452    if(NOT LLVM_ENABLE_PLUGINS AND NOT (ARG_PLUGIN_TOOL AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS))
453      message(STATUS "${name} ignored -- Loadable modules not supported on this platform.")
454      return()
455    endif()
456  else()
457    if(ARG_PLUGIN_TOOL)
458      message(WARNING "PLUGIN_TOOL without MODULE doesn't make sense.")
459    endif()
460    if(BUILD_SHARED_LIBS AND NOT ARG_STATIC)
461      set(ARG_SHARED TRUE)
462    endif()
463    if(NOT ARG_SHARED)
464      set(ARG_STATIC TRUE)
465    endif()
466  endif()
467
468  # Generate objlib
469  if((ARG_SHARED AND ARG_STATIC) OR ARG_OBJECT)
470    # Generate an obj library for both targets.
471    set(obj_name "obj.${name}")
472    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
473      ${ALL_FILES}
474      )
475    llvm_update_compile_flags(${obj_name})
476    if(CMAKE_GENERATOR STREQUAL "Xcode")
477      set(DUMMY_FILE ${CMAKE_CURRENT_BINARY_DIR}/Dummy.c)
478      file(WRITE ${DUMMY_FILE} "// This file intentionally empty\n")
479      set_property(SOURCE ${DUMMY_FILE} APPEND_STRING PROPERTY COMPILE_FLAGS "-Wno-empty-translation-unit")
480    endif()
481    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>" ${DUMMY_FILE})
482
483    # Do add_dependencies(obj) later due to CMake issue 14747.
484    list(APPEND objlibs ${obj_name})
485
486    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
487    if(ARG_DEPENDS)
488      add_dependencies(${obj_name} ${ARG_DEPENDS})
489    endif()
490    # Treat link libraries like PUBLIC dependencies.  LINK_LIBS might
491    # result in generating header files.  Add a dependendency so that
492    # the generated header is created before this object library.
493    if(ARG_LINK_LIBS)
494      cmake_parse_arguments(LINK_LIBS_ARG
495        ""
496        ""
497        "PUBLIC;PRIVATE"
498        ${ARG_LINK_LIBS})
499      foreach(link_lib ${LINK_LIBS_ARG_PUBLIC})
500        if(LLVM_PTHREAD_LIB)
501          # Can't specify a dependence on -lpthread
502          if(NOT ${link_lib} STREQUAL ${LLVM_PTHREAD_LIB})
503            add_dependencies(${obj_name} ${link_lib})
504          endif()
505        else()
506          add_dependencies(${obj_name} ${link_lib})
507        endif()
508      endforeach()
509    endif()
510  endif()
511
512  if(ARG_SHARED AND ARG_STATIC)
513    # static
514    set(name_static "${name}_static")
515    if(ARG_OUTPUT_NAME)
516      set(output_name OUTPUT_NAME "${ARG_OUTPUT_NAME}")
517    endif()
518    # DEPENDS has been appended to LLVM_COMMON_LIBS.
519    llvm_add_library(${name_static} STATIC
520      ${output_name}
521      OBJLIBS ${ALL_FILES} # objlib
522      LINK_LIBS ${ARG_LINK_LIBS}
523      LINK_COMPONENTS ${ARG_LINK_COMPONENTS}
524      )
525    # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY.
526    set(ARG_STATIC)
527  endif()
528
529  if(ARG_MODULE)
530    add_library(${name} MODULE ${ALL_FILES})
531  elseif(ARG_SHARED)
532    add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
533    add_library(${name} SHARED ${ALL_FILES})
534  else()
535    add_library(${name} STATIC ${ALL_FILES})
536  endif()
537
538  if(ARG_COMPONENT_LIB)
539    set_target_properties(${name} PROPERTIES LLVM_COMPONENT TRUE)
540    set_property(GLOBAL APPEND PROPERTY LLVM_COMPONENT_LIBS ${name})
541  endif()
542
543  if(NOT ARG_NO_INSTALL_RPATH)
544    if(ARG_MODULE OR ARG_SHARED)
545      llvm_setup_rpath(${name})
546    endif()
547  endif()
548
549  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
550
551  if(DEFINED windows_resource_file)
552    set_windows_version_resource_properties(${name} ${windows_resource_file})
553    set(windows_resource_file ${windows_resource_file} PARENT_SCOPE)
554  endif()
555
556  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
557  # $<TARGET_OBJECTS> doesn't require compile flags.
558  if(NOT obj_name)
559    llvm_update_compile_flags(${name})
560  endif()
561  add_link_opts( ${name} )
562  if(ARG_OUTPUT_NAME)
563    set_target_properties(${name}
564      PROPERTIES
565      OUTPUT_NAME ${ARG_OUTPUT_NAME}
566      )
567  endif()
568
569  if(ARG_MODULE)
570    set_target_properties(${name} PROPERTIES
571      PREFIX ""
572      SUFFIX ${LLVM_PLUGIN_EXT}
573      )
574  endif()
575
576  if(ARG_SHARED)
577    if(MSVC)
578      set_target_properties(${name} PROPERTIES
579        PREFIX ""
580        )
581    endif()
582
583    # Set SOVERSION on shared libraries that lack explicit SONAME
584    # specifier, on *nix systems that are not Darwin.
585    if(UNIX AND NOT APPLE AND NOT ARG_SONAME)
586      set_target_properties(${name}
587        PROPERTIES
588        # Since 4.0.0, the ABI version is indicated by the major version
589        SOVERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX}
590        VERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
591    endif()
592  endif()
593
594  if(ARG_MODULE OR ARG_SHARED)
595    # Do not add -Dname_EXPORTS to the command-line when building files in this
596    # target. Doing so is actively harmful for the modules build because it
597    # creates extra module variants, and not useful because we don't use these
598    # macros.
599    set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
600
601    if (LLVM_EXPORTED_SYMBOL_FILE)
602      add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
603    endif()
604  endif()
605
606  if(ARG_SHARED AND UNIX)
607    if(NOT APPLE AND ARG_SONAME)
608      get_target_property(output_name ${name} OUTPUT_NAME)
609      if(${output_name} STREQUAL "output_name-NOTFOUND")
610        set(output_name ${name})
611      endif()
612      set(library_name ${output_name}-${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
613      set(api_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX})
614      set_target_properties(${name} PROPERTIES OUTPUT_NAME ${library_name})
615      llvm_install_library_symlink(${api_name} ${library_name} SHARED
616        COMPONENT ${name})
617      llvm_install_library_symlink(${output_name} ${library_name} SHARED
618        COMPONENT ${name})
619    endif()
620  endif()
621
622  if(ARG_STATIC)
623    set(libtype PUBLIC)
624  else()
625    # We can use PRIVATE since SO knows its dependent libs.
626    set(libtype PRIVATE)
627  endif()
628
629  if(ARG_MODULE AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS AND ARG_PLUGIN_TOOL AND (WIN32 OR CYGWIN))
630    # On DLL platforms symbols are imported from the tool by linking against it.
631    set(llvm_libs ${ARG_PLUGIN_TOOL})
632  elseif (NOT ARG_COMPONENT_LIB)
633    if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
634      set(llvm_libs LLVM)
635    else()
636      llvm_map_components_to_libnames(llvm_libs
637       ${ARG_LINK_COMPONENTS}
638       ${LLVM_LINK_COMPONENTS}
639       )
640    endif()
641  else()
642    # Components have not been defined explicitly in CMake, so add the
643    # dependency information for this library through their name, and let
644    # LLVMBuildResolveComponentsLink resolve the mapping.
645    #
646    # It would be nice to verify that we have the dependencies for this library
647    # name, but using get_property(... SET) doesn't suffice to determine if a
648    # property has been set to an empty value.
649    set_property(TARGET ${name} PROPERTY LLVM_LINK_COMPONENTS ${ARG_LINK_COMPONENTS} ${LLVM_LINK_COMPONENTS})
650
651    # These two properties are internal properties only used to make sure the
652    # link step applied in LLVMBuildResolveComponentsLink uses the same
653    # properties as the target_link_libraries call below.
654    set_property(TARGET ${name} PROPERTY LLVM_LINK_LIBS ${ARG_LINK_LIBS})
655    set_property(TARGET ${name} PROPERTY LLVM_LIBTYPE ${libtype})
656  endif()
657
658  target_link_libraries(${name} ${libtype}
659      ${ARG_LINK_LIBS}
660      ${lib_deps}
661      ${llvm_libs}
662      )
663
664  if(LLVM_COMMON_DEPENDS)
665    add_dependencies(${name} ${LLVM_COMMON_DEPENDS})
666    # Add dependencies also to objlibs.
667    # CMake issue 14747 --  add_dependencies() might be ignored to objlib's user.
668    foreach(objlib ${objlibs})
669      add_dependencies(${objlib} ${LLVM_COMMON_DEPENDS})
670    endforeach()
671  endif()
672
673  if(ARG_SHARED OR ARG_MODULE)
674    llvm_externalize_debuginfo(${name})
675    llvm_codesign(${name} ENTITLEMENTS ${ARG_ENTITLEMENTS} BUNDLE_PATH ${ARG_BUNDLE_PATH})
676  endif()
677  # clang and newer versions of ninja use high-resolutions timestamps,
678  # but older versions of libtool on Darwin don't, so the archive will
679  # often get an older timestamp than the last object that was added
680  # or updated.  To fix this, we add a custom command to touch archive
681  # after it's been built so that ninja won't rebuild it unnecessarily
682  # the next time it's run.
683  if(ARG_STATIC AND LLVM_TOUCH_STATIC_LIBRARIES)
684    add_custom_command(TARGET ${name}
685      POST_BUILD
686      COMMAND touch ${LLVM_LIBRARY_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}${name}${CMAKE_STATIC_LIBRARY_SUFFIX}
687      )
688  endif()
689endfunction()
690
691function(add_llvm_install_targets target)
692  cmake_parse_arguments(ARG "" "COMPONENT;PREFIX;SYMLINK" "DEPENDS" ${ARGN})
693  if(ARG_COMPONENT)
694    set(component_option -DCMAKE_INSTALL_COMPONENT="${ARG_COMPONENT}")
695  endif()
696  if(ARG_PREFIX)
697    set(prefix_option -DCMAKE_INSTALL_PREFIX="${ARG_PREFIX}")
698  endif()
699
700  set(file_dependencies)
701  set(target_dependencies)
702  foreach(dependency ${ARG_DEPENDS})
703    if(TARGET ${dependency})
704      list(APPEND target_dependencies ${dependency})
705    else()
706      list(APPEND file_dependencies ${dependency})
707    endif()
708  endforeach()
709
710  add_custom_target(${target}
711                    DEPENDS ${file_dependencies}
712                    COMMAND "${CMAKE_COMMAND}"
713                            ${component_option}
714                            ${prefix_option}
715                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
716                    USES_TERMINAL)
717  add_custom_target(${target}-stripped
718                    DEPENDS ${file_dependencies}
719                    COMMAND "${CMAKE_COMMAND}"
720                            ${component_option}
721                            ${prefix_option}
722                            -DCMAKE_INSTALL_DO_STRIP=1
723                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
724                    USES_TERMINAL)
725  if(target_dependencies)
726    add_dependencies(${target} ${target_dependencies})
727    add_dependencies(${target}-stripped ${target_dependencies})
728  endif()
729
730  if(ARG_SYMLINK)
731    add_dependencies(${target} install-${ARG_SYMLINK})
732    add_dependencies(${target}-stripped install-${ARG_SYMLINK}-stripped)
733  endif()
734endfunction()
735
736# Define special targets that behave like a component group. They don't have any
737# source attached but other components can add themselves to them. If the
738# component supports is a Target and it supports JIT compilation, HAS_JIT must
739# be passed. One can use ADD_TO_COMPONENT option from add_llvm_component_library
740# to link extra component into an existing group.
741function(add_llvm_component_group name)
742  cmake_parse_arguments(ARG "HAS_JIT" "" "LINK_COMPONENTS" ${ARGN})
743  add_custom_target(${name})
744  if(ARG_HAS_JIT)
745    set_property(TARGET ${name} PROPERTY COMPONENT_HAS_JIT ON)
746  endif()
747  if(ARG_LINK_COMPONENTS)
748    set_property(TARGET ${name} PROPERTY LLVM_LINK_COMPONENTS ${ARG_LINK_COMPONENTS})
749  endif()
750endfunction()
751
752# An LLVM component is a cmake target with the following cmake properties
753# eventually set:
754#   - LLVM_COMPONENT_NAME: the name of the component, which can be the name of
755#     the associated library or the one specified through COMPONENT_NAME
756#   - LLVM_LINK_COMPONENTS: a list of component this component depends on
757#   - COMPONENT_HAS_JIT: (only for group component) whether this target group
758#     supports JIT compilation
759# Additionnaly, the ADD_TO_COMPONENT <component> option make it possible to add this
760# component to the LLVM_LINK_COMPONENTS of <component>.
761function(add_llvm_component_library name)
762  cmake_parse_arguments(ARG
763    ""
764    "COMPONENT_NAME;ADD_TO_COMPONENT"
765    ""
766    ${ARGN})
767  add_llvm_library(${name} COMPONENT_LIB ${ARG_UNPARSED_ARGUMENTS})
768  string(REGEX REPLACE "^LLVM" "" component_name ${name})
769  set_property(TARGET ${name} PROPERTY LLVM_COMPONENT_NAME ${component_name})
770
771  if(ARG_COMPONENT_NAME)
772    set_property(GLOBAL PROPERTY LLVM_COMPONENT_NAME_${ARG_COMPONENT_NAME} ${component_name})
773  endif()
774
775  if(ARG_ADD_TO_COMPONENT)
776    set_property(TARGET ${ARG_ADD_TO_COMPONENT} APPEND PROPERTY LLVM_LINK_COMPONENTS ${component_name})
777  endif()
778
779endfunction()
780
781macro(add_llvm_library name)
782  cmake_parse_arguments(ARG
783    "SHARED;BUILDTREE_ONLY;MODULE;INSTALL_WITH_TOOLCHAIN"
784    ""
785    ""
786    ${ARGN})
787  if(ARG_MODULE)
788    llvm_add_library(${name} MODULE ${ARG_UNPARSED_ARGUMENTS})
789  elseif( BUILD_SHARED_LIBS OR ARG_SHARED )
790    llvm_add_library(${name} SHARED ${ARG_UNPARSED_ARGUMENTS})
791  else()
792    llvm_add_library(${name} ${ARG_UNPARSED_ARGUMENTS})
793  endif()
794
795  # Libraries that are meant to only be exposed via the build tree only are
796  # never installed and are only exported as a target in the special build tree
797  # config file.
798  if (NOT ARG_BUILDTREE_ONLY AND NOT ARG_MODULE)
799    set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} )
800    set(in_llvm_libs YES)
801  endif()
802
803  if (ARG_MODULE AND NOT TARGET ${name})
804    # Add empty "phony" target
805    add_custom_target(${name})
806  elseif( EXCLUDE_FROM_ALL )
807    set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
808  elseif(ARG_BUILDTREE_ONLY)
809    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS_BUILDTREE_ONLY ${name})
810  else()
811    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ARG_INSTALL_WITH_TOOLCHAIN)
812      if(in_llvm_libs)
813        set(umbrella UMBRELLA llvm-libraries)
814      else()
815        set(umbrella)
816      endif()
817
818      get_target_export_arg(${name} LLVM export_to_llvmexports ${umbrella})
819      install(TARGETS ${name}
820              ${export_to_llvmexports}
821              LIBRARY DESTINATION lib${LLVM_LIBDIR_SUFFIX} COMPONENT ${name}
822              ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX} COMPONENT ${name}
823              RUNTIME DESTINATION bin COMPONENT ${name})
824
825      if (NOT LLVM_ENABLE_IDE)
826        add_llvm_install_targets(install-${name}
827                                 DEPENDS ${name}
828                                 COMPONENT ${name})
829      endif()
830    endif()
831    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
832  endif()
833  if (ARG_MODULE)
834    set_target_properties(${name} PROPERTIES FOLDER "Loadable modules")
835  else()
836    set_target_properties(${name} PROPERTIES FOLDER "Libraries")
837  endif()
838endmacro(add_llvm_library name)
839
840macro(add_llvm_executable name)
841  cmake_parse_arguments(ARG
842    "DISABLE_LLVM_LINK_LLVM_DYLIB;IGNORE_EXTERNALIZE_DEBUGINFO;NO_INSTALL_RPATH;SUPPORT_PLUGINS"
843    "ENTITLEMENTS;BUNDLE_PATH"
844    "DEPENDS"
845    ${ARGN})
846
847  llvm_process_sources( ALL_FILES ${ARG_UNPARSED_ARGUMENTS} )
848
849  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
850
851  # Generate objlib
852  if(LLVM_ENABLE_OBJLIB)
853    # Generate an obj library for both targets.
854    set(obj_name "obj.${name}")
855    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
856      ${ALL_FILES}
857      )
858    llvm_update_compile_flags(${obj_name})
859    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
860
861    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
862  endif()
863
864  add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
865
866  if(XCODE)
867    # Note: the dummy.cpp source file provides no definitions. However,
868    # it forces Xcode to properly link the static library.
869    list(APPEND ALL_FILES "${LLVM_MAIN_SRC_DIR}/cmake/dummy.cpp")
870  endif()
871
872  if( EXCLUDE_FROM_ALL )
873    add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES})
874  else()
875    add_executable(${name} ${ALL_FILES})
876  endif()
877
878  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
879
880  if(NOT ARG_NO_INSTALL_RPATH)
881    llvm_setup_rpath(${name})
882  elseif(NOT "${LLVM_LOCAL_RPATH}" STREQUAL "")
883    # Enable BUILD_WITH_INSTALL_RPATH unless CMAKE_BUILD_RPATH is set.
884    if("${CMAKE_BUILD_RPATH}" STREQUAL "")
885      set_property(TARGET ${name} PROPERTY BUILD_WITH_INSTALL_RPATH ON)
886    endif()
887
888    set_property(TARGET ${name} PROPERTY INSTALL_RPATH "${LLVM_LOCAL_RPATH}")
889  endif()
890
891  if(DEFINED windows_resource_file)
892    set_windows_version_resource_properties(${name} ${windows_resource_file})
893  endif()
894
895  # $<TARGET_OBJECTS> doesn't require compile flags.
896  if(NOT LLVM_ENABLE_OBJLIB)
897    llvm_update_compile_flags(${name})
898  endif()
899
900  if (ARG_SUPPORT_PLUGINS AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
901    set(LLVM_NO_DEAD_STRIP On)
902  endif()
903
904  add_link_opts( ${name} )
905
906  # Do not add -Dname_EXPORTS to the command-line when building files in this
907  # target. Doing so is actively harmful for the modules build because it
908  # creates extra module variants, and not useful because we don't use these
909  # macros.
910  set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
911
912  if (LLVM_EXPORTED_SYMBOL_FILE)
913    add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
914  endif(LLVM_EXPORTED_SYMBOL_FILE)
915
916  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
917    set(USE_SHARED USE_SHARED)
918  endif()
919
920  set(EXCLUDE_FROM_ALL OFF)
921  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
922  llvm_config( ${name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )
923  if( LLVM_COMMON_DEPENDS )
924    add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
925  endif( LLVM_COMMON_DEPENDS )
926
927  if(NOT ARG_IGNORE_EXTERNALIZE_DEBUGINFO)
928    llvm_externalize_debuginfo(${name})
929  endif()
930  if (LLVM_PTHREAD_LIB)
931    # libpthreads overrides some standard library symbols, so main
932    # executable must be linked with it in order to provide consistent
933    # API for all shared libaries loaded by this executable.
934    target_link_libraries(${name} PRIVATE ${LLVM_PTHREAD_LIB})
935  endif()
936
937  llvm_codesign(${name} ENTITLEMENTS ${ARG_ENTITLEMENTS} BUNDLE_PATH ${ARG_BUNDLE_PATH})
938endmacro(add_llvm_executable name)
939
940# add_llvm_pass_plugin(name [NO_MODULE] ...)
941#   Add ${name} as an llvm plugin.
942#   If option LLVM_${name_upper}_LINK_INTO_TOOLS is set to ON, the plugin is registered statically.
943#   Otherwise a pluggable shared library is registered.
944#
945#   If NO_MODULE is specified, when option LLVM_${name_upper}_LINK_INTO_TOOLS is set to OFF,
946#   only an object library is built, and no module is built. This is specific to the Polly use case.
947#
948#   The SUBPROJECT argument contains the LLVM project the plugin belongs
949#   to. If set, the plugin will link statically by default it if the
950#   project was enabled.
951function(add_llvm_pass_plugin name)
952  cmake_parse_arguments(ARG
953    "NO_MODULE" "SUBPROJECT" ""
954    ${ARGN})
955
956  string(TOUPPER ${name} name_upper)
957
958  # Enable the plugin by default if it was explicitly enabled by the user.
959  # Note: If was set to "all", LLVM's CMakeLists.txt replaces it with a
960  # list of all projects, counting as explicitly enabled.
961  set(link_into_tools_default OFF)
962  if (ARG_SUBPROJECT AND LLVM_TOOL_${name_upper}_BUILD)
963    set(link_into_tools_default ON)
964  endif()
965  option(LLVM_${name_upper}_LINK_INTO_TOOLS "Statically link ${name} into tools (if available)" ${link_into_tools_default})
966
967  # If we statically link the plugin, don't use llvm dylib because we're going
968  # to be part of it.
969  if(LLVM_${name_upper}_LINK_INTO_TOOLS)
970      list(APPEND ARG_UNPARSED_ARGUMENTS DISABLE_LLVM_LINK_LLVM_DYLIB)
971  endif()
972
973  if(LLVM_${name_upper}_LINK_INTO_TOOLS)
974    list(REMOVE_ITEM ARG_UNPARSED_ARGUMENTS BUILDTREE_ONLY)
975    # process_llvm_pass_plugins takes care of the actual linking, just create an
976    # object library as of now
977    add_llvm_library(${name} OBJECT ${ARG_UNPARSED_ARGUMENTS})
978    target_compile_definitions(${name} PRIVATE LLVM_${name_upper}_LINK_INTO_TOOLS)
979    set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS LLVM_LINK_INTO_TOOLS)
980    if (TARGET intrinsics_gen)
981      add_dependencies(obj.${name} intrinsics_gen)
982    endif()
983    if (TARGET omp_gen)
984      add_dependencies(obj.${name} omp_gen)
985    endif()
986    if (TARGET acc_gen)
987      add_dependencies(obj.${name} acc_gen)
988    endif()
989    set_property(GLOBAL APPEND PROPERTY LLVM_STATIC_EXTENSIONS ${name})
990  elseif(NOT ARG_NO_MODULE)
991    add_llvm_library(${name} MODULE ${ARG_UNPARSED_ARGUMENTS})
992  else()
993    add_llvm_library(${name} OBJECT ${ARG_UNPARSED_ARGUMENTS})
994  endif()
995  message(STATUS "Registering ${name} as a pass plugin (static build: ${LLVM_${name_upper}_LINK_INTO_TOOLS})")
996
997endfunction(add_llvm_pass_plugin)
998
999# process_llvm_pass_plugins([GEN_CONFIG])
1000#
1001# Correctly set lib dependencies between plugins and tools, based on tools
1002# registered with the ENABLE_PLUGINS option.
1003#
1004# if GEN_CONFIG option is set, also generate X Macro file for extension
1005# handling. It provides a HANDLE_EXTENSION(extension_namespace, ExtensionProject)
1006# call for each extension allowing client code to define
1007# HANDLE_EXTENSION to have a specific code be run for each extension.
1008#
1009function(process_llvm_pass_plugins)
1010  cmake_parse_arguments(ARG
1011      "GEN_CONFIG" "" ""
1012    ${ARGN})
1013
1014  if(ARG_GEN_CONFIG)
1015      get_property(LLVM_STATIC_EXTENSIONS GLOBAL PROPERTY LLVM_STATIC_EXTENSIONS)
1016  else()
1017      include(LLVMConfigExtensions)
1018  endif()
1019
1020  # Add static plugins to the Extension component
1021  foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1022      set_property(TARGET LLVMExtensions APPEND PROPERTY LINK_LIBRARIES ${llvm_extension})
1023      set_property(TARGET LLVMExtensions APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${llvm_extension})
1024  endforeach()
1025
1026  # Eventually generate the extension headers, and store config to a cmake file
1027  # for usage in third-party configuration.
1028  if(ARG_GEN_CONFIG)
1029
1030      ## Part 1: Extension header to be included whenever we need extension
1031      #  processing.
1032      set(LLVM_INSTALL_PACKAGE_DIR lib${LLVM_LIBDIR_SUFFIX}/cmake/llvm)
1033      set(llvm_cmake_builddir "${LLVM_BINARY_DIR}/${LLVM_INSTALL_PACKAGE_DIR}")
1034      file(WRITE
1035          "${llvm_cmake_builddir}/LLVMConfigExtensions.cmake"
1036          "set(LLVM_STATIC_EXTENSIONS ${LLVM_STATIC_EXTENSIONS})")
1037      install(FILES
1038          ${llvm_cmake_builddir}/LLVMConfigExtensions.cmake
1039          DESTINATION ${LLVM_INSTALL_PACKAGE_DIR}
1040          COMPONENT cmake-exports)
1041
1042      set(ExtensionDef "${LLVM_BINARY_DIR}/include/llvm/Support/Extension.def")
1043      file(WRITE "${ExtensionDef}.tmp" "//extension handlers\n")
1044      foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1045          file(APPEND "${ExtensionDef}.tmp" "HANDLE_EXTENSION(${llvm_extension})\n")
1046      endforeach()
1047      file(APPEND "${ExtensionDef}.tmp" "#undef HANDLE_EXTENSION\n")
1048
1049      # only replace if there's an actual change
1050      execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
1051          "${ExtensionDef}.tmp"
1052          "${ExtensionDef}")
1053      file(REMOVE "${ExtensionDef}.tmp")
1054
1055      ## Part 2: Extension header that captures each extension dependency, to be
1056      #  used by llvm-config.
1057      set(ExtensionDeps "${LLVM_BINARY_DIR}/tools/llvm-config/ExtensionDependencies.inc")
1058
1059      # Max needed to correctly size the required library array.
1060      set(llvm_plugin_max_deps_length 0)
1061      foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1062        get_property(llvm_plugin_deps TARGET ${llvm_extension} PROPERTY LINK_LIBRARIES)
1063        list(LENGTH llvm_plugin_deps llvm_plugin_deps_length)
1064        if(llvm_plugin_deps_length GREATER llvm_plugin_max_deps_length)
1065            set(llvm_plugin_max_deps_length ${llvm_plugin_deps_length})
1066        endif()
1067      endforeach()
1068
1069      list(LENGTH LLVM_STATIC_EXTENSIONS llvm_static_extension_count)
1070      file(WRITE
1071          "${ExtensionDeps}.tmp"
1072          "#include <array>\n\
1073           struct ExtensionDescriptor {\n\
1074              const char* Name;\n\
1075              const char* RequiredLibraries[1 + 1 + ${llvm_plugin_max_deps_length}];\n\
1076           };\n\
1077           std::array<ExtensionDescriptor, ${llvm_static_extension_count}> AvailableExtensions{\n")
1078
1079      foreach(llvm_extension ${LLVM_STATIC_EXTENSIONS})
1080        get_property(llvm_plugin_deps TARGET ${llvm_extension} PROPERTY LINK_LIBRARIES)
1081
1082        file(APPEND "${ExtensionDeps}.tmp" "ExtensionDescriptor{\"${llvm_extension}\", {")
1083        foreach(llvm_plugin_dep ${llvm_plugin_deps})
1084            # Turn library dependency back to component name, if possible.
1085            # That way llvm-config can avoid redundant dependencies.
1086            STRING(REGEX REPLACE "^-l" ""  plugin_dep_name ${llvm_plugin_dep})
1087            STRING(REGEX MATCH "^LLVM" is_llvm_library ${plugin_dep_name})
1088            if(is_llvm_library)
1089                STRING(REGEX REPLACE "^LLVM" ""  plugin_dep_name ${plugin_dep_name})
1090                STRING(TOLOWER ${plugin_dep_name} plugin_dep_name)
1091            endif()
1092            file(APPEND "${ExtensionDeps}.tmp" "\"${plugin_dep_name}\", ")
1093        endforeach()
1094
1095        # Self + mandatory trailing null, because the number of RequiredLibraries differs between extensions.
1096        file(APPEND "${ExtensionDeps}.tmp" \"${llvm_extension}\", "nullptr}},\n")
1097      endforeach()
1098      file(APPEND "${ExtensionDeps}.tmp" "};\n")
1099
1100      # only replace if there's an actual change
1101      execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
1102          "${ExtensionDeps}.tmp"
1103          "${ExtensionDeps}")
1104      file(REMOVE "${ExtensionDeps}.tmp")
1105  endif()
1106endfunction()
1107
1108function(export_executable_symbols target)
1109  if (LLVM_EXPORTED_SYMBOL_FILE)
1110    # The symbol file should contain the symbols we want the executable to
1111    # export
1112    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
1113  elseif (LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1114    # Extract the symbols to export from the static libraries that the
1115    # executable links against.
1116    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
1117    set(exported_symbol_file ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${target}.symbols)
1118    # We need to consider not just the direct link dependencies, but also the
1119    # transitive link dependencies. Do this by starting with the set of direct
1120    # dependencies, then the dependencies of those dependencies, and so on.
1121    get_target_property(new_libs ${target} LINK_LIBRARIES)
1122    set(link_libs ${new_libs})
1123    while(NOT "${new_libs}" STREQUAL "")
1124      foreach(lib ${new_libs})
1125        if(TARGET ${lib})
1126          get_target_property(lib_type ${lib} TYPE)
1127          if("${lib_type}" STREQUAL "STATIC_LIBRARY")
1128            list(APPEND static_libs ${lib})
1129          else()
1130            list(APPEND other_libs ${lib})
1131          endif()
1132          get_target_property(transitive_libs ${lib} INTERFACE_LINK_LIBRARIES)
1133          foreach(transitive_lib ${transitive_libs})
1134            list(FIND link_libs ${transitive_lib} idx)
1135            if(TARGET ${transitive_lib} AND idx EQUAL -1)
1136              list(APPEND newer_libs ${transitive_lib})
1137              list(APPEND link_libs ${transitive_lib})
1138            endif()
1139          endforeach(transitive_lib)
1140        endif()
1141      endforeach(lib)
1142      set(new_libs ${newer_libs})
1143      set(newer_libs "")
1144    endwhile()
1145    list(REMOVE_DUPLICATES static_libs)
1146    if (MSVC)
1147      set(mangling microsoft)
1148    else()
1149      set(mangling itanium)
1150    endif()
1151    add_custom_command(OUTPUT ${exported_symbol_file}
1152                       COMMAND "${Python3_EXECUTABLE}" ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py --mangling=${mangling} ${static_libs} -o ${exported_symbol_file}
1153                       WORKING_DIRECTORY ${LLVM_LIBRARY_OUTPUT_INTDIR}
1154                       DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${static_libs}
1155                       VERBATIM
1156                       COMMENT "Generating export list for ${target}")
1157    add_llvm_symbol_exports( ${target} ${exported_symbol_file} )
1158    # If something links against this executable then we want a
1159    # transitive link against only the libraries whose symbols
1160    # we aren't exporting.
1161    set_target_properties(${target} PROPERTIES INTERFACE_LINK_LIBRARIES "${other_libs}")
1162    # The default import library suffix that cmake uses for cygwin/mingw is
1163    # ".dll.a", but for clang.exe that causes a collision with libclang.dll,
1164    # where the import libraries of both get named libclang.dll.a. Use a suffix
1165    # of ".exe.a" to avoid this.
1166    if(CYGWIN OR MINGW)
1167      set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".exe.a")
1168    endif()
1169  elseif(NOT (WIN32 OR CYGWIN))
1170    # On Windows auto-exporting everything doesn't work because of the limit on
1171    # the size of the exported symbol table, but on other platforms we can do
1172    # it without any trouble.
1173    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
1174    if (APPLE)
1175      set_property(TARGET ${target} APPEND_STRING PROPERTY
1176        LINK_FLAGS " -rdynamic")
1177    endif()
1178  endif()
1179endfunction()
1180
1181# Export symbols if LLVM plugins are enabled.
1182function(export_executable_symbols_for_plugins target)
1183  if(LLVM_ENABLE_PLUGINS OR LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1184    export_executable_symbols(${target})
1185  endif()
1186endfunction()
1187
1188if(NOT LLVM_TOOLCHAIN_TOOLS)
1189  set (LLVM_TOOLCHAIN_TOOLS
1190    llvm-ar
1191    llvm-cov
1192    llvm-cxxfilt
1193    llvm-ranlib
1194    llvm-lib
1195    llvm-nm
1196    llvm-objcopy
1197    llvm-objdump
1198    llvm-rc
1199    llvm-size
1200    llvm-strings
1201    llvm-strip
1202    llvm-profdata
1203    llvm-symbolizer
1204    # symlink version of some of above tools that are enabled by
1205    # LLVM_INSTALL_BINUTILS_SYMLINKS.
1206    addr2line
1207    ar
1208    c++filt
1209    ranlib
1210    nm
1211    objcopy
1212    objdump
1213    size
1214    strings
1215    strip
1216    )
1217endif()
1218
1219macro(add_llvm_tool name)
1220  if( NOT LLVM_BUILD_TOOLS )
1221    set(EXCLUDE_FROM_ALL ON)
1222  endif()
1223  add_llvm_executable(${name} ${ARGN})
1224
1225  if ( ${name} IN_LIST LLVM_TOOLCHAIN_TOOLS OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
1226    if( LLVM_BUILD_TOOLS )
1227      get_target_export_arg(${name} LLVM export_to_llvmexports)
1228      install(TARGETS ${name}
1229              ${export_to_llvmexports}
1230              RUNTIME DESTINATION ${LLVM_TOOLS_INSTALL_DIR}
1231              COMPONENT ${name})
1232
1233      if (NOT LLVM_ENABLE_IDE)
1234        add_llvm_install_targets(install-${name}
1235                                 DEPENDS ${name}
1236                                 COMPONENT ${name})
1237      endif()
1238    endif()
1239  endif()
1240  if( LLVM_BUILD_TOOLS )
1241    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
1242  endif()
1243  set_target_properties(${name} PROPERTIES FOLDER "Tools")
1244endmacro(add_llvm_tool name)
1245
1246
1247macro(add_llvm_example name)
1248  if( NOT LLVM_BUILD_EXAMPLES )
1249    set(EXCLUDE_FROM_ALL ON)
1250  endif()
1251  add_llvm_executable(${name} ${ARGN})
1252  if( LLVM_BUILD_EXAMPLES )
1253    install(TARGETS ${name} RUNTIME DESTINATION examples)
1254  endif()
1255  set_target_properties(${name} PROPERTIES FOLDER "Examples")
1256endmacro(add_llvm_example name)
1257
1258macro(add_llvm_example_library name)
1259  if( NOT LLVM_BUILD_EXAMPLES )
1260    set(EXCLUDE_FROM_ALL ON)
1261    add_llvm_library(${name} BUILDTREE_ONLY ${ARGN})
1262  else()
1263    add_llvm_library(${name} ${ARGN})
1264  endif()
1265
1266  set_target_properties(${name} PROPERTIES FOLDER "Examples")
1267endmacro(add_llvm_example_library name)
1268
1269# This is a macro that is used to create targets for executables that are needed
1270# for development, but that are not intended to be installed by default.
1271macro(add_llvm_utility name)
1272  if ( NOT LLVM_BUILD_UTILS )
1273    set(EXCLUDE_FROM_ALL ON)
1274  endif()
1275
1276  add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
1277  set_target_properties(${name} PROPERTIES FOLDER "Utils")
1278  if ( ${name} IN_LIST LLVM_TOOLCHAIN_UTILITIES OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
1279    if (LLVM_INSTALL_UTILS AND LLVM_BUILD_UTILS)
1280      get_target_export_arg(${name} LLVM export_to_llvmexports)
1281      install(TARGETS ${name}
1282              ${export_to_llvmexports}
1283              RUNTIME DESTINATION ${LLVM_UTILS_INSTALL_DIR}
1284              COMPONENT ${name})
1285
1286      if (NOT LLVM_ENABLE_IDE)
1287        add_llvm_install_targets(install-${name}
1288                                 DEPENDS ${name}
1289                                 COMPONENT ${name})
1290      endif()
1291      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
1292    elseif(LLVM_BUILD_UTILS)
1293      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS_BUILDTREE_ONLY ${name})
1294    endif()
1295  endif()
1296endmacro(add_llvm_utility name)
1297
1298macro(add_llvm_fuzzer name)
1299  cmake_parse_arguments(ARG "" "DUMMY_MAIN" "" ${ARGN})
1300  if( LLVM_LIB_FUZZING_ENGINE )
1301    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
1302    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
1303    target_link_libraries(${name} PRIVATE ${LLVM_LIB_FUZZING_ENGINE})
1304    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
1305  elseif( LLVM_USE_SANITIZE_COVERAGE )
1306    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=fuzzer")
1307    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
1308    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
1309    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
1310  elseif( ARG_DUMMY_MAIN )
1311    add_llvm_executable(${name} ${ARG_DUMMY_MAIN} ${ARG_UNPARSED_ARGUMENTS})
1312    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
1313  endif()
1314endmacro()
1315
1316macro(add_llvm_target target_name)
1317  include_directories(BEFORE
1318    ${CMAKE_CURRENT_BINARY_DIR}
1319    ${CMAKE_CURRENT_SOURCE_DIR})
1320  add_llvm_component_library(LLVM${target_name} ${ARGN})
1321  set( CURRENT_LLVM_TARGET LLVM${target_name} )
1322endmacro(add_llvm_target)
1323
1324function(canonicalize_tool_name name output)
1325  string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" nameStrip ${name})
1326  string(REPLACE "-" "_" nameUNDERSCORE ${nameStrip})
1327  string(TOUPPER ${nameUNDERSCORE} nameUPPER)
1328  set(${output} "${nameUPPER}" PARENT_SCOPE)
1329endfunction(canonicalize_tool_name)
1330
1331# Custom add_subdirectory wrapper
1332# Takes in a project name (i.e. LLVM), the subdirectory name, and an optional
1333# path if it differs from the name.
1334function(add_llvm_subdirectory project type name)
1335  set(add_llvm_external_dir "${ARGN}")
1336  if("${add_llvm_external_dir}" STREQUAL "")
1337    set(add_llvm_external_dir ${name})
1338  endif()
1339  canonicalize_tool_name(${name} nameUPPER)
1340  set(canonical_full_name ${project}_${type}_${nameUPPER})
1341  get_property(already_processed GLOBAL PROPERTY ${canonical_full_name}_PROCESSED)
1342  if(already_processed)
1343    return()
1344  endif()
1345  set_property(GLOBAL PROPERTY ${canonical_full_name}_PROCESSED YES)
1346
1347  if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}/CMakeLists.txt)
1348    # Treat it as in-tree subproject.
1349    option(${canonical_full_name}_BUILD
1350           "Whether to build ${name} as part of ${project}" On)
1351    mark_as_advanced(${project}_${type}_${name}_BUILD)
1352    if(${canonical_full_name}_BUILD)
1353      add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir} ${add_llvm_external_dir})
1354    endif()
1355  else()
1356    set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR
1357      "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}"
1358      CACHE PATH "Path to ${name} source directory")
1359    set(${canonical_full_name}_BUILD_DEFAULT ON)
1360    if(NOT LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR OR NOT EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
1361      set(${canonical_full_name}_BUILD_DEFAULT OFF)
1362    endif()
1363    if("${LLVM_EXTERNAL_${nameUPPER}_BUILD}" STREQUAL "OFF")
1364      set(${canonical_full_name}_BUILD_DEFAULT OFF)
1365    endif()
1366    option(${canonical_full_name}_BUILD
1367      "Whether to build ${name} as part of LLVM"
1368      ${${canonical_full_name}_BUILD_DEFAULT})
1369    if (${canonical_full_name}_BUILD)
1370      if(EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
1371        add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${add_llvm_external_dir})
1372      elseif(NOT "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}" STREQUAL "")
1373        message(WARNING "Nonexistent directory for ${name}: ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}")
1374      endif()
1375    endif()
1376  endif()
1377endfunction()
1378
1379# Add external project that may want to be built as part of llvm such as Clang,
1380# lld, and Polly. This adds two options. One for the source directory of the
1381# project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to
1382# enable or disable building it with everything else.
1383# Additional parameter can be specified as the name of directory.
1384macro(add_llvm_external_project name)
1385  add_llvm_subdirectory(LLVM TOOL ${name} ${ARGN})
1386endmacro()
1387
1388macro(add_llvm_tool_subdirectory name)
1389  add_llvm_external_project(${name})
1390endmacro(add_llvm_tool_subdirectory)
1391
1392function(get_project_name_from_src_var var output)
1393  string(REGEX MATCH "LLVM_EXTERNAL_(.*)_SOURCE_DIR"
1394         MACHED_TOOL "${var}")
1395  if(MACHED_TOOL)
1396    set(${output} ${CMAKE_MATCH_1} PARENT_SCOPE)
1397  else()
1398    set(${output} PARENT_SCOPE)
1399  endif()
1400endfunction()
1401
1402function(create_subdirectory_options project type)
1403  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1404  foreach(dir ${sub-dirs})
1405    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1406      canonicalize_tool_name(${dir} name)
1407      option(${project}_${type}_${name}_BUILD
1408           "Whether to build ${name} as part of ${project}" On)
1409      mark_as_advanced(${project}_${type}_${name}_BUILD)
1410    endif()
1411  endforeach()
1412endfunction(create_subdirectory_options)
1413
1414function(create_llvm_tool_options)
1415  create_subdirectory_options(LLVM TOOL)
1416endfunction(create_llvm_tool_options)
1417
1418function(llvm_add_implicit_projects project)
1419  set(list_of_implicit_subdirs "")
1420  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1421  foreach(dir ${sub-dirs})
1422    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1423      canonicalize_tool_name(${dir} name)
1424      if (${project}_TOOL_${name}_BUILD)
1425        get_filename_component(fn "${dir}" NAME)
1426        list(APPEND list_of_implicit_subdirs "${fn}")
1427      endif()
1428    endif()
1429  endforeach()
1430
1431  foreach(external_proj ${list_of_implicit_subdirs})
1432    add_llvm_subdirectory(${project} TOOL "${external_proj}" ${ARGN})
1433  endforeach()
1434endfunction(llvm_add_implicit_projects)
1435
1436function(add_llvm_implicit_projects)
1437  llvm_add_implicit_projects(LLVM)
1438endfunction(add_llvm_implicit_projects)
1439
1440# Generic support for adding a unittest.
1441function(add_unittest test_suite test_name)
1442  if( NOT LLVM_BUILD_TESTS )
1443    set(EXCLUDE_FROM_ALL ON)
1444  endif()
1445
1446  if (SUPPORTS_VARIADIC_MACROS_FLAG)
1447    list(APPEND LLVM_COMPILE_FLAGS "-Wno-variadic-macros")
1448  endif ()
1449  # Some parts of gtest rely on this GNU extension, don't warn on it.
1450  if(SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG)
1451    list(APPEND LLVM_COMPILE_FLAGS "-Wno-gnu-zero-variadic-macro-arguments")
1452  endif()
1453
1454  set(LLVM_REQUIRES_RTTI OFF)
1455
1456  list(APPEND LLVM_LINK_COMPONENTS Support) # gtest needs it for raw_ostream
1457  add_llvm_executable(${test_name} IGNORE_EXTERNALIZE_DEBUGINFO NO_INSTALL_RPATH ${ARGN})
1458
1459  # The runtime benefits of LTO don't outweight the compile time costs for tests.
1460  if(LLVM_ENABLE_LTO)
1461    if((UNIX OR MINGW) AND LLVM_USE_LINKER STREQUAL "lld")
1462      set_property(TARGET ${test_name} APPEND_STRING PROPERTY
1463                    LINK_FLAGS " -Wl,--lto-O0")
1464    elseif(LINKER_IS_LLD_LINK)
1465      set_property(TARGET ${test_name} APPEND_STRING PROPERTY
1466                    LINK_FLAGS " /opt:lldlto=0")
1467    endif()
1468  endif()
1469
1470  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
1471  set_output_directory(${test_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
1472  # libpthreads overrides some standard library symbols, so main
1473  # executable must be linked with it in order to provide consistent
1474  # API for all shared libaries loaded by this executable.
1475  target_link_libraries(${test_name} PRIVATE gtest_main gtest ${LLVM_PTHREAD_LIB})
1476
1477  add_dependencies(${test_suite} ${test_name})
1478  get_target_property(test_suite_folder ${test_suite} FOLDER)
1479  if (test_suite_folder)
1480    set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}")
1481  endif ()
1482endfunction()
1483
1484# Use for test binaries that call llvm::getInputFileDirectory(). Use of this
1485# is discouraged.
1486function(add_unittest_with_input_files test_suite test_name)
1487  set(LLVM_UNITTEST_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
1488  configure_file(
1489    ${LLVM_MAIN_SRC_DIR}/unittests/unittest.cfg.in
1490    ${CMAKE_CURRENT_BINARY_DIR}/llvm.srcdir.txt)
1491
1492  add_unittest(${test_suite} ${test_name} ${ARGN})
1493endfunction()
1494
1495# Generic support for adding a benchmark.
1496function(add_benchmark benchmark_name)
1497  if( NOT LLVM_BUILD_BENCHMARKS )
1498    set(EXCLUDE_FROM_ALL ON)
1499  endif()
1500
1501  add_llvm_executable(${benchmark_name} IGNORE_EXTERNALIZE_DEBUGINFO NO_INSTALL_RPATH ${ARGN})
1502  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
1503  set_output_directory(${benchmark_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
1504  set_property(TARGET ${benchmark_name} PROPERTY FOLDER "Utils")
1505  target_link_libraries(${benchmark_name} PRIVATE benchmark)
1506endfunction()
1507
1508# This function canonicalize the CMake variables passed by names
1509# from CMake boolean to 0/1 suitable for passing into Python or C++,
1510# in place.
1511function(llvm_canonicalize_cmake_booleans)
1512  foreach(var ${ARGN})
1513    if(${var})
1514      set(${var} 1 PARENT_SCOPE)
1515    else()
1516      set(${var} 0 PARENT_SCOPE)
1517    endif()
1518  endforeach()
1519endfunction(llvm_canonicalize_cmake_booleans)
1520
1521macro(set_llvm_build_mode)
1522  # Configuration-time: See Unit/lit.site.cfg.in
1523  if (CMAKE_CFG_INTDIR STREQUAL ".")
1524    set(LLVM_BUILD_MODE ".")
1525  else ()
1526    set(LLVM_BUILD_MODE "%(build_mode)s")
1527  endif ()
1528endmacro()
1529
1530# Takes a list of path names in pathlist and a base directory, and returns
1531# a list of paths relative to the base directory in out_pathlist.
1532# Paths that are on a different drive than the basedir (on Windows) or that
1533# contain symlinks are returned absolute.
1534# Use with LLVM_LIT_PATH_FUNCTION below.
1535function(make_paths_relative out_pathlist basedir pathlist)
1536  # Passing ARG_PATH_VALUES as-is to execute_process() makes cmake strip
1537  # empty list entries. So escape the ;s in the list and do the splitting
1538  # ourselves. cmake has no relpath function, so use Python for that.
1539  string(REPLACE ";" "\\;" pathlist_escaped "${pathlist}")
1540  execute_process(COMMAND "${Python3_EXECUTABLE}" "-c" "\n
1541import os, sys\n
1542base = sys.argv[1]
1543def haslink(p):\n
1544    if not p or p == os.path.dirname(p): return False\n
1545    return os.path.islink(p) or haslink(os.path.dirname(p))\n
1546def relpath(p):\n
1547    if not p: return ''\n
1548    if os.path.splitdrive(p)[0] != os.path.splitdrive(base)[0]: return p\n
1549    if haslink(p) or haslink(base): return p\n
1550    return os.path.relpath(p, base)\n
1551if len(sys.argv) < 3: sys.exit(0)\n
1552sys.stdout.write(';'.join(relpath(p) for p in sys.argv[2].split(';')))"
1553    ${basedir}
1554    ${pathlist_escaped}
1555    OUTPUT_VARIABLE pathlist_relative
1556    ERROR_VARIABLE error
1557    RESULT_VARIABLE result)
1558  if (NOT result EQUAL 0)
1559    message(FATAL_ERROR "make_paths_relative() failed due to error '${result}', with stderr\n${error}")
1560  endif()
1561  set(${out_pathlist} "${pathlist_relative}" PARENT_SCOPE)
1562endfunction()
1563
1564# Converts a file that's relative to the current python file to an absolute
1565# path. Since this uses __file__, it has to be emitted into python files that
1566# use it and can't be in a lit module. Use with make_paths_relative().
1567string(CONCAT LLVM_LIT_PATH_FUNCTION
1568  "# Allow generated file to be relocatable.\n"
1569  "def path(p):\n"
1570  "    if not p: return ''\n"
1571  "    return os.path.join(os.path.dirname(os.path.abspath(__file__)), p)\n"
1572  )
1573
1574# This function provides an automatic way to 'configure'-like generate a file
1575# based on a set of common and custom variables, specifically targeting the
1576# variables needed for the 'lit.site.cfg' files. This function bundles the
1577# common variables that any Lit instance is likely to need, and custom
1578# variables can be passed in.
1579# The keyword PATHS is followed by a list of cmake variable names that are
1580# mentioned as `path("@varname@")` in the lit.cfg.py.in file. Variables in that
1581# list are treated as paths that are relative to the directory the generated
1582# lit.cfg.py file is in, and the `path()` function converts the relative
1583# path back to absolute form. This makes it possible to move a build directory
1584# containing lit.cfg.py files from one machine to another.
1585function(configure_lit_site_cfg site_in site_out)
1586  cmake_parse_arguments(ARG "" "" "MAIN_CONFIG;OUTPUT_MAPPING;PATHS" ${ARGN})
1587
1588  if ("${ARG_MAIN_CONFIG}" STREQUAL "")
1589    get_filename_component(INPUT_DIR ${site_in} DIRECTORY)
1590    set(ARG_MAIN_CONFIG "${INPUT_DIR}/lit.cfg")
1591  endif()
1592  if ("${ARG_OUTPUT_MAPPING}" STREQUAL "")
1593    set(ARG_OUTPUT_MAPPING "${site_out}")
1594  endif()
1595
1596  foreach(c ${LLVM_TARGETS_TO_BUILD})
1597    set(TARGETS_BUILT "${TARGETS_BUILT} ${c}")
1598  endforeach(c)
1599  set(TARGETS_TO_BUILD ${TARGETS_BUILT})
1600
1601  set(SHLIBEXT "${LTDL_SHLIB_EXT}")
1602
1603  set_llvm_build_mode()
1604
1605  # The below might not be the build tree but provided binary tree.
1606  set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
1607  set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
1608  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" LLVM_TOOLS_DIR "${LLVM_TOOLS_BINARY_DIR}")
1609  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" LLVM_LIBS_DIR  "${LLVM_LIBRARY_DIR}")
1610
1611  # SHLIBDIR points the build tree.
1612  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" SHLIBDIR "${LLVM_SHLIB_OUTPUT_INTDIR}")
1613
1614  # FIXME: "ENABLE_SHARED" doesn't make sense, since it is used just for
1615  # plugins. We may rename it.
1616  if(LLVM_ENABLE_PLUGINS)
1617    set(ENABLE_SHARED "1")
1618  else()
1619    set(ENABLE_SHARED "0")
1620  endif()
1621
1622  if(LLVM_ENABLE_ASSERTIONS AND NOT MSVC_IDE)
1623    set(ENABLE_ASSERTIONS "1")
1624  else()
1625    set(ENABLE_ASSERTIONS "0")
1626  endif()
1627
1628  set(HOST_OS ${CMAKE_SYSTEM_NAME})
1629  set(HOST_ARCH ${CMAKE_SYSTEM_PROCESSOR})
1630
1631  set(HOST_CC "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1632  set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1633  set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}")
1634
1635  string(CONCAT LIT_SITE_CFG_IN_HEADER
1636    "# Autogenerated from ${site_in}\n# Do not edit!\n\n"
1637    "${LLVM_LIT_PATH_FUNCTION}"
1638    )
1639
1640  # Override config_target_triple (and the env)
1641  if(LLVM_TARGET_TRIPLE_ENV)
1642    # This is expanded into the heading.
1643    string(CONCAT LIT_SITE_CFG_IN_HEADER "${LIT_SITE_CFG_IN_HEADER}"
1644      "import os\n"
1645      "target_env = \"${LLVM_TARGET_TRIPLE_ENV}\"\n"
1646      "config.target_triple = config.environment[target_env] = os.environ.get(target_env, \"${TARGET_TRIPLE}\")\n"
1647      )
1648
1649    # This is expanded to; config.target_triple = ""+config.target_triple+""
1650    set(TARGET_TRIPLE "\"+config.target_triple+\"")
1651  endif()
1652
1653  if (ARG_PATHS)
1654    # Walk ARG_PATHS and collect the current value of the variables in there.
1655    # list(APPEND) ignores empty elements exactly if the list is empty,
1656    # so start the list with a dummy element and drop it, to make sure that
1657    # even empty values make it into the values list.
1658    set(ARG_PATH_VALUES "dummy")
1659    foreach(path ${ARG_PATHS})
1660      list(APPEND ARG_PATH_VALUES "${${path}}")
1661    endforeach()
1662    list(REMOVE_AT ARG_PATH_VALUES 0)
1663
1664    get_filename_component(OUTPUT_DIR ${site_out} DIRECTORY)
1665    make_paths_relative(
1666        ARG_PATH_VALUES_RELATIVE "${OUTPUT_DIR}" "${ARG_PATH_VALUES}")
1667
1668    list(LENGTH ARG_PATHS len_paths)
1669    list(LENGTH ARG_PATH_VALUES len_path_values)
1670    list(LENGTH ARG_PATH_VALUES_RELATIVE len_path_value_rels)
1671    if ((NOT ${len_paths} EQUAL ${len_path_values}) OR
1672        (NOT ${len_paths} EQUAL ${len_path_value_rels}))
1673      message(SEND_ERROR "PATHS lengths got confused")
1674    endif()
1675
1676    # Transform variables mentioned in ARG_PATHS to relative paths for
1677    # the configure_file() call. Variables are copied to subscopeds by cmake,
1678    # so this only modifies the local copy of the variables.
1679    math(EXPR arg_path_limit "${len_paths} - 1")
1680    foreach(i RANGE ${arg_path_limit})
1681      list(GET ARG_PATHS ${i} val1)
1682      list(GET ARG_PATH_VALUES_RELATIVE ${i} val2)
1683      set(${val1} ${val2})
1684    endforeach()
1685  endif()
1686
1687  configure_file(${site_in} ${site_out} @ONLY)
1688
1689  if (EXISTS "${ARG_MAIN_CONFIG}")
1690    # Remember main config / generated site config for llvm-lit.in.
1691    get_property(LLVM_LIT_CONFIG_FILES GLOBAL PROPERTY LLVM_LIT_CONFIG_FILES)
1692    list(APPEND LLVM_LIT_CONFIG_FILES "${ARG_MAIN_CONFIG}" "${site_out}")
1693    set_property(GLOBAL PROPERTY LLVM_LIT_CONFIG_FILES ${LLVM_LIT_CONFIG_FILES})
1694  endif()
1695endfunction()
1696
1697function(dump_all_cmake_variables)
1698  get_cmake_property(_variableNames VARIABLES)
1699  foreach (_variableName ${_variableNames})
1700    message(STATUS "${_variableName}=${${_variableName}}")
1701  endforeach()
1702endfunction()
1703
1704function(get_llvm_lit_path base_dir file_name)
1705  cmake_parse_arguments(ARG "ALLOW_EXTERNAL" "" "" ${ARGN})
1706
1707  if (ARG_ALLOW_EXTERNAL)
1708    set (LLVM_EXTERNAL_LIT "" CACHE STRING "Command used to spawn lit")
1709    if ("${LLVM_EXTERNAL_LIT}" STREQUAL "")
1710      set(LLVM_EXTERNAL_LIT "${LLVM_DEFAULT_EXTERNAL_LIT}")
1711    endif()
1712
1713    if (NOT "${LLVM_EXTERNAL_LIT}" STREQUAL "")
1714      if (EXISTS ${LLVM_EXTERNAL_LIT})
1715        get_filename_component(LIT_FILE_NAME ${LLVM_EXTERNAL_LIT} NAME)
1716        get_filename_component(LIT_BASE_DIR ${LLVM_EXTERNAL_LIT} DIRECTORY)
1717        set(${file_name} ${LIT_FILE_NAME} PARENT_SCOPE)
1718        set(${base_dir} ${LIT_BASE_DIR} PARENT_SCOPE)
1719        return()
1720      elseif (NOT DEFINED CACHE{LLVM_EXTERNAL_LIT_MISSING_WARNED_ONCE})
1721        message(WARNING "LLVM_EXTERNAL_LIT set to ${LLVM_EXTERNAL_LIT}, but the path does not exist.")
1722        set(LLVM_EXTERNAL_LIT_MISSING_WARNED_ONCE YES CACHE INTERNAL "")
1723      endif()
1724    endif()
1725  endif()
1726
1727  set(lit_file_name "llvm-lit")
1728  if (CMAKE_HOST_WIN32 AND NOT CYGWIN)
1729    # llvm-lit needs suffix.py for multiprocess to find a main module.
1730    set(lit_file_name "${lit_file_name}.py")
1731  endif ()
1732  set(${file_name} ${lit_file_name} PARENT_SCOPE)
1733
1734  get_property(LLVM_LIT_BASE_DIR GLOBAL PROPERTY LLVM_LIT_BASE_DIR)
1735  if (NOT "${LLVM_LIT_BASE_DIR}" STREQUAL "")
1736    set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1737  endif()
1738
1739  # Allow individual projects to provide an override
1740  if (NOT "${LLVM_LIT_OUTPUT_DIR}" STREQUAL "")
1741    set(LLVM_LIT_BASE_DIR ${LLVM_LIT_OUTPUT_DIR})
1742  elseif(NOT "${LLVM_RUNTIME_OUTPUT_INTDIR}" STREQUAL "")
1743    set(LLVM_LIT_BASE_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
1744  else()
1745    set(LLVM_LIT_BASE_DIR "")
1746  endif()
1747
1748  # Cache this so we don't have to do it again and have subsequent calls
1749  # potentially disagree on the value.
1750  set_property(GLOBAL PROPERTY LLVM_LIT_BASE_DIR ${LLVM_LIT_BASE_DIR})
1751  set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1752endfunction()
1753
1754# A raw function to create a lit target. This is used to implement the testuite
1755# management functions.
1756function(add_lit_target target comment)
1757  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1758  set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}")
1759  separate_arguments(LIT_ARGS)
1760  if (NOT CMAKE_CFG_INTDIR STREQUAL ".")
1761    list(APPEND LIT_ARGS --param build_mode=${CMAKE_CFG_INTDIR})
1762  endif ()
1763
1764  # Get the path to the lit to *run* tests with.  This can be overriden by
1765  # the user by specifying -DLLVM_EXTERNAL_LIT=<path-to-lit.py>
1766  get_llvm_lit_path(
1767    lit_base_dir
1768    lit_file_name
1769    ALLOW_EXTERNAL
1770    )
1771
1772  set(LIT_COMMAND "${Python3_EXECUTABLE};${lit_base_dir}/${lit_file_name}")
1773  list(APPEND LIT_COMMAND ${LIT_ARGS})
1774  foreach(param ${ARG_PARAMS})
1775    list(APPEND LIT_COMMAND --param ${param})
1776  endforeach()
1777  if (ARG_UNPARSED_ARGUMENTS)
1778    add_custom_target(${target}
1779      COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS}
1780      COMMENT "${comment}"
1781      USES_TERMINAL
1782      )
1783  else()
1784    add_custom_target(${target}
1785      COMMAND ${CMAKE_COMMAND} -E echo "${target} does nothing, no tools built.")
1786    message(STATUS "${target} does nothing.")
1787  endif()
1788
1789  if (ARG_DEPENDS)
1790    add_dependencies(${target} ${ARG_DEPENDS})
1791  endif()
1792
1793  # Tests should be excluded from "Build Solution".
1794  set_target_properties(${target} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON)
1795endfunction()
1796
1797# A function to add a set of lit test suites to be driven through 'check-*' targets.
1798function(add_lit_testsuite target comment)
1799  cmake_parse_arguments(ARG "EXCLUDE_FROM_CHECK_ALL" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1800
1801  # EXCLUDE_FROM_ALL excludes the test ${target} out of check-all.
1802  if(NOT ARG_EXCLUDE_FROM_CHECK_ALL)
1803    # Register the testsuites, params and depends for the global check rule.
1804    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${ARG_UNPARSED_ARGUMENTS})
1805    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${ARG_PARAMS})
1806    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_DEPENDS ${ARG_DEPENDS})
1807    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${ARG_ARGS})
1808  endif()
1809
1810  # Produce a specific suffixed check rule.
1811  add_lit_target(${target} ${comment}
1812    ${ARG_UNPARSED_ARGUMENTS}
1813    PARAMS ${ARG_PARAMS}
1814    DEPENDS ${ARG_DEPENDS}
1815    ARGS ${ARG_ARGS}
1816    )
1817endfunction()
1818
1819function(add_lit_testsuites project directory)
1820  if (NOT LLVM_ENABLE_IDE)
1821    cmake_parse_arguments(ARG "EXCLUDE_FROM_CHECK_ALL" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1822
1823    # Search recursively for test directories by assuming anything not
1824    # in a directory called Inputs contains tests.
1825    file(GLOB_RECURSE to_process LIST_DIRECTORIES true ${directory}/*)
1826    foreach(lit_suite ${to_process})
1827      if(NOT IS_DIRECTORY ${lit_suite})
1828        continue()
1829      endif()
1830      string(FIND ${lit_suite} Inputs is_inputs)
1831      string(FIND ${lit_suite} Output is_output)
1832      if (NOT (is_inputs EQUAL -1 AND is_output EQUAL -1))
1833        continue()
1834      endif()
1835
1836      # Create a check- target for the directory.
1837      string(REPLACE ${directory} "" name_slash ${lit_suite})
1838      if (name_slash)
1839        string(REPLACE "/" "-" name_slash ${name_slash})
1840        string(REPLACE "\\" "-" name_dashes ${name_slash})
1841        string(TOLOWER "${project}${name_dashes}" name_var)
1842        add_lit_target("check-${name_var}" "Running lit suite ${lit_suite}"
1843          ${lit_suite}
1844          ${EXCLUDE_FROM_CHECK_ALL}
1845          PARAMS ${ARG_PARAMS}
1846          DEPENDS ${ARG_DEPENDS}
1847          ARGS ${ARG_ARGS}
1848        )
1849      endif()
1850    endforeach()
1851  endif()
1852endfunction()
1853
1854function(llvm_install_library_symlink name dest type)
1855  cmake_parse_arguments(ARG "" "COMPONENT" "" ${ARGN})
1856  foreach(path ${CMAKE_MODULE_PATH})
1857    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1858      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1859      break()
1860    endif()
1861  endforeach()
1862
1863  set(component ${ARG_COMPONENT})
1864  if(NOT component)
1865    set(component ${name})
1866  endif()
1867
1868  set(full_name ${CMAKE_${type}_LIBRARY_PREFIX}${name}${CMAKE_${type}_LIBRARY_SUFFIX})
1869  set(full_dest ${CMAKE_${type}_LIBRARY_PREFIX}${dest}${CMAKE_${type}_LIBRARY_SUFFIX})
1870
1871  set(output_dir lib${LLVM_LIBDIR_SUFFIX})
1872  if(WIN32 AND "${type}" STREQUAL "SHARED")
1873    set(output_dir bin)
1874  endif()
1875
1876  install(SCRIPT ${INSTALL_SYMLINK}
1877          CODE "install_symlink(${full_name} ${full_dest} ${output_dir})"
1878          COMPONENT ${component})
1879
1880endfunction()
1881
1882function(llvm_install_symlink name dest)
1883  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1884  foreach(path ${CMAKE_MODULE_PATH})
1885    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1886      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1887      break()
1888    endif()
1889  endforeach()
1890
1891  if(ARG_COMPONENT)
1892    set(component ${ARG_COMPONENT})
1893  else()
1894    if(ARG_ALWAYS_GENERATE)
1895      set(component ${dest})
1896    else()
1897      set(component ${name})
1898    endif()
1899  endif()
1900
1901  set(full_name ${name}${CMAKE_EXECUTABLE_SUFFIX})
1902  set(full_dest ${dest}${CMAKE_EXECUTABLE_SUFFIX})
1903
1904  install(SCRIPT ${INSTALL_SYMLINK}
1905          CODE "install_symlink(${full_name} ${full_dest} ${LLVM_TOOLS_INSTALL_DIR})"
1906          COMPONENT ${component})
1907
1908  if (NOT LLVM_ENABLE_IDE AND NOT ARG_ALWAYS_GENERATE)
1909    add_llvm_install_targets(install-${name}
1910                             DEPENDS ${name} ${dest}
1911                             COMPONENT ${name}
1912                             SYMLINK ${dest})
1913  endif()
1914endfunction()
1915
1916function(add_llvm_tool_symlink link_name target)
1917  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "OUTPUT_DIR" "" ${ARGN})
1918  set(dest_binary "$<TARGET_FILE:${target}>")
1919
1920  # This got a bit gross... For multi-configuration generators the target
1921  # properties return the resolved value of the string, not the build system
1922  # expression. To reconstruct the platform-agnostic path we have to do some
1923  # magic. First we grab one of the types, and a type-specific path. Then from
1924  # the type-specific path we find the last occurrence of the type in the path,
1925  # and replace it with CMAKE_CFG_INTDIR. This allows the build step to be type
1926  # agnostic again.
1927  if(NOT ARG_OUTPUT_DIR)
1928    # If you're not overriding the OUTPUT_DIR, we can make the link relative in
1929    # the same directory.
1930    if(CMAKE_HOST_UNIX)
1931      set(dest_binary "$<TARGET_FILE_NAME:${target}>")
1932    endif()
1933    if(CMAKE_CONFIGURATION_TYPES)
1934      list(GET CMAKE_CONFIGURATION_TYPES 0 first_type)
1935      string(TOUPPER ${first_type} first_type_upper)
1936      set(first_type_suffix _${first_type_upper})
1937    endif()
1938    get_target_property(target_type ${target} TYPE)
1939    if(${target_type} STREQUAL "STATIC_LIBRARY")
1940      get_target_property(ARG_OUTPUT_DIR ${target} ARCHIVE_OUTPUT_DIRECTORY${first_type_suffix})
1941    elseif(UNIX AND ${target_type} STREQUAL "SHARED_LIBRARY")
1942      get_target_property(ARG_OUTPUT_DIR ${target} LIBRARY_OUTPUT_DIRECTORY${first_type_suffix})
1943    else()
1944      get_target_property(ARG_OUTPUT_DIR ${target} RUNTIME_OUTPUT_DIRECTORY${first_type_suffix})
1945    endif()
1946    if(CMAKE_CONFIGURATION_TYPES)
1947      string(FIND "${ARG_OUTPUT_DIR}" "/${first_type}/" type_start REVERSE)
1948      string(SUBSTRING "${ARG_OUTPUT_DIR}" 0 ${type_start} path_prefix)
1949      string(SUBSTRING "${ARG_OUTPUT_DIR}" ${type_start} -1 path_suffix)
1950      string(REPLACE "/${first_type}/" "/${CMAKE_CFG_INTDIR}/"
1951             path_suffix ${path_suffix})
1952      set(ARG_OUTPUT_DIR ${path_prefix}${path_suffix})
1953    endif()
1954  endif()
1955
1956  if(CMAKE_HOST_UNIX)
1957    set(LLVM_LINK_OR_COPY create_symlink)
1958  else()
1959    set(LLVM_LINK_OR_COPY copy)
1960  endif()
1961
1962  set(output_path "${ARG_OUTPUT_DIR}/${link_name}${CMAKE_EXECUTABLE_SUFFIX}")
1963
1964  set(target_name ${link_name})
1965  if(TARGET ${link_name})
1966    set(target_name ${link_name}-link)
1967  endif()
1968
1969
1970  if(ARG_ALWAYS_GENERATE)
1971    set_property(DIRECTORY APPEND PROPERTY
1972      ADDITIONAL_MAKE_CLEAN_FILES ${dest_binary})
1973    add_custom_command(TARGET ${target} POST_BUILD
1974      COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}")
1975  else()
1976    add_custom_command(OUTPUT ${output_path}
1977                     COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}"
1978                     DEPENDS ${target})
1979    add_custom_target(${target_name} ALL DEPENDS ${target} ${output_path})
1980    set_target_properties(${target_name} PROPERTIES FOLDER Tools)
1981
1982    # Make sure both the link and target are toolchain tools
1983    if (${link_name} IN_LIST LLVM_TOOLCHAIN_TOOLS AND ${target} IN_LIST LLVM_TOOLCHAIN_TOOLS)
1984      set(TOOL_IS_TOOLCHAIN ON)
1985    endif()
1986
1987    if ((TOOL_IS_TOOLCHAIN OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY) AND LLVM_BUILD_TOOLS)
1988      llvm_install_symlink(${link_name} ${target})
1989    endif()
1990  endif()
1991endfunction()
1992
1993function(llvm_externalize_debuginfo name)
1994  if(NOT LLVM_EXTERNALIZE_DEBUGINFO)
1995    return()
1996  endif()
1997
1998  if(NOT LLVM_EXTERNALIZE_DEBUGINFO_SKIP_STRIP)
1999    if(APPLE)
2000      if(NOT CMAKE_STRIP)
2001        set(CMAKE_STRIP xcrun strip)
2002      endif()
2003      set(strip_command COMMAND ${CMAKE_STRIP} -Sxl $<TARGET_FILE:${name}>)
2004    else()
2005      set(strip_command COMMAND ${CMAKE_STRIP} -g -x $<TARGET_FILE:${name}>)
2006    endif()
2007  endif()
2008
2009  if(APPLE)
2010    if(LLVM_EXTERNALIZE_DEBUGINFO_EXTENSION)
2011      set(file_ext ${LLVM_EXTERNALIZE_DEBUGINFO_EXTENSION})
2012    else()
2013      set(file_ext dSYM)
2014    endif()
2015
2016    set(output_name "$<TARGET_FILE_NAME:${name}>.${file_ext}")
2017
2018    if(LLVM_EXTERNALIZE_DEBUGINFO_OUTPUT_DIR)
2019      set(output_path "-o=${LLVM_EXTERNALIZE_DEBUGINFO_OUTPUT_DIR}/${output_name}")
2020    else()
2021      set(output_path "-o=${output_name}")
2022    endif()
2023
2024    if(CMAKE_CXX_FLAGS MATCHES "-flto"
2025      OR CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE} MATCHES "-flto")
2026
2027      set(lto_object ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${name}-lto.o)
2028      set_property(TARGET ${name} APPEND_STRING PROPERTY
2029        LINK_FLAGS " -Wl,-object_path_lto,${lto_object}")
2030    endif()
2031    if(NOT CMAKE_DSYMUTIL)
2032      set(CMAKE_DSYMUTIL xcrun dsymutil)
2033    endif()
2034    add_custom_command(TARGET ${name} POST_BUILD
2035      COMMAND ${CMAKE_DSYMUTIL} ${output_path} $<TARGET_FILE:${name}>
2036      ${strip_command}
2037      )
2038  else()
2039    add_custom_command(TARGET ${name} POST_BUILD
2040      COMMAND ${CMAKE_OBJCOPY} --only-keep-debug $<TARGET_FILE:${name}> $<TARGET_FILE:${name}>.debug
2041      ${strip_command} -R .gnu_debuglink
2042      COMMAND ${CMAKE_OBJCOPY} --add-gnu-debuglink=$<TARGET_FILE:${name}>.debug $<TARGET_FILE:${name}>
2043      )
2044  endif()
2045endfunction()
2046
2047# Usage: llvm_codesign(name [FORCE] [ENTITLEMENTS file] [BUNDLE_PATH path])
2048function(llvm_codesign name)
2049  cmake_parse_arguments(ARG "FORCE" "ENTITLEMENTS;BUNDLE_PATH" "" ${ARGN})
2050
2051  if(NOT LLVM_CODESIGNING_IDENTITY)
2052    return()
2053  endif()
2054
2055  if(CMAKE_GENERATOR STREQUAL "Xcode")
2056    set_target_properties(${name} PROPERTIES
2057      XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${LLVM_CODESIGNING_IDENTITY}
2058    )
2059    if(DEFINED ARG_ENTITLEMENTS)
2060      set_target_properties(${name} PROPERTIES
2061        XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS ${ARG_ENTITLEMENTS}
2062      )
2063    endif()
2064  elseif(APPLE AND CMAKE_HOST_SYSTEM_NAME MATCHES Darwin)
2065    if(NOT CMAKE_CODESIGN)
2066      set(CMAKE_CODESIGN xcrun codesign)
2067    endif()
2068    if(NOT CMAKE_CODESIGN_ALLOCATE)
2069      execute_process(
2070        COMMAND xcrun -f codesign_allocate
2071        OUTPUT_STRIP_TRAILING_WHITESPACE
2072        OUTPUT_VARIABLE CMAKE_CODESIGN_ALLOCATE
2073      )
2074    endif()
2075    if(DEFINED ARG_ENTITLEMENTS)
2076      set(pass_entitlements --entitlements ${ARG_ENTITLEMENTS})
2077    endif()
2078
2079    if (NOT ARG_BUNDLE_PATH)
2080      set(ARG_BUNDLE_PATH $<TARGET_FILE:${name}>)
2081    endif()
2082
2083    # ld64 now always codesigns the binaries it creates. Apply the force arg
2084    # unconditionally so that we can - for example - add entitlements to the
2085    # targets that need it.
2086    set(force_flag "-f")
2087
2088    add_custom_command(
2089      TARGET ${name} POST_BUILD
2090      COMMAND ${CMAKE_COMMAND} -E
2091              env CODESIGN_ALLOCATE=${CMAKE_CODESIGN_ALLOCATE}
2092              ${CMAKE_CODESIGN} -s ${LLVM_CODESIGNING_IDENTITY}
2093              ${pass_entitlements} ${force_flag} ${ARG_BUNDLE_PATH}
2094    )
2095  endif()
2096endfunction()
2097
2098function(llvm_setup_rpath name)
2099  if(CMAKE_INSTALL_RPATH)
2100    return()
2101  endif()
2102
2103  if(LLVM_INSTALL_PREFIX AND NOT (LLVM_INSTALL_PREFIX STREQUAL CMAKE_INSTALL_PREFIX))
2104    set(extra_libdir ${LLVM_LIBRARY_DIR})
2105  elseif(LLVM_BUILD_LIBRARY_DIR)
2106    set(extra_libdir ${LLVM_LIBRARY_DIR})
2107  endif()
2108
2109  if (APPLE)
2110    set(_install_name_dir INSTALL_NAME_DIR "@rpath")
2111    set(_install_rpath "@loader_path/../lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
2112  elseif(${CMAKE_SYSTEM_NAME} MATCHES "AIX" AND BUILD_SHARED_LIBS)
2113    # $ORIGIN is not interpreted at link time by aix ld.
2114    # Since BUILD_SHARED_LIBS is only recommended for use by developers,
2115    # hardcode the rpath to build/install lib dir first in this mode.
2116    # FIXME: update this when there is better solution.
2117    set(_install_rpath "${LLVM_LIBRARY_OUTPUT_INTDIR}" "${CMAKE_INSTALL_PREFIX}/lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
2118  elseif(UNIX)
2119    set(_install_rpath "\$ORIGIN/../lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
2120    if(${CMAKE_SYSTEM_NAME} MATCHES "(FreeBSD|DragonFly)")
2121      set_property(TARGET ${name} APPEND_STRING PROPERTY
2122                   LINK_FLAGS " -Wl,-z,origin ")
2123    endif()
2124    if(LLVM_LINKER_IS_GNULD)
2125      # $ORIGIN is not interpreted at link time by ld.bfd
2126      set_property(TARGET ${name} APPEND_STRING PROPERTY
2127                   LINK_FLAGS " -Wl,-rpath-link,${LLVM_LIBRARY_OUTPUT_INTDIR} ")
2128    endif()
2129  else()
2130    return()
2131  endif()
2132
2133  # Enable BUILD_WITH_INSTALL_RPATH unless CMAKE_BUILD_RPATH is set.
2134  if("${CMAKE_BUILD_RPATH}" STREQUAL "")
2135    set_property(TARGET ${name} PROPERTY BUILD_WITH_INSTALL_RPATH ON)
2136  endif()
2137
2138  set_target_properties(${name} PROPERTIES
2139                        INSTALL_RPATH "${_install_rpath}"
2140                        ${_install_name_dir})
2141endfunction()
2142
2143function(setup_dependency_debugging name)
2144  if(NOT LLVM_DEPENDENCY_DEBUGGING)
2145    return()
2146  endif()
2147
2148  if("intrinsics_gen" IN_LIST ARGN)
2149    return()
2150  endif()
2151
2152  set(deny_attributes_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Attributes.inc\"))")
2153  set(deny_intrinsics_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Intrinsics.inc\"))")
2154
2155  set(sandbox_command "sandbox-exec -p '(version 1) (allow default) ${deny_attributes_inc} ${deny_intrinsics_inc}'")
2156  set_target_properties(${name} PROPERTIES RULE_LAUNCH_COMPILE ${sandbox_command})
2157endfunction()
2158
2159# If the sources at the given `path` are under version control, set `out_var`
2160# to the the path of a file which will be modified when the VCS revision
2161# changes, attempting to create that file if it does not exist; if no such
2162# file exists and one cannot be created, instead set `out_var` to the
2163# empty string.
2164#
2165# If the sources are not under version control, do not define `out_var`.
2166function(find_first_existing_vc_file path out_var)
2167  if(NOT EXISTS "${path}")
2168    return()
2169  endif()
2170  find_package(Git)
2171  if(GIT_FOUND)
2172    execute_process(COMMAND ${GIT_EXECUTABLE} rev-parse --git-dir
2173      WORKING_DIRECTORY ${path}
2174      RESULT_VARIABLE git_result
2175      OUTPUT_VARIABLE git_output
2176      ERROR_QUIET)
2177    if(git_result EQUAL 0)
2178      string(STRIP "${git_output}" git_output)
2179      get_filename_component(git_dir ${git_output} ABSOLUTE BASE_DIR ${path})
2180      # Some branchless cases (e.g. 'repo') may not yet have .git/logs/HEAD
2181      if (NOT EXISTS "${git_dir}/logs/HEAD")
2182        execute_process(COMMAND ${CMAKE_COMMAND} -E touch HEAD
2183          WORKING_DIRECTORY "${git_dir}/logs"
2184          RESULT_VARIABLE touch_head_result
2185          ERROR_QUIET)
2186        if (NOT touch_head_result EQUAL 0)
2187          set(${out_var} "" PARENT_SCOPE)
2188          return()
2189        endif()
2190      endif()
2191      set(${out_var} "${git_dir}/logs/HEAD" PARENT_SCOPE)
2192    endif()
2193  endif()
2194endfunction()
2195