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  else()
19    if(LLVM_COMPILER_IS_GCC_COMPATIBLE)
20      list(APPEND LLVM_COMPILE_FLAGS "-fno-exceptions")
21    elseif(MSVC)
22      list(APPEND LLVM_COMPILE_DEFINITIONS _HAS_EXCEPTIONS=0)
23      list(APPEND LLVM_COMPILE_FLAGS "/EHs-c-")
24    endif()
25  endif()
26
27  # LLVM_REQUIRES_RTTI is an internal flag that individual
28  # targets can use to force RTTI
29  set(LLVM_CONFIG_HAS_RTTI YES CACHE INTERNAL "")
30  if(NOT (LLVM_REQUIRES_RTTI OR LLVM_ENABLE_RTTI))
31    set(LLVM_CONFIG_HAS_RTTI NO CACHE INTERNAL "")
32    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_RTTI=0)
33    if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
34      list(APPEND LLVM_COMPILE_FLAGS "-fno-rtti")
35    elseif (MSVC)
36      list(APPEND LLVM_COMPILE_FLAGS "/GR-")
37    endif ()
38  endif()
39
40  # Assume that;
41  #   - LLVM_COMPILE_FLAGS is list.
42  #   - PROPERTY COMPILE_FLAGS is string.
43  string(REPLACE ";" " " target_compile_flags " ${LLVM_COMPILE_FLAGS}")
44
45  if(update_src_props)
46    foreach(fn ${sources})
47      get_filename_component(suf ${fn} EXT)
48      if("${suf}" STREQUAL ".cpp")
49        set_property(SOURCE ${fn} APPEND_STRING PROPERTY
50          COMPILE_FLAGS "${target_compile_flags}")
51      endif()
52    endforeach()
53  else()
54    # Update target props, since all sources are C++.
55    set_property(TARGET ${name} APPEND_STRING PROPERTY
56      COMPILE_FLAGS "${target_compile_flags}")
57  endif()
58
59  set_property(TARGET ${name} APPEND PROPERTY COMPILE_DEFINITIONS ${LLVM_COMPILE_DEFINITIONS})
60endfunction()
61
62function(add_llvm_symbol_exports target_name export_file)
63  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
64    set(native_export_file "${target_name}.exports")
65    add_custom_command(OUTPUT ${native_export_file}
66      COMMAND sed -e "s/^/_/" < ${export_file} > ${native_export_file}
67      DEPENDS ${export_file}
68      VERBATIM
69      COMMENT "Creating export file for ${target_name}")
70    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
71                 LINK_FLAGS " -Wl,-exported_symbols_list,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
72  elseif(LLVM_HAVE_LINK_VERSION_SCRIPT)
73    # Gold and BFD ld require a version script rather than a plain list.
74    set(native_export_file "${target_name}.exports")
75    # FIXME: Don't write the "local:" line on OpenBSD.
76    add_custom_command(OUTPUT ${native_export_file}
77      COMMAND echo "{" > ${native_export_file}
78      COMMAND grep -q "[[:alnum:]]" ${export_file} && echo "  global:" >> ${native_export_file} || :
79      COMMAND sed -e "s/$/;/" -e "s/^/    /" < ${export_file} >> ${native_export_file}
80      COMMAND echo "  local: *;" >> ${native_export_file}
81      COMMAND echo "};" >> ${native_export_file}
82      DEPENDS ${export_file}
83      VERBATIM
84      COMMENT "Creating export file for ${target_name}")
85    if (${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
86      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
87                   LINK_FLAGS "  -Wl,-M,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
88    else()
89      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
90                   LINK_FLAGS "  -Wl,--version-script,${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
91    endif()
92  else()
93    set(native_export_file "${target_name}.def")
94
95    add_custom_command(OUTPUT ${native_export_file}
96      COMMAND ${PYTHON_EXECUTABLE} -c "import sys;print(''.join(['EXPORTS\\n']+sys.stdin.readlines(),))"
97        < ${export_file} > ${native_export_file}
98      DEPENDS ${export_file}
99      VERBATIM
100      COMMENT "Creating export file for ${target_name}")
101    set(export_file_linker_flag "${CMAKE_CURRENT_BINARY_DIR}/${native_export_file}")
102    if(MSVC)
103      set(export_file_linker_flag "/DEF:\"${export_file_linker_flag}\"")
104    endif()
105    set_property(TARGET ${target_name} APPEND_STRING PROPERTY
106                 LINK_FLAGS " ${export_file_linker_flag}")
107  endif()
108
109  add_custom_target(${target_name}_exports DEPENDS ${native_export_file})
110  set_target_properties(${target_name}_exports PROPERTIES FOLDER "Misc")
111
112  get_property(srcs TARGET ${target_name} PROPERTY SOURCES)
113  foreach(src ${srcs})
114    get_filename_component(extension ${src} EXT)
115    if(extension STREQUAL ".cpp")
116      set(first_source_file ${src})
117      break()
118    endif()
119  endforeach()
120
121  # Force re-linking when the exports file changes. Actually, it
122  # forces recompilation of the source file. The LINK_DEPENDS target
123  # property only works for makefile-based generators.
124  # FIXME: This is not safe because this will create the same target
125  # ${native_export_file} in several different file:
126  # - One where we emitted ${target_name}_exports
127  # - One where we emitted the build command for the following object.
128  # set_property(SOURCE ${first_source_file} APPEND PROPERTY
129  #   OBJECT_DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${native_export_file})
130
131  set_property(DIRECTORY APPEND
132    PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${native_export_file})
133
134  add_dependencies(${target_name} ${target_name}_exports)
135
136  # Add dependency to *_exports later -- CMake issue 14747
137  list(APPEND LLVM_COMMON_DEPENDS ${target_name}_exports)
138  set(LLVM_COMMON_DEPENDS ${LLVM_COMMON_DEPENDS} PARENT_SCOPE)
139endfunction(add_llvm_symbol_exports)
140
141if(NOT WIN32 AND NOT APPLE)
142  execute_process(
143    COMMAND ${CMAKE_C_COMPILER} -Wl,--version
144    OUTPUT_VARIABLE stdout
145    ERROR_QUIET
146    )
147  if("${stdout}" MATCHES "GNU gold")
148    set(LLVM_LINKER_IS_GOLD ON)
149  endif()
150endif()
151
152function(add_link_opts target_name)
153  # Don't use linker optimizations in debug builds since it slows down the
154  # linker in a context where the optimizations are not important.
155  if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
156
157    # Pass -O3 to the linker. This enabled different optimizations on different
158    # linkers.
159    if(NOT (${CMAKE_SYSTEM_NAME} MATCHES "Darwin|SunOS" OR WIN32))
160      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
161                   LINK_FLAGS " -Wl,-O3")
162    endif()
163
164    if(LLVM_LINKER_IS_GOLD)
165      # With gold gc-sections is always safe.
166      set_property(TARGET ${target_name} APPEND_STRING PROPERTY
167                   LINK_FLAGS " -Wl,--gc-sections")
168      # Note that there is a bug with -Wl,--icf=safe so it is not safe
169      # to enable. See https://sourceware.org/bugzilla/show_bug.cgi?id=17704.
170    endif()
171
172    if(NOT LLVM_NO_DEAD_STRIP)
173      if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
174        # ld64's implementation of -dead_strip breaks tools that use plugins.
175        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
176                     LINK_FLAGS " -Wl,-dead_strip")
177      elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
178        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
179                     LINK_FLAGS " -Wl,-z -Wl,discard-unused=sections")
180      elseif(NOT WIN32 AND NOT LLVM_LINKER_IS_GOLD)
181        # Object files are compiled with -ffunction-data-sections.
182        # Versions of bfd ld < 2.23.1 have a bug in --gc-sections that breaks
183        # tools that use plugins. Always pass --gc-sections once we require
184        # a newer linker.
185        set_property(TARGET ${target_name} APPEND_STRING PROPERTY
186                     LINK_FLAGS " -Wl,--gc-sections")
187      endif()
188    endif()
189  endif()
190endfunction(add_link_opts)
191
192# Set each output directory according to ${CMAKE_CONFIGURATION_TYPES}.
193# Note: Don't set variables CMAKE_*_OUTPUT_DIRECTORY any more,
194# or a certain builder, for eaxample, msbuild.exe, would be confused.
195function(set_output_directory target)
196  cmake_parse_arguments(ARG "" "BINARY_DIR;LIBRARY_DIR" "" ${ARGN})
197
198  # module_dir -- corresponding to LIBRARY_OUTPUT_DIRECTORY.
199  # It affects output of add_library(MODULE).
200  if(WIN32 OR CYGWIN)
201    # DLL platform
202    set(module_dir ${ARG_BINARY_DIR})
203  else()
204    set(module_dir ${ARG_LIBRARY_DIR})
205  endif()
206  if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
207    foreach(build_mode ${CMAKE_CONFIGURATION_TYPES})
208      string(TOUPPER "${build_mode}" CONFIG_SUFFIX)
209      if(ARG_BINARY_DIR)
210        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} bi ${ARG_BINARY_DIR})
211        set_target_properties(${target} PROPERTIES "RUNTIME_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${bi})
212      endif()
213      if(ARG_LIBRARY_DIR)
214        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} li ${ARG_LIBRARY_DIR})
215        set_target_properties(${target} PROPERTIES "ARCHIVE_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${li})
216      endif()
217      if(module_dir)
218        string(REPLACE ${CMAKE_CFG_INTDIR} ${build_mode} mi ${module_dir})
219        set_target_properties(${target} PROPERTIES "LIBRARY_OUTPUT_DIRECTORY_${CONFIG_SUFFIX}" ${mi})
220      endif()
221    endforeach()
222  else()
223    if(ARG_BINARY_DIR)
224      set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${ARG_BINARY_DIR})
225    endif()
226    if(ARG_LIBRARY_DIR)
227      set_target_properties(${target} PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${ARG_LIBRARY_DIR})
228    endif()
229    if(module_dir)
230      set_target_properties(${target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${module_dir})
231    endif()
232  endif()
233endfunction()
234
235# If on Windows and building with MSVC, add the resource script containing the
236# VERSIONINFO data to the project.  This embeds version resource information
237# into the output .exe or .dll.
238# TODO: Enable for MinGW Windows builds too.
239#
240function(add_windows_version_resource_file OUT_VAR)
241  set(sources ${ARGN})
242  if (MSVC)
243    set(resource_file ${LLVM_SOURCE_DIR}/resources/windows_version_resource.rc)
244    if(EXISTS ${resource_file})
245      set(sources ${sources} ${resource_file})
246      source_group("Resource Files" ${resource_file})
247      set(windows_resource_file ${resource_file} PARENT_SCOPE)
248    endif()
249  endif(MSVC)
250
251  set(${OUT_VAR} ${sources} PARENT_SCOPE)
252endfunction(add_windows_version_resource_file)
253
254# set_windows_version_resource_properties(name resource_file...
255#   VERSION_MAJOR int
256#     Optional major version number (defaults to LLVM_VERSION_MAJOR)
257#   VERSION_MINOR int
258#     Optional minor version number (defaults to LLVM_VERSION_MINOR)
259#   VERSION_PATCHLEVEL int
260#     Optional patchlevel version number (defaults to LLVM_VERSION_PATCH)
261#   VERSION_STRING
262#     Optional version string (defaults to PACKAGE_VERSION)
263#   PRODUCT_NAME
264#     Optional product name string (defaults to "LLVM")
265#   )
266function(set_windows_version_resource_properties name resource_file)
267  cmake_parse_arguments(ARG
268    ""
269    "VERSION_MAJOR;VERSION_MINOR;VERSION_PATCHLEVEL;VERSION_STRING;PRODUCT_NAME"
270    ""
271    ${ARGN})
272
273  if (NOT DEFINED ARG_VERSION_MAJOR)
274    set(ARG_VERSION_MAJOR ${LLVM_VERSION_MAJOR})
275  endif()
276
277  if (NOT DEFINED ARG_VERSION_MINOR)
278    set(ARG_VERSION_MINOR ${LLVM_VERSION_MINOR})
279  endif()
280
281  if (NOT DEFINED ARG_VERSION_PATCHLEVEL)
282    set(ARG_VERSION_PATCHLEVEL ${LLVM_VERSION_PATCH})
283  endif()
284
285  if (NOT DEFINED ARG_VERSION_STRING)
286    set(ARG_VERSION_STRING ${PACKAGE_VERSION})
287  endif()
288
289  if (NOT DEFINED ARG_PRODUCT_NAME)
290    set(ARG_PRODUCT_NAME "LLVM")
291  endif()
292
293  set_property(SOURCE ${resource_file}
294               PROPERTY COMPILE_FLAGS /nologo)
295  set_property(SOURCE ${resource_file}
296               PROPERTY COMPILE_DEFINITIONS
297               "RC_VERSION_FIELD_1=${ARG_VERSION_MAJOR}"
298               "RC_VERSION_FIELD_2=${ARG_VERSION_MINOR}"
299               "RC_VERSION_FIELD_3=${ARG_VERSION_PATCHLEVEL}"
300               "RC_VERSION_FIELD_4=0"
301               "RC_FILE_VERSION=\"${ARG_VERSION_STRING}\""
302               "RC_INTERNAL_NAME=\"${name}\""
303               "RC_PRODUCT_NAME=\"${ARG_PRODUCT_NAME}\""
304               "RC_PRODUCT_VERSION=\"${ARG_VERSION_STRING}\"")
305endfunction(set_windows_version_resource_properties)
306
307# llvm_add_library(name sources...
308#   SHARED;STATIC
309#     STATIC by default w/o BUILD_SHARED_LIBS.
310#     SHARED by default w/  BUILD_SHARED_LIBS.
311#   OBJECT
312#     Also create an OBJECT library target. Default if STATIC && SHARED.
313#   MODULE
314#     Target ${name} might not be created on unsupported platforms.
315#     Check with "if(TARGET ${name})".
316#   DISABLE_LLVM_LINK_LLVM_DYLIB
317#     Do not link this library to libLLVM, even if
318#     LLVM_LINK_LLVM_DYLIB is enabled.
319#   OUTPUT_NAME name
320#     Corresponds to OUTPUT_NAME in target properties.
321#   DEPENDS targets...
322#     Same semantics as add_dependencies().
323#   LINK_COMPONENTS components...
324#     Same as the variable LLVM_LINK_COMPONENTS.
325#   LINK_LIBS lib_targets...
326#     Same semantics as target_link_libraries().
327#   ADDITIONAL_HEADERS
328#     May specify header files for IDE generators.
329#   SONAME
330#     Should set SONAME link flags and create symlinks
331#   PLUGIN_TOOL
332#     The tool (i.e. cmake target) that this plugin will link against
333#   )
334function(llvm_add_library name)
335  cmake_parse_arguments(ARG
336    "MODULE;SHARED;STATIC;OBJECT;DISABLE_LLVM_LINK_LLVM_DYLIB;SONAME"
337    "OUTPUT_NAME;PLUGIN_TOOL"
338    "ADDITIONAL_HEADERS;DEPENDS;LINK_COMPONENTS;LINK_LIBS;OBJLIBS"
339    ${ARGN})
340  list(APPEND LLVM_COMMON_DEPENDS ${ARG_DEPENDS})
341  if(ARG_ADDITIONAL_HEADERS)
342    # Pass through ADDITIONAL_HEADERS.
343    set(ARG_ADDITIONAL_HEADERS ADDITIONAL_HEADERS ${ARG_ADDITIONAL_HEADERS})
344  endif()
345  if(ARG_OBJLIBS)
346    set(ALL_FILES ${ARG_OBJLIBS})
347  else()
348    llvm_process_sources(ALL_FILES ${ARG_UNPARSED_ARGUMENTS} ${ARG_ADDITIONAL_HEADERS})
349  endif()
350
351  if(ARG_MODULE)
352    if(ARG_SHARED OR ARG_STATIC)
353      message(WARNING "MODULE with SHARED|STATIC doesn't make sense.")
354    endif()
355    # Plugins that link against a tool are allowed even when plugins in general are not
356    if(NOT LLVM_ENABLE_PLUGINS AND NOT (ARG_PLUGIN_TOOL AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS))
357      message(STATUS "${name} ignored -- Loadable modules not supported on this platform.")
358      return()
359    endif()
360  else()
361    if(ARG_PLUGIN_TOOL)
362      message(WARNING "PLUGIN_TOOL without MODULE doesn't make sense.")
363    endif()
364    if(BUILD_SHARED_LIBS AND NOT ARG_STATIC)
365      set(ARG_SHARED TRUE)
366    endif()
367    if(NOT ARG_SHARED)
368      set(ARG_STATIC TRUE)
369    endif()
370  endif()
371
372  # Generate objlib
373  if((ARG_SHARED AND ARG_STATIC) OR ARG_OBJECT)
374    # Generate an obj library for both targets.
375    set(obj_name "obj.${name}")
376    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
377      ${ALL_FILES}
378      )
379    llvm_update_compile_flags(${obj_name})
380    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
381
382    # Do add_dependencies(obj) later due to CMake issue 14747.
383    list(APPEND objlibs ${obj_name})
384
385    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
386  endif()
387
388  if(ARG_SHARED AND ARG_STATIC)
389    # static
390    set(name_static "${name}_static")
391    if(ARG_OUTPUT_NAME)
392      set(output_name OUTPUT_NAME "${ARG_OUTPUT_NAME}")
393    endif()
394    # DEPENDS has been appended to LLVM_COMMON_LIBS.
395    llvm_add_library(${name_static} STATIC
396      ${output_name}
397      OBJLIBS ${ALL_FILES} # objlib
398      LINK_LIBS ${ARG_LINK_LIBS}
399      LINK_COMPONENTS ${ARG_LINK_COMPONENTS}
400      )
401    # FIXME: Add name_static to anywhere in TARGET ${name}'s PROPERTY.
402    set(ARG_STATIC)
403  endif()
404
405  if(ARG_MODULE)
406    add_library(${name} MODULE ${ALL_FILES})
407  elseif(ARG_SHARED)
408    add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
409    add_library(${name} SHARED ${ALL_FILES})
410  else()
411    add_library(${name} STATIC ${ALL_FILES})
412  endif()
413
414  if(DEFINED windows_resource_file)
415    set_windows_version_resource_properties(${name} ${windows_resource_file})
416    set(windows_resource_file ${windows_resource_file} PARENT_SCOPE)
417  endif()
418
419  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
420  # $<TARGET_OBJECTS> doesn't require compile flags.
421  if(NOT obj_name)
422    llvm_update_compile_flags(${name})
423  endif()
424  add_link_opts( ${name} )
425  if(ARG_OUTPUT_NAME)
426    set_target_properties(${name}
427      PROPERTIES
428      OUTPUT_NAME ${ARG_OUTPUT_NAME}
429      )
430  endif()
431
432  if(ARG_MODULE)
433    set_target_properties(${name} PROPERTIES
434      PREFIX ""
435      SUFFIX ${LLVM_PLUGIN_EXT}
436      )
437  endif()
438
439  if(ARG_SHARED)
440    if(WIN32)
441      set_target_properties(${name} PROPERTIES
442        PREFIX ""
443        )
444    endif()
445  endif()
446
447  if(ARG_MODULE OR ARG_SHARED)
448    # Do not add -Dname_EXPORTS to the command-line when building files in this
449    # target. Doing so is actively harmful for the modules build because it
450    # creates extra module variants, and not useful because we don't use these
451    # macros.
452    set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
453
454    if (LLVM_EXPORTED_SYMBOL_FILE)
455      add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
456    endif()
457  endif()
458
459  if(ARG_SHARED AND UNIX)
460    if(NOT APPLE AND ARG_SONAME)
461      get_target_property(output_name ${name} OUTPUT_NAME)
462      if(${output_name} STREQUAL "output_name-NOTFOUND")
463        set(output_name ${name})
464      endif()
465      set(library_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}${LLVM_VERSION_SUFFIX})
466      set(api_name ${output_name}-${LLVM_VERSION_MAJOR}.${LLVM_VERSION_MINOR}.${LLVM_VERSION_PATCH}${LLVM_VERSION_SUFFIX})
467      set_target_properties(${name} PROPERTIES OUTPUT_NAME ${library_name})
468      llvm_install_library_symlink(${api_name} ${library_name} SHARED
469        COMPONENT ${name}
470        ALWAYS_GENERATE)
471      llvm_install_library_symlink(${output_name} ${library_name} SHARED
472        COMPONENT ${name}
473        ALWAYS_GENERATE)
474    endif()
475  endif()
476
477  if(ARG_MODULE AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS AND ARG_PLUGIN_TOOL AND (WIN32 OR CYGWIN))
478    # On DLL platforms symbols are imported from the tool by linking against it.
479    set(llvm_libs ${ARG_PLUGIN_TOOL})
480  elseif (DEFINED LLVM_LINK_COMPONENTS OR DEFINED ARG_LINK_COMPONENTS)
481    if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
482      set(llvm_libs LLVM)
483    else()
484      llvm_map_components_to_libnames(llvm_libs
485       ${ARG_LINK_COMPONENTS}
486       ${LLVM_LINK_COMPONENTS}
487       )
488    endif()
489  else()
490    # Components have not been defined explicitly in CMake, so add the
491    # dependency information for this library as defined by LLVMBuild.
492    #
493    # It would be nice to verify that we have the dependencies for this library
494    # name, but using get_property(... SET) doesn't suffice to determine if a
495    # property has been set to an empty value.
496    get_property(lib_deps GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_${name})
497  endif()
498
499  if(CMAKE_VERSION VERSION_LESS 2.8.12)
500    # Link libs w/o keywords, assuming PUBLIC.
501    target_link_libraries(${name}
502      ${ARG_LINK_LIBS}
503      ${lib_deps}
504      ${llvm_libs}
505      )
506  elseif(ARG_STATIC)
507    target_link_libraries(${name} INTERFACE
508      ${ARG_LINK_LIBS}
509      ${lib_deps}
510      ${llvm_libs}
511      )
512  else()
513    # We can use PRIVATE since SO knows its dependent libs.
514    target_link_libraries(${name} PRIVATE
515      ${ARG_LINK_LIBS}
516      ${lib_deps}
517      ${llvm_libs}
518      )
519  endif()
520
521  if(LLVM_COMMON_DEPENDS)
522    add_dependencies(${name} ${LLVM_COMMON_DEPENDS})
523    # Add dependencies also to objlibs.
524    # CMake issue 14747 --  add_dependencies() might be ignored to objlib's user.
525    foreach(objlib ${objlibs})
526      add_dependencies(${objlib} ${LLVM_COMMON_DEPENDS})
527    endforeach()
528  endif()
529
530  if(ARG_SHARED OR ARG_MODULE)
531    llvm_externalize_debuginfo(${name})
532  endif()
533endfunction()
534
535macro(add_llvm_library name)
536  cmake_parse_arguments(ARG
537    "SHARED"
538    ""
539    ""
540    ${ARGN})
541  if( BUILD_SHARED_LIBS )
542    llvm_add_library(${name} SHARED ${ARGN})
543  else()
544    llvm_add_library(${name} ${ARGN})
545  endif()
546  # The gtest libraries should not be installed or exported as a target
547  if ("${name}" STREQUAL gtest OR "${name}" STREQUAL gtest_main)
548    set(_is_gtest TRUE)
549  else()
550    set(_is_gtest FALSE)
551    set_property( GLOBAL APPEND PROPERTY LLVM_LIBS ${name} )
552  endif()
553
554  if( EXCLUDE_FROM_ALL )
555    set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
556  elseif(NOT _is_gtest)
557    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY OR ${name} STREQUAL "LTO")
558      set(install_dir lib${LLVM_LIBDIR_SUFFIX})
559      if(ARG_SHARED OR BUILD_SHARED_LIBS)
560        if(WIN32 OR CYGWIN OR MINGW)
561          set(install_type RUNTIME)
562          set(install_dir bin)
563        else()
564          set(install_type LIBRARY)
565        endif()
566      else()
567        set(install_type ARCHIVE)
568      endif()
569
570      install(TARGETS ${name}
571            EXPORT LLVMExports
572            ${install_type} DESTINATION ${install_dir}
573            COMPONENT ${name})
574
575      if (NOT CMAKE_CONFIGURATION_TYPES)
576        add_custom_target(install-${name}
577                          DEPENDS ${name}
578                          COMMAND "${CMAKE_COMMAND}"
579                                  -DCMAKE_INSTALL_COMPONENT=${name}
580                                  -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
581      endif()
582    endif()
583    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
584  endif()
585  set_target_properties(${name} PROPERTIES FOLDER "Libraries")
586endmacro(add_llvm_library name)
587
588macro(add_llvm_loadable_module name)
589  llvm_add_library(${name} MODULE ${ARGN})
590  if(NOT TARGET ${name})
591    # Add empty "phony" target
592    add_custom_target(${name})
593  else()
594    if( EXCLUDE_FROM_ALL )
595      set_target_properties( ${name} PROPERTIES EXCLUDE_FROM_ALL ON)
596    else()
597      if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
598        if(WIN32 OR CYGWIN)
599          # DLL platform
600          set(dlldir "bin")
601        else()
602          set(dlldir "lib${LLVM_LIBDIR_SUFFIX}")
603        endif()
604        install(TARGETS ${name}
605          EXPORT LLVMExports
606          LIBRARY DESTINATION ${dlldir}
607          ARCHIVE DESTINATION lib${LLVM_LIBDIR_SUFFIX})
608      endif()
609      set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
610    endif()
611  endif()
612
613  set_target_properties(${name} PROPERTIES FOLDER "Loadable modules")
614endmacro(add_llvm_loadable_module name)
615
616
617macro(add_llvm_executable name)
618  cmake_parse_arguments(ARG "DISABLE_LLVM_LINK_LLVM_DYLIB;IGNORE_EXTERNALIZE_DEBUGINFO" "" "" ${ARGN})
619  llvm_process_sources( ALL_FILES ${ARG_UNPARSED_ARGUMENTS} )
620
621  # Generate objlib
622  if(LLVM_ENABLE_OBJLIB)
623    # Generate an obj library for both targets.
624    set(obj_name "obj.${name}")
625    add_library(${obj_name} OBJECT EXCLUDE_FROM_ALL
626      ${ALL_FILES}
627      )
628    llvm_update_compile_flags(${obj_name})
629    set(ALL_FILES "$<TARGET_OBJECTS:${obj_name}>")
630
631    set_target_properties(${obj_name} PROPERTIES FOLDER "Object Libraries")
632  endif()
633
634  add_windows_version_resource_file(ALL_FILES ${ALL_FILES})
635
636  if(XCODE)
637    # Note: the dummy.cpp source file provides no definitions. However,
638    # it forces Xcode to properly link the static library.
639    list(APPEND ALL_FILES "${LLVM_MAIN_SRC_DIR}/cmake/dummy.cpp")
640  endif()
641
642  if( EXCLUDE_FROM_ALL )
643    add_executable(${name} EXCLUDE_FROM_ALL ${ALL_FILES})
644  else()
645    add_executable(${name} ${ALL_FILES})
646  endif()
647
648  if(DEFINED windows_resource_file)
649    set_windows_version_resource_properties(${name} ${windows_resource_file})
650  endif()
651
652  # $<TARGET_OBJECTS> doesn't require compile flags.
653  if(NOT LLVM_ENABLE_OBJLIB)
654    llvm_update_compile_flags(${name})
655  endif()
656  add_link_opts( ${name} )
657
658  # Do not add -Dname_EXPORTS to the command-line when building files in this
659  # target. Doing so is actively harmful for the modules build because it
660  # creates extra module variants, and not useful because we don't use these
661  # macros.
662  set_target_properties( ${name} PROPERTIES DEFINE_SYMBOL "" )
663
664  if (LLVM_EXPORTED_SYMBOL_FILE)
665    add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
666  endif(LLVM_EXPORTED_SYMBOL_FILE)
667
668  if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
669    set(USE_SHARED USE_SHARED)
670  endif()
671
672  set(EXCLUDE_FROM_ALL OFF)
673  set_output_directory(${name} BINARY_DIR ${LLVM_RUNTIME_OUTPUT_INTDIR} LIBRARY_DIR ${LLVM_LIBRARY_OUTPUT_INTDIR})
674  llvm_config( ${name} ${USE_SHARED} ${LLVM_LINK_COMPONENTS} )
675  if( LLVM_COMMON_DEPENDS )
676    add_dependencies( ${name} ${LLVM_COMMON_DEPENDS} )
677  endif( LLVM_COMMON_DEPENDS )
678
679  if(NOT ARG_IGNORE_EXTERNALIZE_DEBUGINFO)
680    llvm_externalize_debuginfo(${name})
681  endif()
682endmacro(add_llvm_executable name)
683
684function(export_executable_symbols target)
685  if (LLVM_EXPORTED_SYMBOL_FILE)
686    # The symbol file should contain the symbols we want the executable to
687    # export
688    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
689  elseif (LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
690    # Extract the symbols to export from the static libraries that the
691    # executable links against.
692    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
693    set(exported_symbol_file ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${target}.symbols)
694    # We need to consider not just the direct link dependencies, but also the
695    # transitive link dependencies. Do this by starting with the set of direct
696    # dependencies, then the dependencies of those dependencies, and so on.
697    get_target_property(new_libs ${target} LINK_LIBRARIES)
698    set(link_libs ${new_libs})
699    while(NOT "${new_libs}" STREQUAL "")
700      foreach(lib ${new_libs})
701        get_target_property(lib_type ${lib} TYPE)
702        if("${lib_type}" STREQUAL "STATIC_LIBRARY")
703          list(APPEND static_libs ${lib})
704        else()
705          list(APPEND other_libs ${lib})
706        endif()
707        get_target_property(transitive_libs ${lib} INTERFACE_LINK_LIBRARIES)
708        foreach(transitive_lib ${transitive_libs})
709          list(FIND link_libs ${transitive_lib} idx)
710          if(TARGET ${transitive_lib} AND idx EQUAL -1)
711            list(APPEND newer_libs ${transitive_lib})
712            list(APPEND link_libs ${transitive_lib})
713          endif()
714        endforeach(transitive_lib)
715      endforeach(lib)
716      set(new_libs ${newer_libs})
717      set(newer_libs "")
718    endwhile()
719    if (MSVC)
720      set(mangling microsoft)
721    else()
722      set(mangling itanium)
723    endif()
724    add_custom_command(OUTPUT ${exported_symbol_file}
725                       COMMAND ${PYTHON_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py --mangling=${mangling} ${static_libs} -o ${exported_symbol_file}
726                       WORKING_DIRECTORY ${LLVM_LIBRARY_OUTPUT_INTDIR}
727                       DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/extract_symbols.py ${static_libs}
728                       VERBATIM
729                       COMMENT "Generating export list for ${target}")
730    add_llvm_symbol_exports( ${target} ${exported_symbol_file} )
731    # If something links against this executable then we want a
732    # transitive link against only the libraries whose symbols
733    # we aren't exporting.
734    set_target_properties(${target} PROPERTIES INTERFACE_LINK_LIBRARIES "${other_libs}")
735    # The default import library suffix that cmake uses for cygwin/mingw is
736    # ".dll.a", but for clang.exe that causes a collision with libclang.dll,
737    # where the import libraries of both get named libclang.dll.a. Use a suffix
738    # of ".exe.a" to avoid this.
739    if(CYGWIN OR MINGW)
740      set_target_properties(${target} PROPERTIES IMPORT_SUFFIX ".exe.a")
741    endif()
742  elseif(NOT (WIN32 OR CYGWIN))
743    # On Windows auto-exporting everything doesn't work because of the limit on
744    # the size of the exported symbol table, but on other platforms we can do
745    # it without any trouble.
746    set_target_properties(${target} PROPERTIES ENABLE_EXPORTS 1)
747    if (APPLE)
748      set_property(TARGET ${target} APPEND_STRING PROPERTY
749        LINK_FLAGS " -rdynamic")
750    endif()
751  endif()
752endfunction()
753
754if(NOT LLVM_TOOLCHAIN_TOOLS)
755  set (LLVM_TOOLCHAIN_TOOLS
756    llvm-ar
757    llvm-ranlib
758    llvm-lib
759    llvm-objdump
760    )
761endif()
762
763macro(add_llvm_tool name)
764  if( NOT LLVM_BUILD_TOOLS )
765    set(EXCLUDE_FROM_ALL ON)
766  endif()
767  add_llvm_executable(${name} ${ARGN})
768
769  list(FIND LLVM_TOOLCHAIN_TOOLS ${name} LLVM_IS_${name}_TOOLCHAIN_TOOL)
770  if (LLVM_IS_${name}_TOOLCHAIN_TOOL GREATER -1 OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
771    if( LLVM_BUILD_TOOLS )
772      install(TARGETS ${name}
773              EXPORT LLVMExports
774              RUNTIME DESTINATION bin
775              COMPONENT ${name})
776
777      if (NOT CMAKE_CONFIGURATION_TYPES)
778        add_custom_target(install-${name}
779                          DEPENDS ${name}
780                          COMMAND "${CMAKE_COMMAND}"
781                                  -DCMAKE_INSTALL_COMPONENT=${name}
782                                  -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
783      endif()
784    endif()
785  endif()
786  if( LLVM_BUILD_TOOLS )
787    set_property(GLOBAL APPEND PROPERTY LLVM_EXPORTS ${name})
788  endif()
789  set_target_properties(${name} PROPERTIES FOLDER "Tools")
790endmacro(add_llvm_tool name)
791
792
793macro(add_llvm_example name)
794  if( NOT LLVM_BUILD_EXAMPLES )
795    set(EXCLUDE_FROM_ALL ON)
796  endif()
797  add_llvm_executable(${name} ${ARGN})
798  if( LLVM_BUILD_EXAMPLES )
799    install(TARGETS ${name} RUNTIME DESTINATION examples)
800  endif()
801  set_target_properties(${name} PROPERTIES FOLDER "Examples")
802endmacro(add_llvm_example name)
803
804
805macro(add_llvm_utility name)
806  add_llvm_executable(${name} DISABLE_LLVM_LINK_LLVM_DYLIB ${ARGN})
807  set_target_properties(${name} PROPERTIES FOLDER "Utils")
808  if( LLVM_INSTALL_UTILS )
809    install (TARGETS ${name}
810      RUNTIME DESTINATION bin
811      COMPONENT ${name})
812    if (NOT CMAKE_CONFIGURATION_TYPES)
813      add_custom_target(install-${name}
814                        DEPENDS ${name}
815                        COMMAND "${CMAKE_COMMAND}"
816                                -DCMAKE_INSTALL_COMPONENT=${name}
817                                -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
818    endif()
819  endif()
820endmacro(add_llvm_utility name)
821
822
823macro(add_llvm_target target_name)
824  include_directories(BEFORE
825    ${CMAKE_CURRENT_BINARY_DIR}
826    ${CMAKE_CURRENT_SOURCE_DIR})
827  add_llvm_library(LLVM${target_name} ${ARGN})
828  set( CURRENT_LLVM_TARGET LLVM${target_name} )
829endmacro(add_llvm_target)
830
831function(canonicalize_tool_name name output)
832  string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" nameStrip ${name})
833  string(REPLACE "-" "_" nameUNDERSCORE ${nameStrip})
834  string(TOUPPER ${nameUNDERSCORE} nameUPPER)
835  set(${output} "${nameUPPER}" PARENT_SCOPE)
836endfunction(canonicalize_tool_name)
837
838# Custom add_subdirectory wrapper
839# Takes in a project name (i.e. LLVM), the subdirectory name, and an optional
840# path if it differs from the name.
841macro(add_llvm_subdirectory project type name)
842  set(add_llvm_external_dir "${ARGN}")
843  if("${add_llvm_external_dir}" STREQUAL "")
844    set(add_llvm_external_dir ${name})
845  endif()
846  canonicalize_tool_name(${name} nameUPPER)
847  if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir}/CMakeLists.txt)
848    # Treat it as in-tree subproject.
849    option(${project}_${type}_${nameUPPER}_BUILD
850           "Whether to build ${name} as part of ${project}" On)
851    mark_as_advanced(${project}_${type}_${name}_BUILD)
852    if(${project}_${type}_${nameUPPER}_BUILD)
853      add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/${add_llvm_external_dir} ${add_llvm_external_dir})
854      # Don't process it in add_llvm_implicit_projects().
855      set(${project}_${type}_${nameUPPER}_BUILD OFF)
856    endif()
857  else()
858    set(LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR
859      "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}"
860      CACHE PATH "Path to ${name} source directory")
861    set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT ON)
862    if(NOT LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR OR NOT EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
863      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
864    endif()
865    if("${LLVM_EXTERNAL_${nameUPPER}_BUILD}" STREQUAL "OFF")
866      set(${project}_${type}_${nameUPPER}_BUILD_DEFAULT OFF)
867    endif()
868    option(${project}_${type}_${nameUPPER}_BUILD
869      "Whether to build ${name} as part of LLVM"
870      ${${project}_${type}_${nameUPPER}_BUILD_DEFAULT})
871    if (${project}_${type}_${nameUPPER}_BUILD)
872      if(EXISTS ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR})
873        add_subdirectory(${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR} ${add_llvm_external_dir})
874      elseif(NOT "${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}" STREQUAL "")
875        message(WARNING "Nonexistent directory for ${name}: ${LLVM_EXTERNAL_${nameUPPER}_SOURCE_DIR}")
876      endif()
877      # FIXME: It'd be redundant.
878      set(${project}_${type}_${nameUPPER}_BUILD Off)
879    endif()
880  endif()
881endmacro()
882
883# Add external project that may want to be built as part of llvm such as Clang,
884# lld, and Polly. This adds two options. One for the source directory of the
885# project, which defaults to ${CMAKE_CURRENT_SOURCE_DIR}/${name}. Another to
886# enable or disable building it with everything else.
887# Additional parameter can be specified as the name of directory.
888macro(add_llvm_external_project name)
889  add_llvm_subdirectory(LLVM TOOL ${name} ${ARGN})
890endmacro()
891
892macro(add_llvm_tool_subdirectory name)
893  add_llvm_external_project(${name})
894endmacro(add_llvm_tool_subdirectory)
895
896function(get_project_name_from_src_var var output)
897  string(REGEX MATCH "LLVM_EXTERNAL_(.*)_SOURCE_DIR"
898         MACHED_TOOL "${var}")
899  if(MACHED_TOOL)
900    set(${output} ${CMAKE_MATCH_1} PARENT_SCOPE)
901  else()
902    set(${output} PARENT_SCOPE)
903  endif()
904endfunction()
905
906function(create_subdirectory_options project type)
907  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
908  foreach(dir ${sub-dirs})
909    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
910      canonicalize_tool_name(${dir} name)
911      option(${project}_${type}_${name}_BUILD
912           "Whether to build ${name} as part of ${project}" On)
913      mark_as_advanced(${project}_${type}_${name}_BUILD)
914    endif()
915  endforeach()
916endfunction(create_subdirectory_options)
917
918function(create_llvm_tool_options)
919  create_subdirectory_options(LLVM TOOL)
920endfunction(create_llvm_tool_options)
921
922function(llvm_add_implicit_projects project)
923  set(list_of_implicit_subdirs "")
924  file(GLOB sub-dirs "${CMAKE_CURRENT_SOURCE_DIR}/*")
925  foreach(dir ${sub-dirs})
926    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/CMakeLists.txt")
927      canonicalize_tool_name(${dir} name)
928      if (${project}_TOOL_${name}_BUILD)
929        get_filename_component(fn "${dir}" NAME)
930        list(APPEND list_of_implicit_subdirs "${fn}")
931      endif()
932    endif()
933  endforeach()
934
935  foreach(external_proj ${list_of_implicit_subdirs})
936    add_llvm_subdirectory(${project} TOOL "${external_proj}" ${ARGN})
937  endforeach()
938endfunction(llvm_add_implicit_projects)
939
940function(add_llvm_implicit_projects)
941  llvm_add_implicit_projects(LLVM)
942endfunction(add_llvm_implicit_projects)
943
944# Generic support for adding a unittest.
945function(add_unittest test_suite test_name)
946  if( NOT LLVM_BUILD_TESTS )
947    set(EXCLUDE_FROM_ALL ON)
948  endif()
949
950  include_directories(${LLVM_MAIN_SRC_DIR}/utils/unittest/googletest/include)
951  if (NOT LLVM_ENABLE_THREADS)
952    list(APPEND LLVM_COMPILE_DEFINITIONS GTEST_HAS_PTHREAD=0)
953  endif ()
954
955  if (SUPPORTS_NO_VARIADIC_MACROS_FLAG)
956    list(APPEND LLVM_COMPILE_FLAGS "-Wno-variadic-macros")
957  endif ()
958
959  set(LLVM_REQUIRES_RTTI OFF)
960
961  list(APPEND LLVM_LINK_COMPONENTS Support) # gtest needs it for raw_ostream
962  add_llvm_executable(${test_name} IGNORE_EXTERNALIZE_DEBUGINFO ${ARGN})
963  set(outdir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
964  set_output_directory(${test_name} BINARY_DIR ${outdir} LIBRARY_DIR ${outdir})
965  target_link_libraries(${test_name} gtest_main gtest)
966
967  add_dependencies(${test_suite} ${test_name})
968  get_target_property(test_suite_folder ${test_suite} FOLDER)
969  if (NOT ${test_suite_folder} STREQUAL "NOTFOUND")
970    set_property(TARGET ${test_name} PROPERTY FOLDER "${test_suite_folder}")
971  endif ()
972endfunction()
973
974function(llvm_add_go_executable binary pkgpath)
975  cmake_parse_arguments(ARG "ALL" "" "DEPENDS;GOFLAGS" ${ARGN})
976
977  if(LLVM_BINDINGS MATCHES "go")
978    # FIXME: This should depend only on the libraries Go needs.
979    get_property(llvmlibs GLOBAL PROPERTY LLVM_LIBS)
980    set(binpath ${CMAKE_BINARY_DIR}/bin/${binary}${CMAKE_EXECUTABLE_SUFFIX})
981    set(cc "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
982    set(cxx "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
983    set(cppflags "")
984    get_property(include_dirs DIRECTORY PROPERTY INCLUDE_DIRECTORIES)
985    foreach(d ${include_dirs})
986      set(cppflags "${cppflags} -I${d}")
987    endforeach(d)
988    set(ldflags "${CMAKE_EXE_LINKER_FLAGS}")
989    add_custom_command(OUTPUT ${binpath}
990      COMMAND ${CMAKE_BINARY_DIR}/bin/llvm-go "go=${GO_EXECUTABLE}" "cc=${cc}" "cxx=${cxx}" "cppflags=${cppflags}" "ldflags=${ldflags}"
991              ${ARG_GOFLAGS} build -o ${binpath} ${pkgpath}
992      DEPENDS llvm-config ${CMAKE_BINARY_DIR}/bin/llvm-go${CMAKE_EXECUTABLE_SUFFIX}
993              ${llvmlibs} ${ARG_DEPENDS}
994      COMMENT "Building Go executable ${binary}"
995      VERBATIM)
996    if (ARG_ALL)
997      add_custom_target(${binary} ALL DEPENDS ${binpath})
998    else()
999      add_custom_target(${binary} DEPENDS ${binpath})
1000    endif()
1001  endif()
1002endfunction()
1003
1004# This function provides an automatic way to 'configure'-like generate a file
1005# based on a set of common and custom variables, specifically targeting the
1006# variables needed for the 'lit.site.cfg' files. This function bundles the
1007# common variables that any Lit instance is likely to need, and custom
1008# variables can be passed in.
1009function(configure_lit_site_cfg input output)
1010  foreach(c ${LLVM_TARGETS_TO_BUILD})
1011    set(TARGETS_BUILT "${TARGETS_BUILT} ${c}")
1012  endforeach(c)
1013  set(TARGETS_TO_BUILD ${TARGETS_BUILT})
1014
1015  set(SHLIBEXT "${LTDL_SHLIB_EXT}")
1016
1017  # Configuration-time: See Unit/lit.site.cfg.in
1018  if (CMAKE_CFG_INTDIR STREQUAL ".")
1019    set(LLVM_BUILD_MODE ".")
1020  else ()
1021    set(LLVM_BUILD_MODE "%(build_mode)s")
1022  endif ()
1023
1024  # They below might not be the build tree but provided binary tree.
1025  set(LLVM_SOURCE_DIR ${LLVM_MAIN_SRC_DIR})
1026  set(LLVM_BINARY_DIR ${LLVM_BINARY_DIR})
1027  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_TOOLS_DIR ${LLVM_TOOLS_BINARY_DIR})
1028  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} LLVM_LIBS_DIR  ${LLVM_LIBRARY_DIR})
1029
1030  # SHLIBDIR points the build tree.
1031  string(REPLACE ${CMAKE_CFG_INTDIR} ${LLVM_BUILD_MODE} SHLIBDIR "${LLVM_SHLIB_OUTPUT_INTDIR}")
1032
1033  set(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE})
1034  # FIXME: "ENABLE_SHARED" doesn't make sense, since it is used just for
1035  # plugins. We may rename it.
1036  if(LLVM_ENABLE_PLUGINS)
1037    set(ENABLE_SHARED "1")
1038  else()
1039    set(ENABLE_SHARED "0")
1040  endif()
1041
1042  if(LLVM_ENABLE_ASSERTIONS AND NOT MSVC_IDE)
1043    set(ENABLE_ASSERTIONS "1")
1044  else()
1045    set(ENABLE_ASSERTIONS "0")
1046  endif()
1047
1048  set(HOST_OS ${CMAKE_SYSTEM_NAME})
1049  set(HOST_ARCH ${CMAKE_SYSTEM_PROCESSOR})
1050
1051  set(HOST_CC "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}")
1052  set(HOST_CXX "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}")
1053  set(HOST_LDFLAGS "${CMAKE_EXE_LINKER_FLAGS}")
1054
1055  set(LIT_SITE_CFG_IN_HEADER  "## Autogenerated from ${input}\n## Do not edit!")
1056
1057  configure_file(${input} ${output} @ONLY)
1058endfunction()
1059
1060# A raw function to create a lit target. This is used to implement the testuite
1061# management functions.
1062function(add_lit_target target comment)
1063  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1064  set(LIT_ARGS "${ARG_ARGS} ${LLVM_LIT_ARGS}")
1065  separate_arguments(LIT_ARGS)
1066  if (NOT CMAKE_CFG_INTDIR STREQUAL ".")
1067    list(APPEND LIT_ARGS --param build_mode=${CMAKE_CFG_INTDIR})
1068  endif ()
1069  if (LLVM_MAIN_SRC_DIR)
1070    set (LIT_COMMAND ${PYTHON_EXECUTABLE} ${LLVM_MAIN_SRC_DIR}/utils/lit/lit.py)
1071  else()
1072    find_program(LIT_COMMAND llvm-lit)
1073  endif ()
1074  list(APPEND LIT_COMMAND ${LIT_ARGS})
1075  foreach(param ${ARG_PARAMS})
1076    list(APPEND LIT_COMMAND --param ${param})
1077  endforeach()
1078  if (ARG_UNPARSED_ARGUMENTS)
1079    add_custom_target(${target}
1080      COMMAND ${LIT_COMMAND} ${ARG_UNPARSED_ARGUMENTS}
1081      COMMENT "${comment}"
1082      ${cmake_3_2_USES_TERMINAL}
1083      )
1084  else()
1085    add_custom_target(${target}
1086      COMMAND ${CMAKE_COMMAND} -E echo "${target} does nothing, no tools built.")
1087    message(STATUS "${target} does nothing.")
1088  endif()
1089  if (ARG_DEPENDS)
1090    add_dependencies(${target} ${ARG_DEPENDS})
1091  endif()
1092
1093  # Tests should be excluded from "Build Solution".
1094  set_target_properties(${target} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD ON)
1095endfunction()
1096
1097# A function to add a set of lit test suites to be driven through 'check-*' targets.
1098function(add_lit_testsuite target comment)
1099  cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1100
1101  # EXCLUDE_FROM_ALL excludes the test ${target} out of check-all.
1102  if(NOT EXCLUDE_FROM_ALL)
1103    # Register the testsuites, params and depends for the global check rule.
1104    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${ARG_UNPARSED_ARGUMENTS})
1105    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${ARG_PARAMS})
1106    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_DEPENDS ${ARG_DEPENDS})
1107    set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${ARG_ARGS})
1108  endif()
1109
1110  # Produce a specific suffixed check rule.
1111  add_lit_target(${target} ${comment}
1112    ${ARG_UNPARSED_ARGUMENTS}
1113    PARAMS ${ARG_PARAMS}
1114    DEPENDS ${ARG_DEPENDS}
1115    ARGS ${ARG_ARGS}
1116    )
1117endfunction()
1118
1119function(add_lit_testsuites project directory)
1120  if (NOT CMAKE_CONFIGURATION_TYPES)
1121    cmake_parse_arguments(ARG "" "" "PARAMS;DEPENDS;ARGS" ${ARGN})
1122
1123    # Search recursively for test directories by assuming anything not
1124    # in a directory called Inputs contains tests.
1125    set(lit_suites)
1126    file(GLOB to_process ${directory}/*)
1127    while(to_process)
1128      set(cur_to_process ${to_process})
1129      set(to_process)
1130      foreach(lit_suite ${cur_to_process})
1131        if(IS_DIRECTORY ${lit_suite})
1132          string(FIND ${lit_suite} Inputs is_inputs)
1133          if (is_inputs EQUAL -1)
1134            list(APPEND lit_suites "${lit_suite}")
1135            file(GLOB subdirs ${lit_suite}/*)
1136            list(APPEND to_process ${subdirs})
1137          endif()
1138        endif()
1139      endforeach()
1140    endwhile()
1141
1142    # Now create a check- target for each test directory.
1143    foreach(dir ${lit_suites})
1144      string(REPLACE ${directory} "" name_slash ${dir})
1145      if (name_slash)
1146        string(REPLACE "/" "-" name_slash ${name_slash})
1147        string(REPLACE "\\" "-" name_dashes ${name_slash})
1148        string(TOLOWER "${project}${name_dashes}" name_var)
1149        add_lit_target("check-${name_var}" "Running lit suite ${dir}"
1150          ${dir}
1151          PARAMS ${ARG_PARAMS}
1152          DEPENDS ${ARG_DEPENDS}
1153          ARGS ${ARG_ARGS}
1154        )
1155      endif()
1156    endforeach()
1157  endif()
1158endfunction()
1159
1160function(llvm_install_library_symlink name dest type)
1161  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "COMPONENT" "" ${ARGN})
1162  foreach(path ${CMAKE_MODULE_PATH})
1163    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1164      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1165      break()
1166    endif()
1167  endforeach()
1168
1169  set(component ${ARG_COMPONENT})
1170  if(NOT component)
1171    set(component ${name})
1172  endif()
1173
1174  set(full_name ${CMAKE_${type}_LIBRARY_PREFIX}${name}${CMAKE_${type}_LIBRARY_SUFFIX})
1175  set(full_dest ${CMAKE_${type}_LIBRARY_PREFIX}${dest}${CMAKE_${type}_LIBRARY_SUFFIX})
1176
1177  set(output_dir lib${LLVM_LIBDIR_SUFFIX})
1178  if(WIN32 AND "${type}" STREQUAL "SHARED")
1179    set(output_dir bin)
1180  endif()
1181
1182  install(SCRIPT ${INSTALL_SYMLINK}
1183          CODE "install_symlink(${full_name} ${full_dest} ${output_dir})"
1184          COMPONENT ${component})
1185
1186  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1187    add_custom_target(install-${name}
1188                      DEPENDS ${name} ${dest} install-${dest}
1189                      COMMAND "${CMAKE_COMMAND}"
1190                              -DCMAKE_INSTALL_COMPONENT=${name}
1191                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
1192  endif()
1193endfunction()
1194
1195function(llvm_install_symlink name dest)
1196  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "" "" ${ARGN})
1197  foreach(path ${CMAKE_MODULE_PATH})
1198    if(EXISTS ${path}/LLVMInstallSymlink.cmake)
1199      set(INSTALL_SYMLINK ${path}/LLVMInstallSymlink.cmake)
1200      break()
1201    endif()
1202  endforeach()
1203
1204  if(ARG_ALWAYS_GENERATE)
1205    set(component ${dest})
1206  else()
1207    set(component ${name})
1208  endif()
1209
1210  set(full_name ${name}${CMAKE_EXECUTABLE_SUFFIX})
1211  set(full_dest ${dest}${CMAKE_EXECUTABLE_SUFFIX})
1212
1213  install(SCRIPT ${INSTALL_SYMLINK}
1214          CODE "install_symlink(${full_name} ${full_dest} bin)"
1215          COMPONENT ${component})
1216
1217  if (NOT CMAKE_CONFIGURATION_TYPES AND NOT ARG_ALWAYS_GENERATE)
1218    add_custom_target(install-${name}
1219                      DEPENDS ${name} ${dest} install-${dest}
1220                      COMMAND "${CMAKE_COMMAND}"
1221                              -DCMAKE_INSTALL_COMPONENT=${name}
1222                              -P "${CMAKE_BINARY_DIR}/cmake_install.cmake")
1223  endif()
1224endfunction()
1225
1226function(add_llvm_tool_symlink name dest)
1227  cmake_parse_arguments(ARG "ALWAYS_GENERATE" "" "" ${ARGN})
1228  if(UNIX)
1229    set(LLVM_LINK_OR_COPY create_symlink)
1230    set(dest_binary "${dest}${CMAKE_EXECUTABLE_SUFFIX}")
1231  else()
1232    set(LLVM_LINK_OR_COPY copy)
1233    set(dest_binary "${LLVM_RUNTIME_OUTPUT_INTDIR}/${dest}${CMAKE_EXECUTABLE_SUFFIX}")
1234  endif()
1235
1236  set(output_path "${LLVM_RUNTIME_OUTPUT_INTDIR}/${name}${CMAKE_EXECUTABLE_SUFFIX}")
1237
1238  if(ARG_ALWAYS_GENERATE)
1239    set_property(DIRECTORY APPEND PROPERTY
1240      ADDITIONAL_MAKE_CLEAN_FILES ${dest_binary})
1241    add_custom_command(TARGET ${dest} POST_BUILD
1242      COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}")
1243  else()
1244    add_custom_command(OUTPUT ${output_path}
1245                     COMMAND ${CMAKE_COMMAND} -E ${LLVM_LINK_OR_COPY} "${dest_binary}" "${output_path}"
1246                     DEPENDS ${dest})
1247    add_custom_target(${name} ALL DEPENDS ${output_path})
1248    set_target_properties(${name} PROPERTIES FOLDER Tools)
1249
1250    # Make sure the parent tool is a toolchain tool, otherwise exclude this tool
1251    list(FIND LLVM_TOOLCHAIN_TOOLS ${dest} LLVM_IS_${dest}_TOOLCHAIN_TOOL)
1252    if (NOT LLVM_IS_${dest}_TOOLCHAIN_TOOL GREATER -1)
1253      set(LLVM_IS_${name}_TOOLCHAIN_TOOL ${LLVM_IS_${dest}_TOOLCHAIN_TOOL})
1254    else()
1255      list(FIND LLVM_TOOLCHAIN_TOOLS ${name} LLVM_IS_${name}_TOOLCHAIN_TOOL)
1256    endif()
1257
1258    # LLVM_IS_${name}_TOOLCHAIN_TOOL will only be greater than -1 if both this
1259    # tool and its parent tool are in LLVM_TOOLCHAIN_TOOLS
1260    if (LLVM_IS_${name}_TOOLCHAIN_TOOL GREATER -1 OR NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
1261      if( LLVM_BUILD_TOOLS )
1262        llvm_install_symlink(${name} ${dest})
1263      endif()
1264    endif()
1265  endif()
1266endfunction()
1267
1268function(llvm_externalize_debuginfo name)
1269  if(NOT LLVM_EXTERNALIZE_DEBUGINFO)
1270    return()
1271  endif()
1272
1273  if(NOT LLVM_EXTERNALIZE_DEBUGINFO_SKIP_STRIP)
1274    set(strip_command COMMAND xcrun strip -Sxl $<TARGET_FILE:${name}>)
1275  endif()
1276
1277  if(APPLE)
1278    if(CMAKE_CXX_FLAGS MATCHES "-flto"
1279      OR CMAKE_CXX_FLAGS_${uppercase_CMAKE_BUILD_TYPE} MATCHES "-flto")
1280
1281      set(lto_object ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${name}-lto.o)
1282      set_property(TARGET ${name} APPEND_STRING PROPERTY
1283        LINK_FLAGS " -Wl,-object_path_lto,${lto_object}")
1284    endif()
1285    add_custom_command(TARGET ${name} POST_BUILD
1286      COMMAND xcrun dsymutil $<TARGET_FILE:${name}>
1287      ${strip_command}
1288      )
1289  else()
1290    message(FATAL_ERROR "LLVM_EXTERNALIZE_DEBUGINFO isn't implemented for non-darwin platforms!")
1291  endif()
1292endfunction()
1293