1include(LLVMProcessSources)
2include(LLVM-Config)
3include(DetermineGCCCompatible)
4
5function(llvm_update_compile_flags name)
6  get_property(sources TARGET ${name} PROPERTY SOURCES)
7  if("${sources}" MATCHES "\\.c(;|$)")
8    set(update_src_props ON)
9  endif()
10
11  # LLVM_REQUIRES_EH is an internal flag that individual targets can use to
12  # force EH
13  if(LLVM_REQUIRES_EH OR LLVM_ENABLE_EH)
14    if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
15      message(AUTHOR_WARNING "Exception handling requires RTTI. Enabling RTTI for ${name}")
16      set(LLVM_REQUIRES_RTTI ON)
17    endif()
18    if(MSVC)
19      list(APPEND LLVM_COMPILE_FLAGS "/EHsc")
20    endif()
21  else()
22    if(LLVM_COMPILER_IS_GCC_COMPATIBLE)
23      list(APPEND LLVM_COMPILE_FLAGS "-fno-exceptions")
24    elseif(MSVC)
25      list(APPEND LLVM_COMPILE_DEFINITIONS _HAS_EXCEPTIONS=0)
26      list(APPEND LLVM_COMPILE_FLAGS "/EHs-c-")
27    endif()
28  endif()
29
30  # LLVM_REQUIRES_RTTI is an internal flag that individual
31  # targets can use to force RTTI
32  set(LLVM_CONFIG_HAS_RTTI YES CACHE INTERNAL "")
33  if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
34    set(LLVM_CONFIG_HAS_RTTI NO CACHE INTERNAL "")
35    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_RTTI=0)
36    if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
37      list(APPEND LLVM_COMPILE_FLAGS "-fno-rtti")
38    elseif (MSVC)
39      list(APPEND LLVM_COMPILE_FLAGS "/GR-")
40    endif ()
41  elseif(MSVC)
42    list(APPEND LLVM_COMPILE_FLAGS "/GR")
43  endif()
44
45  # Assume that;
46  #   - LLVM_COMPILE_FLAGS is list.
47  #   - PROPERTY COMPILE_FLAGS is string.
48  string(REPLACE ";" " " target_compile_flags " ${LLVM_COMPILE_FLAGS}")
49
50  if(update_src_props)
51    foreach(fn ${sources})
52      get_filename_component(suf ${fn} EXT)
53      if("${suf}" STREQUAL ".cpp")
54        set_property(SOURCE ${fn} APPEND_STRING PROPERTY
55          COMPILE_FLAGS "${target_compile_flags}")
56      endif()
57    endforeach()
58  else()
59    # Update target props, since all sources are C++.
60    set_property(TARGET ${name} APPEND_STRING PROPERTY
61      COMPILE_FLAGS "${target_compile_flags}")
62  endif()
63
64  set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS ${LLVM_COMPILE_DEFINITIONS})
65endfunction()
66
67function(add_llvm_symbol_exports target_name export_file)
68  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
69    set(native_export_file "${target_name}.exports")
70    add_custom_command(OUTPUT ${native_export_file}
71      COMMAND sed -e "s/^/_/" < ${export_file} > ${native_export_file}
72      DEPENDS ${export_file}
73      VERBATIM
74      COMMENT "Creating export file for ${target_name}")
75    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
76                 LINK_FLAGS " -Wl,-exported_symbols_list,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
77  elseif(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
78    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
79                 LINK_FLAGS " -Wl,-bE:${export_file}")
80  elseif(LLVM_HAVE_LINK_VERSION_SCRIPT)
81    # Gold and BFD ld require a version script rather than a plain list.
82    set(native_export_file "${target_name}.exports")
83    # FIXME: Don't write the "local:" line on OpenBSD.
84    # in the export file, also add a linker script to version LLVM symbols (form: LLVM_N.M)
85    add_custom_command(OUTPUT ${native_export_file}
86      COMMAND echo "LLVM_${LLVM_VERSION_MAJOR} {" > ${native_export_file}
87      COMMAND grep -q "[[:alnum:]]" ${export_file} && echo "  global:" >> ${native_export_file} || :
88      COMMAND sed -e "s/$/;/" -e "s/^/    /" < ${export_file} >> ${native_export_file}
89      COMMAND echo "  local: *;" >> ${native_export_file}
90      COMMAND echo "};" >> ${native_export_file}
91      DEPENDS ${export_file}
92      VERBATIM
93      COMMENT "Creating export file for ${target_name}")
94    if (${LLVM_LINKER_IS_SOLARISLD})
95      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
96                   LINK_FLAGS "  -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
97    else()
98      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
99                   LINK_FLAGS "  -Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
100    endif()
101  else()
102    set(native_export_file "${target_name}.def")
103
104    add_custom_command(OUTPUT ${native_export_file}
105      COMMAND ${PYTHON_EXECUTABLE} -c "import sys;print(''.join(['EXPORTS\\n']+sys.stdin.readlines(),))"
106        < ${export_file} > ${native_export_file}
107      DEPENDS ${export_file}
108      VERBATIM
109      COMMENT "Creating export file for ${target_name}")
110    set(export_file_linker_flag "${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
111    if(MSVC)
112      set(export_file_linker_flag "/DEF:\"${export_file_linker_flag}\"")
113    endif()
114    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
115                 LINK_FLAGS " ${export_file_linker_flag}")
116  endif()
117
118  add_custom_target(${target_name}_exports DEPENDS ${native_export_file})
119  set_target_properties(${target_name}_exports PROPERTIES FOLDER "Misc")
120
121  get_property(srcs TARGET ${target_name} PROPERTY SOURCES)
122  foreach(src ${srcs})
123    get_filename_component(extension ${src} EXT)
124    if(extension STREQUAL ".cpp")
125      set(first_source_file ${src})
126      break()
127    endif()
128  endforeach()
129
130  # Force re-linking when the exports file changes. Actually, it
131  # forces recompilation of the source file. The LINK_DEPENDS target
132  # property only works for makefile-based generators.
133  # FIXME: This is not safe because this will create the same target
134  # ${native_export_file} in several different file:
135  # - One where we emitted ${target_name}_exports
136  # - One where we emitted the build command for the following object.
137  # set_property(SOURCE ${first_source_file} APPEND PROPERTY
138  #   OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file})
139
140  set_property(DIRECTORY APPEND
141    PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${native_export_file})
142
143  add_dependencies(${target_name} ${target_name}_exports)
144
145  # Add dependency to *_exports later -- CMake issue 14747
146  list(APPEND LLVM_COMMON_DEPENDS ${target_name}_exports)
147  set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE)
148endfunction(add_llvm_symbol_exports)
149
150if(APPLE)
151  execute_process(
152    COMMAND "${CMAKE_LINKER}" -v
153    ERROR_VARIABLE stderr
154    )
155  set(LLVM_LINKER_DETECTED YES)
156  if("${stderr}" MATCHES "PROJECT:ld64")
157    set(LLVM_LINKER_IS_LD64 YES)
158    message(STATUS "Linker detection: ld64")
159  else()
160    set(LLVM_LINKER_DETECTED NO)
161    message(STATUS "Linker detection: unknown")
162  endif()
163elseif(NOT WIN32)
164  # Detect what linker we have here
165  if( LLVM_USE_LINKER )
166    set(command ${CMAKE_C_COMPILER} -fuse-ld=${LLVM_USE_LINKER} -Wl,--version)
167  else()
168    separate_arguments(flags UNIX_COMMAND "${CMAKE_EXE_LINKER_FLAGS}")
169    set(command ${CMAKE_C_COMPILER} ${flags} -Wl,--version)
170  endif()
171  execute_process(
172    COMMAND ${command}
173    OUTPUT_VARIABLE stdout
174    ERROR_VARIABLE stderr
175    )
176  set(LLVM_LINKER_DETECTED YES)
177  if("${stdout}" MATCHES "GNU gold")
178    set(LLVM_LINKER_IS_GOLD YES)
179    message(STATUS "Linker detection: GNU Gold")
180  elseif("${stdout}" MATCHES "^LLD")
181    set(LLVM_LINKER_IS_LLD YES)
182    message(STATUS "Linker detection: LLD")
183  elseif("${stdout}" MATCHES "GNU ld")
184    set(LLVM_LINKER_IS_GNULD YES)
185    message(STATUS "Linker detection: GNU ld")
186  elseif("${stderr}" MATCHES "Solaris Link Editors" OR
187         "${stdout}" MATCHES "Solaris Link Editors")
188    set(LLVM_LINKER_IS_SOLARISLD YES)
189    message(STATUS "Linker detection: Solaris ld")
190  else()
191    set(LLVM_LINKER_DETECTED NO)
192    message(STATUS "Linker detection: unknown")
193  endif()
194endif()
195
196function(add_link_opts target_name)
197  # Don't use linker optimizations in debug builds since it slows down the
198  # linker in a context where the optimizations are not important.
199  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
200
201    # Pass -O3 to the linker. This enabled different optimizations on different
202    # linkers.
203    if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin|SunOS|AIX" OR WIN32))
204      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
205                   LINK_FLAGS " -Wl,-O3")
206    endif()
207
208    if(LLVM_LINKER_IS_GOLD)
209      # With gold gc-sections is always safe.
210      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
211                   LINK_FLAGS " -Wl,--gc-sections")
212      # Note that there is a bug with -Wl,--icf=safe so it is not safe
213      # to enable. See https://sourceware.org/bugzilla/show_bug.cgi?id=17704.
214    endif()
215
216    if(NOT LLVM_NO_DEAD_STRIP)
217      if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
218        # ld64's implementation of -dead_strip breaks tools that use plugins.
219        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
220                     LINK_FLAGS " -Wl,-dead_strip")
221      elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
222        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
223                     LINK_FLAGS " -Wl,-z -Wl,discard-unused=sections")
224      elseif(NOT WIN32 AND NOT LLVM_LINKER_IS_GOLD AND NOT ${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD")
225        # Object files are compiled with -ffunction-data-sections.
226        # Versions of bfd ld < 2.23.1 have a bug in --gc-sections that breaks
227        # tools that use plugins. Always pass --gc-sections once we require
228        # a newer linker.
229        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
230                     LINK_FLAGS " -Wl,--gc-sections")
231      endif()
232    endif()
233  endif()
234endfunction(add_link_opts)
235
236# Set each output directory according to ${CMAKE_CONFIGURATION_TYPES}.
237# Note: Don't set variables CMAKE_*_OUTPUT_DIRECTORY any more,
238# or a certain builder, for eaxample, msbuild.exe, would be confused.
239function(set_output_directory target)
240  cmake_parse_arguments(ARG "" "BINARY_DIR;LIBRARY_DIR" "" ${ARGN})
241
242  # module_dir -- corresponding to LIBRARY_OUTPUT_DIRECTORY.
243  # It affects output of add_library(MODULE).
244  if(WIN32 OR CYGWIN)
245    # DLL platform
246    set(module_dir ${ARG_BINARY_DIR})
247  else()
248    set(module_dir ${ARG_LIBRARY_DIR})
249  endif()
250  if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
251    foreach(build_mode ${CMAKE_CONFIGURATION_TYPES})
252      string(TOUPPER "${build_mode}" CONFIG_SUFFIX)
253      if(ARG_BINARY_DIR)
254        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} bi ${ARG_BINARY_DIR})
255        set_target_properties(${target} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${bi})
256      endif()
257      if(ARG_LIBRARY_DIR)
258        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} li ${ARG_LIBRARY_DIR})
259        set_target_properties(${target} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${li})
260      endif()
261      if(module_dir)
262        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} mi ${module_dir})
263        set_target_properties(${target} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${mi})
264      endif()
265    endforeach()
266  else()
267    if(ARG_BINARY_DIR)
268      set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ARG_BINARY_DIR})
269    endif()
270    if(ARG_LIBRARY_DIR)
271      set_target_properties(${target} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${ARG_LIBRARY_DIR})
272    endif()
273    if(module_dir)
274      set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${module_dir})
275    endif()
276  endif()
277endfunction()
278
279# If on Windows and building with MSVC, add the resource script containing the
280# VERSIONINFO data to the project.  This embeds version resource information
281# into the output .exe or .dll.
282# TODO: Enable for MinGW Windows builds too.
283#
284function(add_windows_version_resource_file OUT_VAR)
285  set(sources ${ARGN})
286  if (MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
287    set(resource_file ${LLVM_SOURCE_DIR}/resources/windows_version_resource.rc)
288    if(EXISTS ${resource_file})
289      set(sources ${sources} ${resource_file})
290      source_group("Resource Files" ${resource_file})
291      set(windows_resource_file ${resource_file} PARENT_SCOPE)
292    endif()
293  endif(MSVC AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows")
294
295  set(${OUT_VAR} ${sources} PARENT_SCOPE)
296endfunction(add_windows_version_resource_file)
297
298# set_windows_version_resource_properties(name resource_file...
299#   VERSION_MAJOR int
300#     Optional major version number (defaults to LLVM_VERSION_MAJOR)
301#   VERSION_MINOR int
302#     Optional minor version number (defaults to LLVM_VERSION_MINOR)
303#   VERSION_PATCHLEVEL int
304#     Optional patchlevel version number (defaults to LLVM_VERSION_PATCH)
305#   VERSION_STRING
306#     Optional version string (defaults to PACKAGE_VERSION)
307#   PRODUCT_NAME
308#     Optional product name string (defaults to "LLVM")
309#   )
310function(set_windows_version_resource_properties name resource_file)
311  cmake_parse_arguments(ARG
312    ""
313    "VERSION_MAJOR;VERSION_MINOR;VERSION_PATCHLEVEL;VERSION_STRING;PRODUCT_NAME"
314    ""
315    ${ARGN})
316
317  if (NOT DEFINED ARG_VERSION_MAJOR)
318    set(ARG_VERSION_MAJOR ${LLVM_VERSION_MAJOR})
319  endif()
320
321  if (NOT DEFINED ARG_VERSION_MINOR)
322    set(ARG_VERSION_MINOR ${LLVM_VERSION_MINOR})
323  endif()
324
325  if (NOT DEFINED ARG_VERSION_PATCHLEVEL)
326    set(ARG_VERSION_PATCHLEVEL ${LLVM_VERSION_PATCH})
327  endif()
328
329  if (NOT DEFINED ARG_VERSION_STRING)
330    set(ARG_VERSION_STRING ${PACKAGE_VERSION})
331  endif()
332
333  if (NOT DEFINED ARG_PRODUCT_NAME)
334    set(ARG_PRODUCT_NAME "LLVM")
335  endif()
336
337  set_property(SOURCE ${resource_file}
338               PROPERTY COMPILE_FLAGS /nologo)
339  set_property(SOURCE ${resource_file}
340               PROPERTY COMPILE_DEFINITIONS
341               "RC_VERSION_FIELD_1=${ARG_VERSION_MAJOR}"
342               "RC_VERSION_FIELD_2=${ARG_VERSION_MINOR}"
343               "RC_VERSION_FIELD_3=${ARG_VERSION_PATCHLEVEL}"
344               "RC_VERSION_FIELD_4=0"
345               "RC_FILE_VERSION=\"${ARG_VERSION_STRING}\""
346               "RC_INTERNAL_NAME=\"${name}\""
347               "RC_PRODUCT_NAME=\"${ARG_PRODUCT_NAME}\""
348               "RC_PRODUCT_VERSION=\"${ARG_VERSION_STRING}\"")
349endfunction(set_windows_version_resource_properties)
350
351# llvm_add_library(name sources...
352#   SHARED;STATIC
353#     STATIC by default w/o BUILD_SHARED_LIBS.
354#     SHARED by default w/  BUILD_SHARED_LIBS.
355#   OBJECT
356#     Also create an OBJECT library target. Default if STATIC && SHARED.
357#   MODULE
358#     Target ${name} might not be created on unsupported platforms.
359#     Check with "if(TARGET ${name})".
360#   DISABLE_LLVM_LINK_LLVM_DYLIB
361#     Do not link this library to libLLVM, even if
362#     LLVM_LINK_LLVM_DYLIB is enabled.
363#   OUTPUT_NAME name
364#     Corresponds to OUTPUT_NAME in target properties.
365#   DEPENDS targets...
366#     Same semantics as add_dependencies().
367#   LINK_COMPONENTS components...
368#     Same as the variable LLVM_LINK_COMPONENTS.
369#   LINK_LIBS lib_targets...
370#     Same semantics as target_link_libraries().
371#   ADDITIONAL_HEADERS
372#     May specify header files for IDE generators.
373#   SONAME
374#     Should set SONAME link flags and create symlinks
375#   PLUGIN_TOOL
376#     The tool (i.e. cmake target) that this plugin will link against
377#   )
378function(llvm_add_library name)
379  cmake_parse_arguments(ARG
380    "MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME"
381    "OUTPUT_NAME;PLUGIN_TOOL"
382    "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
383    ${ARGN})
384  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
385  if(ARG_ADDITIONAL_HEADERS)
386    # Pass through ADDITIONAL_HEADERS.
387    set(ARG_ADDITIONAL_HEADERS ADDITIONAL_HEADERS ${ARG_ADDITIONAL_HEADERS})
388  endif()
389  if(ARG_OBJLIBS)
390    set(ALL_FILES ${ARG_OBJLIBS})
391  else()
392    llvm_process_sources(ALL_FILES ${ARG_UNPARSED_ARGUMENTS} ${ARG_ADDITIONAL_HEADERS})
393  endif()
394
395  if(ARG_MODULE)
396    if(ARG_SHARED OR ARG_STATIC)
397      message(WARNING "MODULE with SHARED|STATIC doesn't make sense.")
398    endif()
399    # Plugins that link against a tool are allowed even when plugins in general are not
400    if(NOT LLVM_ENABLE_PLUGINS AND NOT (ARG_PLUGIN_TOOL AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS))
401      message(STATUS "${name} ignored -- Loadable modules not supported on this platform.")
402      return()
403    endif()
404  else()
405    if(ARG_PLUGIN_TOOL)
406      message(WARNING "PLUGIN_TOOL without MODULE doesn't make sense.")
407    endif()
408    if(BUILD_SHARED_LIBS AND NOT ARG_STATIC)
409      set(ARG_SHARED TRUE)
410    endif()
411    if(NOT ARG_SHARED)
412      set(ARG_STATIC TRUE)
413    endif()
414  endif()
415
416  # Generate objlib
417  if((ARG_SHARED AND ARG_STATIC) OR ARG_OBJECT)
418    # Generate an obj library for both targets.
419    set(obj_name "obj.${name}")
420    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
421      ${ALL_FILES}
422      )
423    llvm_update_compile_flags(${obj_name})
424    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
425
426    # Do add_dependencies(obj) later due to CMake issue 14747.
427    list(APPEND objlibs ${obj_name})
428
429    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
430  endif()
431
432  if(ARG_SHARED AND ARG_STATIC)
433    # static
434    set(name_static "${name}_static")
435    if(ARG_OUTPUT_NAME)
436      set(output_name OUTPUT_NAME "${ARG_OUTPUT_NAME}")
437    endif()
438    # DEPENDS has been appended to LLVM_COMMON_LIBS.
439    llvm_add_library(${name_static} STATIC
440      ${output_name}
441      OBJLIBS ${ALL_FILES} # objlib
442      LINK_LIBS ${ARG_LINK_LIBS}
443      LINK_COMPONENTS ${ARG_LINK_COMPONENTS}
444      )
445    # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY.
446    set(ARG_STATIC)
447  endif()
448
449  if(ARG_MODULE)
450    add_library(${name} MODULE ${ALL_FILES})
451    llvm_setup_rpath(${name})
452  elseif(ARG_SHARED)
453    add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
454    add_library(${name} SHARED ${ALL_FILES})
455
456    llvm_setup_rpath(${name})
457
458  else()
459    add_library(${name} STATIC ${ALL_FILES})
460  endif()
461
462  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
463
464  if(DEFINED windows_resource_file)
465    set_windows_version_resource_properties(${name} ${windows_resource_file})
466    set(windows_resource_file ${windows_resource_file} PARENT_SCOPE)
467  endif()
468
469  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
470  # $<TARGET_OBJECTS> doesn't require compile flags.
471  if(NOT obj_name)
472    llvm_update_compile_flags(${name})
473  endif()
474  add_link_opts( ${name} )
475  if(ARG_OUTPUT_NAME)
476    set_target_properties(${name}
477      PROPERTIES
478      OUTPUT_NAME ${ARG_OUTPUT_NAME}
479      )
480  endif()
481
482  if(ARG_MODULE)
483    set_target_properties(${name} PROPERTIES
484      PREFIX ""
485      SUFFIX ${LLVM_PLUGIN_EXT}
486      )
487  endif()
488
489  if(ARG_SHARED)
490    if(WIN32)
491      set_target_properties(${name} PROPERTIES
492        PREFIX ""
493        )
494    endif()
495
496    # Set SOVERSION on shared libraries that lack explicit SONAME
497    # specifier, on *nix systems that are not Darwin.
498    if(UNIX AND NOT APPLE AND NOT ARG_SONAME)
499      set_target_properties(${name}
500        PROPERTIES
501        # Since 4.0.0, the ABI version is indicated by the major version
502        SOVERSION ${LLVM_VERSION_MAJOR}
503        VERSION ${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
504    endif()
505  endif()
506
507  if(ARG_MODULE OR ARG_SHARED)
508    # Do not add -Dname_EXPORTS to the command-line when building files in this
509    # target. Doing so is actively harmful for the modules build because it
510    # creates extra module variants, and not useful because we don't use these
511    # macros.
512    set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
513
514    if (LLVM_EXPORTED_SYMBOL_FILE)
515      add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
516    endif()
517  endif()
518
519  if(ARG_SHARED AND UNIX)
520    if(NOT APPLE AND ARG_SONAME)
521      get_target_property(output_name ${name} OUTPUT_NAME)
522      if(${output_name} STREQUAL "output_name-NOTFOUND")
523        set(output_name ${name})
524      endif()
525      set(library_name ${output_name}-${LLVM_VERSION_MAJOR}${LLVM_VERSION_SUFFIX})
526      set(api_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX})
527      set_target_properties(${name} PROPERTIES OUTPUT_NAME ${library_name})
528      llvm_install_library_symlink(${api_name} ${library_name} SHARED
529        COMPONENT ${name}
530        ALWAYS_GENERATE)
531      llvm_install_library_symlink(${output_name} ${library_name} SHARED
532        COMPONENT ${name}
533        ALWAYS_GENERATE)
534    endif()
535  endif()
536
537  if(ARG_MODULE AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS AND ARG_PLUGIN_TOOL AND (WIN32 OR CYGWIN))
538    # On DLL platforms symbols are imported from the tool by linking against it.
539    set(llvm_libs ${ARG_PLUGIN_TOOL})
540  elseif (DEFINED LLVM_LINK_COMPONENTS OR DEFINED ARG_LINK_COMPONENTS)
541    if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
542      set(llvm_libs LLVM)
543    else()
544      llvm_map_components_to_libnames(llvm_libs
545       ${ARG_LINK_COMPONENTS}
546       ${LLVM_LINK_COMPONENTS}
547       )
548    endif()
549  else()
550    # Components have not been defined explicitly in CMake, so add the
551    # dependency information for this library as defined by LLVMBuild.
552    #
553    # It would be nice to verify that we have the dependencies for this library
554    # name, but using get_property(... SET) doesn't suffice to determine if a
555    # property has been set to an empty value.
556    get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})
557  endif()
558
559  if(ARG_STATIC)
560    set(libtype INTERFACE)
561  else()
562    # We can use PRIVATE since SO knows its dependent libs.
563    set(libtype PRIVATE)
564  endif()
565
566  target_link_libraries(${name} ${libtype}
567      ${ARG_LINK_LIBS}
568      ${lib_deps}
569      ${llvm_libs}
570      )
571
572  if(LLVM_COMMON_DEPENDS)
573    add_dependencies(${name} ${LLVM_COMMON_DEPENDS})
574    # Add dependencies also to objlibs.
575    # CMake issue 14747 --  add_dependencies() might be ignored to objlib's user.
576    foreach(objlib ${objlibs})
577      add_dependencies(${objlib} ${LLVM_COMMON_DEPENDS})
578    endforeach()
579  endif()
580
581  if(ARG_SHARED OR ARG_MODULE)
582    llvm_externalize_debuginfo(${name})
583    llvm_codesign(${name})
584  endif()
585endfunction()
586
587function(add_llvm_install_targets target)
588  cmake_parse_arguments(ARG "" "COMPONENT;PREFIX" "DEPENDS" ${ARGN})
589  if(ARG_COMPONENT)
590    set(component_option -DCMAKE_INSTALL_COMPONENT="${ARG_COMPONENT}")
591  endif()
592  if(ARG_PREFIX)
593    set(prefix_option -DCMAKE_INSTALL_PREFIX="${ARG_PREFIX}")
594  endif()
595
596  add_custom_target(${target}
597                    DEPENDS ${ARG_DEPENDS}
598                    COMMAND "${CMAKE_COMMAND}"
599                            ${component_option}
600                            ${prefix_option}
601                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
602                    USES_TERMINAL)
603  add_custom_target(${target}-stripped
604                    DEPENDS ${ARG_DEPENDS}
605                    COMMAND "${CMAKE_COMMAND}"
606                            ${component_option}
607                            ${prefix_option}
608                            -DCMAKE_INSTALL_DO_STRIP=1
609                            -P "${CMAKE_BINARY_DIR}/cmake_install.cmake"
610                    USES_TERMINAL)
611endfunction()
612
613macro(add_llvm_library name)
614  cmake_parse_arguments(ARG
615    "SHARED;BUILDTREE_ONLY"
616    ""
617    ""
618    ${ARGN})
619  if( BUILD_SHARED_LIBS OR ARG_SHARED )
620    llvm_add_library(${name} SHARED ${ARG_UNPARSED_ARGUMENTS})
621  else()
622    llvm_add_library(${name} ${ARG_UNPARSED_ARGUMENTS})
623  endif()
624
625  # Libraries that are meant to only be exposed via the build tree only are
626  # never installed and are only exported as a target in the special build tree
627  # config file.
628  if (NOT ARG_BUILDTREE_ONLY)
629    set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} )
630  endif()
631
632  if( EXCLUDE_FROM_ALL )
633    set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
634  elseif(ARG_BUILDTREE_ONLY)
635    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS_BUILDTREE_ONLY ${name})
636  else()
637    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "LTO" OR
638        (LLVM_LINK_LLVM_DYLIB AND ${name} STREQUAL "LLVM"))
639      set(install_dir lib${LLVM_LIBDIR_SUFFIX})
640      if(ARG_SHARED OR BUILD_SHARED_LIBS)
641        if(WIN32 OR CYGWIN OR MINGW)
642          set(install_type RUNTIME)
643          set(install_dir bin)
644        else()
645          set(install_type LIBRARY)
646        endif()
647      else()
648        set(install_type ARCHIVE)
649      endif()
650
651      if(${name} IN_LIST LLVM_DISTRIBUTION_COMPONENTS OR
652          NOT LLVM_DISTRIBUTION_COMPONENTS)
653        set(export_to_llvmexports EXPORT LLVMExports)
654        set_property(GLOBAL PROPERTY LLVM_HAS_EXPORTS True)
655      endif()
656
657      install(TARGETS ${name}
658              ${export_to_llvmexports}
659              ${install_type} DESTINATION ${install_dir}
660              COMPONENT ${name})
661
662      if (NOT CMAKE_CONFIGURATION_TYPES)
663        add_llvm_install_targets(install-${name}
664                                 DEPENDS ${name}
665                                 COMPONENT ${name})
666      endif()
667    endif()
668    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
669  endif()
670  set_target_properties(${name} PROPERTIES FOLDER "Libraries")
671endmacro(add_llvm_library name)
672
673macro(add_llvm_loadable_module name)
674  llvm_add_library(${name} MODULE ${ARGN})
675  if(NOT TARGET ${name})
676    # Add empty "phony" target
677    add_custom_target(${name})
678  else()
679    if( EXCLUDE_FROM_ALL )
680      set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
681    else()
682      if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
683        if(WIN32 OR CYGWIN)
684          # DLL platform
685          set(dlldir "bin")
686        else()
687          set(dlldir "lib${LLVM_LIBDIR_SUFFIX}")
688        endif()
689
690        if(${name} IN_LIST LLVM_DISTRIBUTION_COMPONENTS OR
691            NOT LLVM_DISTRIBUTION_COMPONENTS)
692          set(export_to_llvmexports EXPORT LLVMExports)
693          set_property(GLOBAL PROPERTY LLVM_HAS_EXPORTS True)
694        endif()
695
696        install(TARGETS ${name}
697                ${export_to_llvmexports}
698                LIBRARY DESTINATION ${dlldir}
699                ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX})
700      endif()
701      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
702    endif()
703  endif()
704
705  set_target_properties(${name} PROPERTIES FOLDER "Loadable modules")
706endmacro(add_llvm_loadable_module name)
707
708
709macro(add_llvm_executable name)
710  cmake_parse_arguments(ARG "DISABLE_LLVM_LINK_LLVM_DYLIB;IGNORE_EXTERNALIZE_DEBUGINFO;NO_INSTALL_RPATH" "" "DEPENDS" ${ARGN})
711  llvm_process_sources( ALL_FILES ${ARG_UNPARSED_ARGUMENTS} )
712
713  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
714
715  # Generate objlib
716  if(LLVM_ENABLE_OBJLIB)
717    # Generate an obj library for both targets.
718    set(obj_name "obj.${name}")
719    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
720      ${ALL_FILES}
721      )
722    llvm_update_compile_flags(${obj_name})
723    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
724
725    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
726  endif()
727
728  add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
729
730  if(XCODE)
731    # Note: the dummy.cpp source file provides no definitions. However,
732    # it forces Xcode to properly link the static library.
733    list(APPEND ALL_FILES "${LLVM_MAIN_SRC_DIR}/cmake/dummy.cpp")
734  endif()
735
736  if( EXCLUDE_FROM_ALL )
737    add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES})
738  else()
739    add_executable(${name} ${ALL_FILES})
740  endif()
741
742  setup_dependency_debugging(${name} ${LLVM_COMMON_DEPENDS})
743
744  if(NOT ARG_NO_INSTALL_RPATH)
745    llvm_setup_rpath(${name})
746  endif()
747
748  if(DEFINED windows_resource_file)
749    set_windows_version_resource_properties(${name} ${windows_resource_file})
750  endif()
751
752  # $<TARGET_OBJECTS> doesn't require compile flags.
753  if(NOT LLVM_ENABLE_OBJLIB)
754    llvm_update_compile_flags(${name})
755  endif()
756  add_link_opts( ${name} )
757
758  # Do not add -Dname_EXPORTS to the command-line when building files in this
759  # target. Doing so is actively harmful for the modules build because it
760  # creates extra module variants, and not useful because we don't use these
761  # macros.
762  set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
763
764  if (LLVM_EXPORTED_SYMBOL_FILE)
765    add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
766  endif(LLVM_EXPORTED_SYMBOL_FILE)
767
768  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
769    set(USE_SHARED USE_SHARED)
770  endif()
771
772  set(EXCLUDE_FROM_ALL OFF)
773  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
774  llvm_config( ${name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )
775  if( LLVM_COMMON_DEPENDS )
776    add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
777  endif( LLVM_COMMON_DEPENDS )
778
779  if(NOT ARG_IGNORE_EXTERNALIZE_DEBUGINFO)
780    llvm_externalize_debuginfo(${name})
781  endif()
782  if (LLVM_PTHREAD_LIB)
783    # libpthreads overrides some standard library symbols, so main
784    # executable must be linked with it in order to provide consistent
785    # API for all shared libaries loaded by this executable.
786    target_link_libraries(${name} PRIVATE ${LLVM_PTHREAD_LIB})
787  endif()
788
789  llvm_codesign(${name})
790endmacro(add_llvm_executable name)
791
792function(export_executable_symbols target)
793  if (LLVM_EXPORTED_SYMBOL_FILE)
794    # The symbol file should contain the symbols we want the executable to
795    # export
796    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
797  elseif (LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
798    # Extract the symbols to export from the static libraries that the
799    # executable links against.
800    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
801    set(exported_symbol_file ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${target}.symbols)
802    # We need to consider not just the direct link dependencies, but also the
803    # transitive link dependencies. Do this by starting with the set of direct
804    # dependencies, then the dependencies of those dependencies, and so on.
805    get_target_property(new_libs ${target} LINK_LIBRARIES)
806    set(link_libs ${new_libs})
807    while(NOT "${new_libs}" STREQUAL "")
808      foreach(lib ${new_libs})
809        if(TARGET ${lib})
810          get_target_property(lib_type ${lib} TYPE)
811          if("${lib_type}" STREQUAL "STATIC_LIBRARY")
812            list(APPEND static_libs ${lib})
813          else()
814            list(APPEND other_libs ${lib})
815          endif()
816          get_target_property(transitive_libs ${lib} INTERFACE_LINK_LIBRARIES)
817          foreach(transitive_lib ${transitive_libs})
818            list(FIND link_libs ${transitive_lib} idx)
819            if(TARGET ${transitive_lib} AND idx EQUAL -1)
820              list(APPEND newer_libs ${transitive_lib})
821              list(APPEND link_libs ${transitive_lib})
822            endif()
823          endforeach(transitive_lib)
824        endif()
825      endforeach(lib)
826      set(new_libs ${newer_libs})
827      set(newer_libs "")
828    endwhile()
829    if (MSVC)
830      set(mangling microsoft)
831    else()
832      set(mangling itanium)
833    endif()
834    add_custom_command(OUTPUT ${exported_symbol_file}
835                       COMMAND ${PYTHON_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py --mangling=${mangling} ${static_libs} -o ${exported_symbol_file}
836                       WORKING_DIRECTORY ${LLVM_LIBRARY_OUTPUT_INTDIR}
837                       DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${static_libs}
838                       VERBATIM
839                       COMMENT "Generating export list for ${target}")
840    add_llvm_symbol_exports( ${target} ${exported_symbol_file} )
841    # If something links against this executable then we want a
842    # transitive link against only the libraries whose symbols
843    # we aren't exporting.
844    set_target_properties(${target} PROPERTIES INTERFACE_LINK_LIBRARIES "${other_libs}")
845    # The default import library suffix that cmake uses for cygwin/mingw is
846    # ".dll.a", but for clang.exe that causes a collision with libclang.dll,
847    # where the import libraries of both get named libclang.dll.a. Use a suffix
848    # of ".exe.a" to avoid this.
849    if(CYGWIN OR MINGW)
850      set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".exe.a")
851    endif()
852  elseif(NOT (WIN32 OR CYGWIN))
853    # On Windows auto-exporting everything doesn't work because of the limit on
854    # the size of the exported symbol table, but on other platforms we can do
855    # it without any trouble.
856    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
857    if (APPLE)
858      set_property(TARGET ${target} APPEND_STRING PROPERTY
859        LINK_FLAGS " -rdynamic")
860    endif()
861  endif()
862endfunction()
863
864if(NOT LLVM_TOOLCHAIN_TOOLS)
865  set (LLVM_TOOLCHAIN_TOOLS
866    llvm-ar
867    llvm-ranlib
868    llvm-lib
869    llvm-objdump
870    )
871endif()
872
873macro(add_llvm_tool name)
874  if( NOT LLVM_BUILD_TOOLS )
875    set(EXCLUDE_FROM_ALL ON)
876  endif()
877  add_llvm_executable(${name} ${ARGN})
878
879  if ( ${name} IN_LIST LLVM_TOOLCHAIN_TOOLS OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
880    if( LLVM_BUILD_TOOLS )
881      if(${name} IN_LIST LLVM_DISTRIBUTION_COMPONENTS OR
882          NOT LLVM_DISTRIBUTION_COMPONENTS)
883        set(export_to_llvmexports EXPORT LLVMExports)
884        set_property(GLOBAL PROPERTY LLVM_HAS_EXPORTS True)
885      endif()
886
887      install(TARGETS ${name}
888              ${export_to_llvmexports}
889              RUNTIME DESTINATION ${LLVM_TOOLS_INSTALL_DIR}
890              COMPONENT ${name})
891
892      if (NOT CMAKE_CONFIGURATION_TYPES)
893        add_llvm_install_targets(install-${name}
894                                 DEPENDS ${name}
895                                 COMPONENT ${name})
896      endif()
897    endif()
898  endif()
899  if( LLVM_BUILD_TOOLS )
900    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
901  endif()
902  set_target_properties(${name} PROPERTIES FOLDER "Tools")
903endmacro(add_llvm_tool name)
904
905
906macro(add_llvm_example name)
907  if( NOT LLVM_BUILD_EXAMPLES )
908    set(EXCLUDE_FROM_ALL ON)
909  endif()
910  add_llvm_executable(${name} ${ARGN})
911  if( LLVM_BUILD_EXAMPLES )
912    install(TARGETS ${name} RUNTIME DESTINATION examples)
913  endif()
914  set_target_properties(${name} PROPERTIES FOLDER "Examples")
915endmacro(add_llvm_example name)
916
917# This is a macro that is used to create targets for executables that are needed
918# for development, but that are not intended to be installed by default.
919macro(add_llvm_utility name)
920  if ( NOT LLVM_BUILD_UTILS )
921    set(EXCLUDE_FROM_ALL ON)
922  endif()
923
924  add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
925  set_target_properties(${name} PROPERTIES FOLDER "Utils")
926  if( LLVM_INSTALL_UTILS AND LLVM_BUILD_UTILS )
927    install (TARGETS ${name}
928      RUNTIME DESTINATION ${LLVM_UTILS_INSTALL_DIR}
929      COMPONENT ${name})
930    if (NOT CMAKE_CONFIGURATION_TYPES)
931      add_llvm_install_targets(install-${name}
932                               DEPENDS ${name}
933                               COMPONENT ${name})
934    endif()
935  endif()
936endmacro(add_llvm_utility name)
937
938macro(add_llvm_fuzzer name)
939  cmake_parse_arguments(ARG "" "DUMMY_MAIN" "" ${ARGN})
940  if( LLVM_LIB_FUZZING_ENGINE )
941    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
942    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
943    target_link_libraries(${name} PRIVATE ${LLVM_LIB_FUZZING_ENGINE})
944    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
945  elseif( LLVM_USE_SANITIZE_COVERAGE )
946    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=fuzzer")
947    set(LLVM_OPTIONAL_SOURCES ${ARG_DUMMY_MAIN})
948    add_llvm_executable(${name} ${ARG_UNPARSED_ARGUMENTS})
949    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
950  elseif( ARG_DUMMY_MAIN )
951    add_llvm_executable(${name} ${ARG_DUMMY_MAIN} ${ARG_UNPARSED_ARGUMENTS})
952    set_target_properties(${name} PROPERTIES FOLDER "Fuzzers")
953  endif()
954endmacro()
955
956macro(add_llvm_target target_name)
957  include_directories(BEFORE
958    ${CMAKE_CURRENT_BINARY_DIR}
959    ${CMAKE_CURRENT_SOURCE_DIR})
960  add_llvm_library(LLVM${target_name} ${ARGN})
961  set( CURRENT_LLVM_TARGET LLVM${target_name} )
962endmacro(add_llvm_target)
963
964function(canonicalize_tool_name name output)
965  string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" nameStrip ${name})
966  string(REPLACE "-" "_" nameUNDERSCORE ${nameStrip})
967  string(TOUPPER ${nameUNDERSCORE} nameUPPER)
968  set(${output} "${nameUPPER}" PARENT_SCOPE)
969endfunction(canonicalize_tool_name)
970
971# Custom add_subdirectory wrapper
972# Takes in a project name (i.e. LLVM), the subdirectory name, and an optional
973# path if it differs from the name.
974macro(add_llvm_subdirectory project type name)
975  set(add_llvm_external_dir "${ARGN}")
976  if("${add_llvm_external_dir}" STREQUAL "")
977    set(add_llvm_external_dir ${name})
978  endif()
979  canonicalize_tool_name(${name} nameUPPER)
980  if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}/CMakeLists.txt)
981    # Treat it as in-tree subproject.
982    option(${project}_${type}_${nameUPPER}_BUILD
983           "Whether to build ${name} as part of ${project}" On)
984    mark_as_advanced(${project}_${type}_${name}_BUILD)
985    if(${project}_${type}_${nameUPPER}_BUILD)
986      add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir} ${add_llvm_external_dir})
987      # Don't process it in add_llvm_implicit_projects().
988      set(${project}_${type}_${nameUPPER}_BUILD OFF)
989    endif()
990  else()
991    set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR
992      "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}"
993      CACHE PATH "Path to ${name} source directory")
994    set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT ON)
995    if(NOT LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR OR NOT EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
996      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
997    endif()
998    if("${LLVM_EXTERNAL_${nameUPPER}_BUILD}" STREQUAL "OFF")
999      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
1000    endif()
1001    option(${project}_${type}_${nameUPPER}_BUILD
1002      "Whether to build ${name} as part of LLVM"
1003      ${${project}_${type}_${nameUPPER}_BUILD_DEFAULT})
1004    if (${project}_${type}_${nameUPPER}_BUILD)
1005      if(EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
1006        add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${add_llvm_external_dir})
1007      elseif(NOT "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}" STREQUAL "")
1008        message(WARNING "Nonexistent directory for ${name}: ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}")
1009      endif()
1010      # FIXME: It'd be redundant.
1011      set(${project}_${type}_${nameUPPER}_BUILD Off)
1012    endif()
1013  endif()
1014endmacro()
1015
1016# Add external project that may want to be built as part of llvm such as Clang,
1017# lld, and Polly. This adds two options. One for the source directory of the
1018# project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to
1019# enable or disable building it with everything else.
1020# Additional parameter can be specified as the name of directory.
1021macro(add_llvm_external_project name)
1022  add_llvm_subdirectory(LLVM TOOL ${name} ${ARGN})
1023endmacro()
1024
1025macro(add_llvm_tool_subdirectory name)
1026  add_llvm_external_project(${name})
1027endmacro(add_llvm_tool_subdirectory)
1028
1029function(get_project_name_from_src_var var output)
1030  string(REGEX MATCH "LLVM_EXTERNAL_(.*)_SOURCE_DIR"
1031         MACHED_TOOL "${var}")
1032  if(MACHED_TOOL)
1033    set(${output} ${CMAKE_MATCH_1} PARENT_SCOPE)
1034  else()
1035    set(${output} PARENT_SCOPE)
1036  endif()
1037endfunction()
1038
1039function(create_subdirectory_options project type)
1040  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1041  foreach(dir ${sub-dirs})
1042    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1043      canonicalize_tool_name(${dir} name)
1044      option(${project}_${type}_${name}_BUILD
1045           "Whether to build ${name} as part of ${project}" On)
1046      mark_as_advanced(${project}_${type}_${name}_BUILD)
1047    endif()
1048  endforeach()
1049endfunction(create_subdirectory_options)
1050
1051function(create_llvm_tool_options)
1052  create_subdirectory_options(LLVM TOOL)
1053endfunction(create_llvm_tool_options)
1054
1055function(llvm_add_implicit_projects project)
1056  set(list_of_implicit_subdirs "")
1057  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
1058  foreach(dir ${sub-dirs})
1059    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
1060      canonicalize_tool_name(${dir} name)
1061      if (${project}_TOOL_${name}_BUILD)
1062        get_filename_component(fn "${dir}" NAME)
1063        list(APPEND list_of_implicit_subdirs "${fn}")
1064      endif()
1065    endif()
1066  endforeach()
1067
1068  foreach(external_proj ${list_of_implicit_subdirs})
1069    add_llvm_subdirectory(${project} TOOL "${external_proj}" ${ARGN})
1070  endforeach()
1071endfunction(llvm_add_implicit_projects)
1072
1073function(add_llvm_implicit_projects)
1074  llvm_add_implicit_projects(LLVM)
1075endfunction(add_llvm_implicit_projects)
1076
1077# Generic support for adding a unittest.
1078function(add_unittest test_suite test_name)
1079  if( NOT LLVM_BUILD_TESTS )
1080    set(EXCLUDE_FROM_ALL ON)
1081  endif()
1082
1083  # Our current version of gtest does not properly recognize C++11 support
1084  # with MSVC, so it falls back to tr1 / experimental classes.  Since LLVM
1085  # itself requires C++11, we can safely force it on unconditionally so that
1086  # we don't have to fight with the buggy gtest check.
1087  add_definitions(-DGTEST_LANG_CXX11=1)
1088  add_definitions(-DGTEST_HAS_TR1_TUPLE=0)
1089
1090  include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googletest/include)
1091  include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googlemock/include)
1092  if (NOT LLVM_ENABLE_THREADS)
1093    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_PTHREAD=0)
1094  endif ()
1095
1096  if (SUPPORTS_VARIADIC_MACROS_FLAG)
1097    list(APPEND LLVM_COMPILE_FLAGS "-Wno-variadic-macros")
1098  endif ()
1099  # Some parts of gtest rely on this GNU extension, don't warn on it.
1100  if(SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG)
1101    list(APPEND LLVM_COMPILE_FLAGS "-Wno-gnu-zero-variadic-macro-arguments")
1102  endif()
1103
1104  set(LLVM_REQUIRES_RTTI OFF)
1105
1106  list(APPEND LLVM_LINK_COMPONENTS Support) # gtest needs it for raw_ostream
1107  add_llvm_executable(${test_name} IGNORE_EXTERNALIZE_DEBUGINFO NO_INSTALL_RPATH ${ARGN})
1108  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
1109  set_output_directory(${test_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
1110  # libpthreads overrides some standard library symbols, so main
1111  # executable must be linked with it in order to provide consistent
1112  # API for all shared libaries loaded by this executable.
1113  target_link_libraries(${test_name} PRIVATE gtest_main gtest ${LLVM_PTHREAD_LIB})
1114
1115  add_dependencies(${test_suite} ${test_name})
1116  get_target_property(test_suite_folder ${test_suite} FOLDER)
1117  if (NOT ${test_suite_folder} STREQUAL "NOTFOUND")
1118    set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}")
1119  endif ()
1120endfunction()
1121
1122function(llvm_add_go_executable binary pkgpath)
1123  cmake_parse_arguments(ARG "ALL" "" "DEPENDS;GOFLAGS" ${ARGN})
1124
1125  if(LLVM_BINDINGS MATCHES "go")
1126    # FIXME: This should depend only on the libraries Go needs.
1127    get_property(llvmlibs GLOBAL PROPERTY LLVM_LIBS)
1128    set(binpath ${CMAKE_BINARY_DIR}/bin/${binary}${CMAKE_EXECUTABLE_SUFFIX})
1129    set(cc "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1130    set(cxx "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1131    set(cppflags "")
1132    get_property(include_dirs DIRECTORY PROPERTY INCLUDE_DIRECTORIES)
1133    foreach(d ${include_dirs})
1134      set(cppflags "${cppflags} -I${d}")
1135    endforeach(d)
1136    set(ldflags "${CMAKE_EXE_LINKER_FLAGS}")
1137    add_custom_command(OUTPUT ${binpath}
1138      COMMAND ${CMAKE_BINARY_DIR}/bin/llvm-go "go=${GO_EXECUTABLE}" "cc=${cc}" "cxx=${cxx}" "cppflags=${cppflags}" "ldflags=${ldflags}" "packages=${LLVM_GO_PACKAGES}"
1139              ${ARG_GOFLAGS} build -o ${binpath} ${pkgpath}
1140      DEPENDS llvm-config ${CMAKE_BINARY_DIR}/bin/llvm-go${CMAKE_EXECUTABLE_SUFFIX}
1141              ${llvmlibs} ${ARG_DEPENDS}
1142      COMMENT "Building Go executable ${binary}"
1143      VERBATIM)
1144    if (ARG_ALL)
1145      add_custom_target(${binary} ALL DEPENDS ${binpath})
1146    else()
1147      add_custom_target(${binary} DEPENDS ${binpath})
1148    endif()
1149  endif()
1150endfunction()
1151
1152# This function canonicalize the CMake variables passed by names
1153# from CMake boolean to 0/1 suitable for passing into Python or C++,
1154# in place.
1155function(llvm_canonicalize_cmake_booleans)
1156  foreach(var ${ARGN})
1157    if(${var})
1158      set(${var} 1 PARENT_SCOPE)
1159    else()
1160      set(${var} 0 PARENT_SCOPE)
1161    endif()
1162  endforeach()
1163endfunction(llvm_canonicalize_cmake_booleans)
1164
1165macro(set_llvm_build_mode)
1166  # Configuration-time: See Unit/lit.site.cfg.in
1167  if (CMAKE_CFG_INTDIR STREQUAL ".")
1168    set(LLVM_BUILD_MODE ".")
1169  else ()
1170    set(LLVM_BUILD_MODE "%(build_mode)s")
1171  endif ()
1172endmacro()
1173
1174# This function provides an automatic way to 'configure'-like generate a file
1175# based on a set of common and custom variables, specifically targeting the
1176# variables needed for the 'lit.site.cfg' files. This function bundles the
1177# common variables that any Lit instance is likely to need, and custom
1178# variables can be passed in.
1179function(configure_lit_site_cfg site_in site_out)
1180  cmake_parse_arguments(ARG "" "" "MAIN_CONFIG;OUTPUT_MAPPING" ${ARGN})
1181
1182  if ("${ARG_MAIN_CONFIG}" STREQUAL "")
1183    get_filename_component(INPUT_DIR ${site_in} DIRECTORY)
1184    set(ARG_MAIN_CONFIG "${INPUT_DIR}/lit.cfg")
1185  endif()
1186  if ("${ARG_OUTPUT_MAPPING}" STREQUAL "")
1187    set(ARG_OUTPUT_MAPPING "${site_out}")
1188  endif()
1189
1190  foreach(c ${LLVM_TARGETS_TO_BUILD})
1191    set(TARGETS_BUILT "${TARGETS_BUILT} ${c}")
1192  endforeach(c)
1193  set(TARGETS_TO_BUILD ${TARGETS_BUILT})
1194
1195  set(SHLIBEXT "${LTDL_SHLIB_EXT}")
1196
1197  set_llvm_build_mode()
1198
1199  # They below might not be the build tree but provided binary tree.
1200  set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
1201  set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
1202  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" LLVM_TOOLS_DIR "${LLVM_TOOLS_BINARY_DIR}")
1203  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_LIBS_DIR  "${LLVM_LIBRARY_DIR}")
1204
1205  # SHLIBDIR points the build tree.
1206  string(REPLACE "${CMAKE_CFG_INTDIR}" "${LLVM_BUILD_MODE}" SHLIBDIR "${LLVM_SHLIB_OUTPUT_INTDIR}")
1207
1208  set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE})
1209  # FIXME: "ENABLE_SHARED" doesn't make sense, since it is used just for
1210  # plugins. We may rename it.
1211  if(LLVM_ENABLE_PLUGINS)
1212    set(ENABLE_SHARED "1")
1213  else()
1214    set(ENABLE_SHARED "0")
1215  endif()
1216
1217  if(LLVM_ENABLE_ASSERTIONS AND NOT MSVC_IDE)
1218    set(ENABLE_ASSERTIONS "1")
1219  else()
1220    set(ENABLE_ASSERTIONS "0")
1221  endif()
1222
1223  set(HOST_OS ${CMAKE_SYSTEM_NAME})
1224  set(HOST_ARCH ${CMAKE_SYSTEM_PROCESSOR})
1225
1226  set(HOST_CC "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1227  set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1228  set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}")
1229
1230  set(LIT_SITE_CFG_IN_HEADER  "## Autogenerated from ${site_in}\n## Do not edit!")
1231
1232  # Override config_target_triple (and the env)
1233  if(LLVM_TARGET_TRIPLE_ENV)
1234    # This is expanded into the heading.
1235    string(CONCAT LIT_SITE_CFG_IN_HEADER "${LIT_SITE_CFG_IN_HEADER}\n\n"
1236      "import os\n"
1237      "target_env = \"${LLVM_TARGET_TRIPLE_ENV}\"\n"
1238      "config.target_triple = config.environment[target_env] = os.environ.get(target_env, \"${TARGET_TRIPLE}\")\n"
1239      )
1240
1241    # This is expanded to; config.target_triple = ""+config.target_triple+""
1242    set(TARGET_TRIPLE "\"+config.target_triple+\"")
1243  endif()
1244
1245  string(CONCAT LIT_SITE_CFG_IN_FOOTER
1246     "import lit.llvm\n"
1247     "lit.llvm.initialize(lit_config, config)\n")
1248
1249  configure_file(${site_in} ${site_out} @ONLY)
1250  if (EXISTS "${ARG_MAIN_CONFIG}")
1251    set(PYTHON_STATEMENT "map_config('${ARG_MAIN_CONFIG}', '${site_out}')")
1252    get_property(LLVM_LIT_CONFIG_MAP GLOBAL PROPERTY LLVM_LIT_CONFIG_MAP)
1253    set(LLVM_LIT_CONFIG_MAP "${LLVM_LIT_CONFIG_MAP}\n${PYTHON_STATEMENT}")
1254    set_property(GLOBAL PROPERTY LLVM_LIT_CONFIG_MAP ${LLVM_LIT_CONFIG_MAP})
1255  endif()
1256endfunction()
1257
1258function(dump_all_cmake_variables)
1259  get_cmake_property(_variableNames VARIABLES)
1260  foreach (_variableName ${_variableNames})
1261    message(STATUS "${_variableName}=${${_variableName}}")
1262  endforeach()
1263endfunction()
1264
1265function(get_llvm_lit_path base_dir file_name)
1266  cmake_parse_arguments(ARG "ALLOW_EXTERNAL" "" "" ${ARGN})
1267
1268  if (ARG_ALLOW_EXTERNAL)
1269    set(LLVM_DEFAULT_EXTERNAL_LIT "${LLVM_EXTERNAL_LIT}")
1270    set (LLVM_EXTERNAL_LIT "" CACHE STRING "Command used to spawn lit")
1271    if ("${LLVM_EXTERNAL_LIT}" STREQUAL "")
1272      set(LLVM_EXTERNAL_LIT "${LLVM_DEFAULT_EXTERNAL_LIT}")
1273    endif()
1274
1275    if (NOT "${LLVM_EXTERNAL_LIT}" STREQUAL "")
1276      if (EXISTS ${LLVM_EXTERNAL_LIT})
1277        get_filename_component(LIT_FILE_NAME ${LLVM_EXTERNAL_LIT} NAME)
1278        get_filename_component(LIT_BASE_DIR ${LLVM_EXTERNAL_LIT} DIRECTORY)
1279        set(${file_name} ${LIT_FILE_NAME} PARENT_SCOPE)
1280        set(${base_dir} ${LIT_BASE_DIR} PARENT_SCOPE)
1281        return()
1282      else()
1283        message(WARN "LLVM_EXTERNAL_LIT set to ${LLVM_EXTERNAL_LIT}, but the path does not exist.")
1284      endif()
1285    endif()
1286  endif()
1287
1288  set(lit_file_name "llvm-lit")
1289  if (CMAKE_HOST_WIN32 AND NOT CYGWIN)
1290    # llvm-lit needs suffix.py for multiprocess to find a main module.
1291    set(lit_file_name "${lit_file_name}.py")
1292  endif ()
1293  set(${file_name} ${lit_file_name} PARENT_SCOPE)
1294
1295  get_property(LLVM_LIT_BASE_DIR GLOBAL PROPERTY LLVM_LIT_BASE_DIR)
1296  if (NOT "${LLVM_LIT_BASE_DIR}" STREQUAL "")
1297    set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1298  endif()
1299
1300  # Allow individual projects to provide an override
1301  if (NOT "${LLVM_LIT_OUTPUT_DIR}" STREQUAL "")
1302    set(LLVM_LIT_BASE_DIR ${LLVM_LIT_OUTPUT_DIR})
1303  elseif(NOT "${LLVM_RUNTIME_OUTPUT_INTDIR}" STREQUAL "")
1304    set(LLVM_LIT_BASE_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR})
1305  else()
1306    set(LLVM_LIT_BASE_DIR "")
1307  endif()
1308
1309  # Cache this so we don't have to do it again and have subsequent calls
1310  # potentially disagree on the value.
1311  set_property(GLOBAL PROPERTY LLVM_LIT_BASE_DIR ${LLVM_LIT_BASE_DIR})
1312  set(${base_dir} ${LLVM_LIT_BASE_DIR} PARENT_SCOPE)
1313endfunction()
1314
1315# A raw function to create a lit target. This is used to implement the testuite
1316# management functions.
1317function(add_lit_target target comment)
1318  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1319  set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}")
1320  separate_arguments(LIT_ARGS)
1321  if (NOT CMAKE_CFG_INTDIR STREQUAL ".")
1322    list(APPEND LIT_ARGS --param build_mode=${CMAKE_CFG_INTDIR})
1323  endif ()
1324
1325  # Get the path to the lit to *run* tests with.  This can be overriden by
1326  # the user by specifying -DLLVM_EXTERNAL_LIT=<path-to-lit.py>
1327  get_llvm_lit_path(
1328    lit_base_dir
1329    lit_file_name
1330    ALLOW_EXTERNAL
1331    )
1332
1333  set(LIT_COMMAND "${PYTHON_EXECUTABLE};${lit_base_dir}/${lit_file_name}")
1334  list(APPEND LIT_COMMAND ${LIT_ARGS})
1335  foreach(param ${ARG_PARAMS})
1336    list(APPEND LIT_COMMAND --param ${param})
1337  endforeach()
1338  if (ARG_UNPARSED_ARGUMENTS)
1339    add_custom_target(${target}
1340      COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS}
1341      COMMENT "${comment}"
1342      USES_TERMINAL
1343      )
1344  else()
1345    add_custom_target(${target}
1346      COMMAND ${CMAKE_COMMAND} -E echo "${target} does nothing, no tools built.")
1347    message(STATUS "${target} does nothing.")
1348  endif()
1349  if (ARG_DEPENDS)
1350    add_dependencies(${target} ${ARG_DEPENDS})
1351  endif()
1352
1353  # Tests should be excluded from "Build Solution".
1354  set_target_properties(${target} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON)
1355endfunction()
1356
1357# A function to add a set of lit test suites to be driven through 'check-*' targets.
1358function(add_lit_testsuite target comment)
1359  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1360
1361  # EXCLUDE_FROM_ALL excludes the test ${target} out of check-all.
1362  if(NOT EXCLUDE_FROM_ALL)
1363    # Register the testsuites, params and depends for the global check rule.
1364    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${ARG_UNPARSED_ARGUMENTS})
1365    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${ARG_PARAMS})
1366    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_DEPENDS ${ARG_DEPENDS})
1367    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${ARG_ARGS})
1368  endif()
1369
1370  # Produce a specific suffixed check rule.
1371  add_lit_target(${target} ${comment}
1372    ${ARG_UNPARSED_ARGUMENTS}
1373    PARAMS ${ARG_PARAMS}
1374    DEPENDS ${ARG_DEPENDS}
1375    ARGS ${ARG_ARGS}
1376    )
1377endfunction()
1378
1379function(add_lit_testsuites project directory)
1380  if (NOT CMAKE_CONFIGURATION_TYPES)
1381    cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1382
1383    # Search recursively for test directories by assuming anything not
1384    # in a directory called Inputs contains tests.
1385    file(GLOB_RECURSE to_process LIST_DIRECTORIES true ${directory}/*)
1386    foreach(lit_suite ${to_process})
1387      if(NOT IS_DIRECTORY ${lit_suite})
1388        continue()
1389      endif()
1390      string(FIND ${lit_suite} Inputs is_inputs)
1391      string(FIND ${lit_suite} Output is_output)
1392      if (NOT (is_inputs EQUAL -1 AND is_output EQUAL -1))
1393        continue()
1394      endif()
1395
1396      # Create a check- target for the directory.
1397      string(REPLACE ${directory} "" name_slash ${lit_suite})
1398      if (name_slash)
1399        string(REPLACE "/" "-" name_slash ${name_slash})
1400        string(REPLACE "\\" "-" name_dashes ${name_slash})
1401        string(TOLOWER "${project}${name_dashes}" name_var)
1402        add_lit_target("check-${name_var}" "Running lit suite ${lit_suite}"
1403          ${lit_suite}
1404          PARAMS ${ARG_PARAMS}
1405          DEPENDS ${ARG_DEPENDS}
1406          ARGS ${ARG_ARGS}
1407        )
1408      endif()
1409    endforeach()
1410  endif()
1411endfunction()
1412
1413function(llvm_install_library_symlink name dest type)
1414  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1415  foreach(path ${CMAKE_MODULE_PATH})
1416    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1417      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1418      break()
1419    endif()
1420  endforeach()
1421
1422  set(component ${ARG_COMPONENT})
1423  if(NOT component)
1424    set(component ${name})
1425  endif()
1426
1427  set(full_name ${CMAKE_${type}_LIBRARY_PREFIX}${name}${CMAKE_${type}_LIBRARY_SUFFIX})
1428  set(full_dest ${CMAKE_${type}_LIBRARY_PREFIX}${dest}${CMAKE_${type}_LIBRARY_SUFFIX})
1429
1430  set(output_dir lib${LLVM_LIBDIR_SUFFIX})
1431  if(WIN32 AND "${type}" STREQUAL "SHARED")
1432    set(output_dir bin)
1433  endif()
1434
1435  install(SCRIPT ${INSTALL_SYMLINK}
1436          CODE "install_symlink(${full_name} ${full_dest} ${output_dir})"
1437          COMPONENT ${component})
1438
1439  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1440    add_llvm_install_targets(install-${name}
1441                             DEPENDS ${name} ${dest} install-${dest}
1442                             COMPONENT ${name})
1443  endif()
1444endfunction()
1445
1446function(llvm_install_symlink name dest)
1447  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1448  foreach(path ${CMAKE_MODULE_PATH})
1449    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1450      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1451      break()
1452    endif()
1453  endforeach()
1454
1455  if(ARG_COMPONENT)
1456    set(component ${ARG_COMPONENT})
1457  else()
1458    if(ARG_ALWAYS_GENERATE)
1459      set(component ${dest})
1460    else()
1461      set(component ${name})
1462    endif()
1463  endif()
1464
1465  set(full_name ${name}${CMAKE_EXECUTABLE_SUFFIX})
1466  set(full_dest ${dest}${CMAKE_EXECUTABLE_SUFFIX})
1467
1468  install(SCRIPT ${INSTALL_SYMLINK}
1469          CODE "install_symlink(${full_name} ${full_dest} ${LLVM_TOOLS_INSTALL_DIR})"
1470          COMPONENT ${component})
1471
1472  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1473    add_llvm_install_targets(install-${name}
1474                             DEPENDS ${name} ${dest} install-${dest}
1475                             COMPONENT ${name})
1476  endif()
1477endfunction()
1478
1479function(add_llvm_tool_symlink link_name target)
1480  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "OUTPUT_DIR" "" ${ARGN})
1481  set(dest_binary "$<TARGET_FILE:${target}>")
1482
1483  # This got a bit gross... For multi-configuration generators the target
1484  # properties return the resolved value of the string, not the build system
1485  # expression. To reconstruct the platform-agnostic path we have to do some
1486  # magic. First we grab one of the types, and a type-specific path. Then from
1487  # the type-specific path we find the last occurrence of the type in the path,
1488  # and replace it with CMAKE_CFG_INTDIR. This allows the build step to be type
1489  # agnostic again.
1490  if(NOT ARG_OUTPUT_DIR)
1491    # If you're not overriding the OUTPUT_DIR, we can make the link relative in
1492    # the same directory.
1493    if(CMAKE_HOST_UNIX)
1494      set(dest_binary "$<TARGET_FILE_NAME:${target}>")
1495    endif()
1496    if(CMAKE_CONFIGURATION_TYPES)
1497      list(GET CMAKE_CONFIGURATION_TYPES 0 first_type)
1498      string(TOUPPER ${first_type} first_type_upper)
1499      set(first_type_suffix _${first_type_upper})
1500    endif()
1501    get_target_property(target_type ${target} TYPE)
1502    if(${target_type} STREQUAL "STATIC_LIBRARY")
1503      get_target_property(ARG_OUTPUT_DIR ${target} ARCHIVE_OUTPUT_DIRECTORY${first_type_suffix})
1504    elseif(UNIX AND ${target_type} STREQUAL "SHARED_LIBRARY")
1505      get_target_property(ARG_OUTPUT_DIR ${target} LIBRARY_OUTPUT_DIRECTORY${first_type_suffix})
1506    else()
1507      get_target_property(ARG_OUTPUT_DIR ${target} RUNTIME_OUTPUT_DIRECTORY${first_type_suffix})
1508    endif()
1509    if(CMAKE_CONFIGURATION_TYPES)
1510      string(FIND "${ARG_OUTPUT_DIR}" "/${first_type}/" type_start REVERSE)
1511      string(SUBSTRING "${ARG_OUTPUT_DIR}" 0 ${type_start} path_prefix)
1512      string(SUBSTRING "${ARG_OUTPUT_DIR}" ${type_start} -1 path_suffix)
1513      string(REPLACE "/${first_type}/" "/${CMAKE_CFG_INTDIR}/"
1514             path_suffix ${path_suffix})
1515      set(ARG_OUTPUT_DIR ${path_prefix}${path_suffix})
1516    endif()
1517  endif()
1518
1519  if(CMAKE_HOST_UNIX)
1520    set(LLVM_LINK_OR_COPY create_symlink)
1521  else()
1522    set(LLVM_LINK_OR_COPY copy)
1523  endif()
1524
1525  set(output_path "${ARG_OUTPUT_DIR}/${link_name}${CMAKE_EXECUTABLE_SUFFIX}")
1526
1527  set(target_name ${link_name})
1528  if(TARGET ${link_name})
1529    set(target_name ${link_name}-link)
1530  endif()
1531
1532
1533  if(ARG_ALWAYS_GENERATE)
1534    set_property(DIRECTORY APPEND PROPERTY
1535      ADDITIONAL_MAKE_CLEAN_FILES ${dest_binary})
1536    add_custom_command(TARGET ${target} POST_BUILD
1537      COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}")
1538  else()
1539    add_custom_command(OUTPUT ${output_path}
1540                     COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}"
1541                     DEPENDS ${target})
1542    add_custom_target(${target_name} ALL DEPENDS ${target} ${output_path})
1543    set_target_properties(${target_name} PROPERTIES FOLDER Tools)
1544
1545    # Make sure both the link and target are toolchain tools
1546    if (${link_name} IN_LIST LLVM_TOOLCHAIN_TOOLS AND ${target} IN_LIST LLVM_TOOLCHAIN_TOOLS)
1547      set(TOOL_IS_TOOLCHAIN ON)
1548    endif()
1549
1550    if ((TOOL_IS_TOOLCHAIN OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY) AND LLVM_BUILD_TOOLS)
1551      llvm_install_symlink(${link_name} ${target})
1552    endif()
1553  endif()
1554endfunction()
1555
1556function(llvm_externalize_debuginfo name)
1557  if(NOT LLVM_EXTERNALIZE_DEBUGINFO)
1558    return()
1559  endif()
1560
1561  if(NOT LLVM_EXTERNALIZE_DEBUGINFO_SKIP_STRIP)
1562    if(APPLE)
1563      if(NOT CMAKE_STRIP)
1564        set(CMAKE_STRIP xcrun strip)
1565      endif()
1566      set(strip_command COMMAND ${CMAKE_STRIP} -Sxl $<TARGET_FILE:${name}>)
1567    else()
1568      set(strip_command COMMAND ${CMAKE_STRIP} -gx $<TARGET_FILE:${name}>)
1569    endif()
1570  endif()
1571
1572  if(APPLE)
1573    if(CMAKE_CXX_FLAGS MATCHES "-flto"
1574      OR CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE} MATCHES "-flto")
1575
1576      set(lto_object ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${name}-lto.o)
1577      set_property(TARGET ${name} APPEND_STRING PROPERTY
1578        LINK_FLAGS " -Wl,-object_path_lto,${lto_object}")
1579    endif()
1580    if(NOT CMAKE_DSYMUTIL)
1581      set(CMAKE_DSYMUTIL xcrun dsymutil)
1582    endif()
1583    add_custom_command(TARGET ${name} POST_BUILD
1584      COMMAND ${CMAKE_DSYMUTIL} $<TARGET_FILE:${name}>
1585      ${strip_command}
1586      )
1587  else()
1588    add_custom_command(TARGET ${name} POST_BUILD
1589      COMMAND ${CMAKE_OBJCOPY} --only-keep-debug $<TARGET_FILE:${name}> $<TARGET_FILE:${name}>.debug
1590      ${strip_command} -R .gnu_debuglink
1591      COMMAND ${CMAKE_OBJCOPY} --add-gnu-debuglink=$<TARGET_FILE:${name}>.debug $<TARGET_FILE:${name}>
1592      )
1593  endif()
1594endfunction()
1595
1596function(llvm_codesign name)
1597  if(NOT LLVM_CODESIGNING_IDENTITY)
1598    return()
1599  endif()
1600
1601  if(APPLE)
1602    if(NOT CMAKE_CODESIGN)
1603      set(CMAKE_CODESIGN xcrun codesign)
1604    endif()
1605    if(NOT CMAKE_CODESIGN_ALLOCATE)
1606      execute_process(
1607        COMMAND xcrun -f codesign_allocate
1608        OUTPUT_STRIP_TRAILING_WHITESPACE
1609        OUTPUT_VARIABLE CMAKE_CODESIGN_ALLOCATE
1610      )
1611    endif()
1612    add_custom_command(
1613      TARGET ${name} POST_BUILD
1614      COMMAND ${CMAKE_COMMAND} -E
1615              env CODESIGN_ALLOCATE=${CMAKE_CODESIGN_ALLOCATE}
1616              ${CMAKE_CODESIGN} -s ${LLVM_CODESIGNING_IDENTITY}
1617              $<TARGET_FILE:${name}>
1618    )
1619  endif()
1620endfunction()
1621
1622function(llvm_setup_rpath name)
1623  if(CMAKE_INSTALL_RPATH)
1624    return()
1625  endif()
1626
1627  if(LLVM_INSTALL_PREFIX AND NOT (LLVM_INSTALL_PREFIX STREQUAL CMAKE_INSTALL_PREFIX))
1628    set(extra_libdir ${LLVM_LIBRARY_DIR})
1629  elseif(LLVM_BUILD_LIBRARY_DIR)
1630    set(extra_libdir ${LLVM_LIBRARY_DIR})
1631  endif()
1632
1633  if (APPLE)
1634    set(_install_name_dir INSTALL_NAME_DIR "@rpath")
1635    set(_install_rpath "@loader_path/../lib" ${extra_libdir})
1636  elseif(UNIX)
1637    set(_install_rpath "\$ORIGIN/../lib${LLVM_LIBDIR_SUFFIX}" ${extra_libdir})
1638    if(${CMAKE_SYSTEM_NAME} MATCHES "(FreeBSD|DragonFly)")
1639      set_property(TARGET ${name} APPEND_STRING PROPERTY
1640                   LINK_FLAGS " -Wl,-z,origin ")
1641    endif()
1642    if(LLVM_LINKER_IS_GNULD)
1643      # $ORIGIN is not interpreted at link time by ld.bfd
1644      set_property(TARGET ${name} APPEND_STRING PROPERTY
1645                   LINK_FLAGS " -Wl,-rpath-link,${LLVM_LIBRARY_OUTPUT_INTDIR} ")
1646    endif()
1647  else()
1648    return()
1649  endif()
1650
1651  set_target_properties(${name} PROPERTIES
1652                        BUILD_WITH_INSTALL_RPATH On
1653                        INSTALL_RPATH "${_install_rpath}"
1654                        ${_install_name_dir})
1655endfunction()
1656
1657function(setup_dependency_debugging name)
1658  if(NOT LLVM_DEPENDENCY_DEBUGGING)
1659    return()
1660  endif()
1661
1662  if("intrinsics_gen" IN_LIST ARGN)
1663    return()
1664  endif()
1665
1666  set(deny_attributes_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Attributes.inc\"))")
1667  set(deny_intrinsics_inc "(deny file* (literal \"${LLVM_BINARY_DIR}/include/llvm/IR/Intrinsics.inc\"))")
1668
1669  set(sandbox_command "sandbox-exec -p '(version 1) (allow default) ${deny_attributes_inc} ${deny_intrinsics_inc}'")
1670  set_target_properties(${name} PROPERTIES RULE_LAUNCH_COMPILE ${sandbox_command})
1671endfunction()
1672
1673# Figure out if we can track VC revisions.
1674function(find_first_existing_file out_var)
1675  foreach(file ${ARGN})
1676    if(EXISTS "${file}")
1677      set(${out_var} "${file}" PARENT_SCOPE)
1678      return()
1679    endif()
1680  endforeach()
1681endfunction()
1682
1683macro(find_first_existing_vc_file out_var path)
1684    find_program(git_executable NAMES git git.exe git.cmd)
1685    # Run from a subdirectory to force git to print an absolute path.
1686    execute_process(COMMAND ${git_executable} rev-parse --git-dir
1687      WORKING_DIRECTORY ${path}/cmake
1688      RESULT_VARIABLE git_result
1689      OUTPUT_VARIABLE git_dir
1690      ERROR_QUIET)
1691    if(git_result EQUAL 0)
1692      string(STRIP "${git_dir}" git_dir)
1693      set(${out_var} "${git_dir}/logs/HEAD")
1694      # some branchless cases (e.g. 'repo') may not yet have .git/logs/HEAD
1695      if (NOT EXISTS "${git_dir}/logs/HEAD")
1696        file(WRITE "${git_dir}/logs/HEAD" "")
1697      endif()
1698    else()
1699      find_first_existing_file(${out_var}
1700        "${path}/.svn/wc.db"   # SVN 1.7
1701        "${path}/.svn/entries" # SVN 1.6
1702      )
1703    endif()
1704endmacro()
1705