1include(ExternalProject)
2
3# llvm_ExternalProject_BuildCmd(out_var target)
4#   Utility function for constructing command lines for external project targets
5function(llvm_ExternalProject_BuildCmd out_var target bin_dir)
6  cmake_parse_arguments(ARG "" "CONFIGURATION" "" ${ARGN})
7  if(NOT ARG_CONFIGURATION)
8    set(ARG_CONFIGURATION "$<CONFIG>")
9  endif()
10  if (CMAKE_GENERATOR MATCHES "Make")
11    # Use special command for Makefiles to support parallelism.
12    set(${out_var} "$(MAKE)" "-C" "${bin_dir}" "${target}" PARENT_SCOPE)
13  else()
14    set(${out_var} ${CMAKE_COMMAND} --build ${bin_dir} --target ${target}
15                                    --config ${ARG_CONFIGURATION} PARENT_SCOPE)
16  endif()
17endfunction()
18
19# llvm_ExternalProject_Add(name source_dir ...
20#   USE_TOOLCHAIN
21#     Use just-built tools (see TOOLCHAIN_TOOLS)
22#   EXCLUDE_FROM_ALL
23#     Exclude this project from the all target
24#   NO_INSTALL
25#     Don't generate install targets for this project
26#   ALWAYS_CLEAN
27#     Always clean the sub-project before building
28#   CMAKE_ARGS arguments...
29#     Optional cmake arguments to pass when configuring the project
30#   TOOLCHAIN_TOOLS targets...
31#     Targets for toolchain tools (defaults to clang;lld)
32#   DEPENDS targets...
33#     Targets that this project depends on
34#   EXTRA_TARGETS targets...
35#     Extra targets in the subproject to generate targets for
36#   PASSTHROUGH_PREFIXES prefix...
37#     Extra variable prefixes (name is always included) to pass down
38#   STRIP_TOOL path
39#     Use provided strip tool instead of the default one.
40#   )
41function(llvm_ExternalProject_Add name source_dir)
42  cmake_parse_arguments(ARG
43    "USE_TOOLCHAIN;EXCLUDE_FROM_ALL;NO_INSTALL;ALWAYS_CLEAN"
44    "SOURCE_DIR"
45    "CMAKE_ARGS;TOOLCHAIN_TOOLS;RUNTIME_LIBRARIES;DEPENDS;EXTRA_TARGETS;PASSTHROUGH_PREFIXES;STRIP_TOOL"
46    ${ARGN})
47  canonicalize_tool_name(${name} nameCanon)
48
49  foreach(arg ${ARG_CMAKE_ARGS})
50    if(arg MATCHES "^-DCMAKE_SYSTEM_NAME=")
51      string(REGEX REPLACE "^-DCMAKE_SYSTEM_NAME=(.*)$" "\\1" _cmake_system_name "${arg}")
52    endif()
53  endforeach()
54
55  if(NOT ARG_TOOLCHAIN_TOOLS)
56    set(ARG_TOOLCHAIN_TOOLS clang lld llvm-ar llvm-ranlib llvm-nm llvm-objdump)
57    if(_cmake_system_name STREQUAL Darwin)
58      list(APPEND ARG_TOOLCHAIN_TOOLS llvm-libtool-darwin llvm-lipo)
59    elseif(_cmake_system_name STREQUAL Windows)
60      list(APPEND ARG_TOOLCHAIN_TOOLS llvm-lib)
61    else()
62      # TODO: These tools don't fully support Mach-O format yet.
63      list(APPEND ARG_TOOLCHAIN_TOOLS llvm-objcopy llvm-strip)
64    endif()
65  endif()
66  foreach(tool ${ARG_TOOLCHAIN_TOOLS})
67    if(TARGET ${tool})
68      list(APPEND TOOLCHAIN_TOOLS ${tool})
69
70      # $<TARGET_FILE:tgt> only works on add_executable or add_library targets
71      # The below logic mirrors cmake's own implementation
72      get_target_property(target_type "${tool}" TYPE)
73      if(NOT target_type STREQUAL "OBJECT_LIBRARY" AND
74         NOT target_type STREQUAL "UTILITY" AND
75         NOT target_type STREQUAL "GLOBAL_TARGET" AND
76         NOT target_type STREQUAL "INTERFACE_LIBRARY")
77        list(APPEND TOOLCHAIN_BINS $<TARGET_FILE:${tool}>)
78      endif()
79
80    endif()
81  endforeach()
82
83  if(NOT ARG_RUNTIME_LIBRARIES)
84    set(ARG_RUNTIME_LIBRARIES compiler-rt libcxx)
85  endif()
86  foreach(lib ${ARG_RUNTIME_LIBRARIES})
87    if(TARGET ${lib})
88      list(APPEND RUNTIME_LIBRARIES ${lib})
89    endif()
90  endforeach()
91
92  if(ARG_ALWAYS_CLEAN)
93    set(always_clean clean)
94  endif()
95
96  list(FIND TOOLCHAIN_TOOLS clang FOUND_CLANG)
97  if(FOUND_CLANG GREATER -1)
98    set(CLANG_IN_TOOLCHAIN On)
99  endif()
100
101  if(RUNTIME_LIBRARIES AND CLANG_IN_TOOLCHAIN)
102    list(APPEND TOOLCHAIN_BINS ${RUNTIME_LIBRARIES})
103  endif()
104
105  set(STAMP_DIR ${CMAKE_CURRENT_BINARY_DIR}/${name}-stamps/)
106  set(BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/${name}-bins/)
107
108  add_custom_target(${name}-clear
109    COMMAND ${CMAKE_COMMAND} -E remove_directory ${BINARY_DIR}
110    COMMAND ${CMAKE_COMMAND} -E remove_directory ${STAMP_DIR}
111    COMMENT "Clobbering ${name} build and stamp directories"
112    USES_TERMINAL
113    )
114
115  # Find all variables that start with a prefix and propagate them through
116  get_cmake_property(variableNames VARIABLES)
117
118  list(APPEND ARG_PASSTHROUGH_PREFIXES ${nameCanon})
119  foreach(prefix ${ARG_PASSTHROUGH_PREFIXES})
120    foreach(variableName ${variableNames})
121      if(variableName MATCHES "^${prefix}")
122        string(REPLACE ";" "|" value "${${variableName}}")
123        list(APPEND PASSTHROUGH_VARIABLES
124          -D${variableName}=${value})
125      endif()
126    endforeach()
127  endforeach()
128
129  if(ARG_USE_TOOLCHAIN AND NOT CMAKE_CROSSCOMPILING)
130    if(CLANG_IN_TOOLCHAIN)
131      if(_cmake_system_name STREQUAL Windows)
132        set(compiler_args -DCMAKE_C_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}
133                          -DCMAKE_CXX_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}
134                          -DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang-cl${CMAKE_EXECUTABLE_SUFFIX})
135      else()
136        set(compiler_args -DCMAKE_C_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang${CMAKE_EXECUTABLE_SUFFIX}
137                          -DCMAKE_CXX_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang++${CMAKE_EXECUTABLE_SUFFIX}
138                          -DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/clang${CMAKE_EXECUTABLE_SUFFIX})
139      endif()
140    endif()
141    if(lld IN_LIST TOOLCHAIN_TOOLS)
142      if(_cmake_system_name STREQUAL Windows)
143        list(APPEND compiler_args -DCMAKE_LINKER=${LLVM_RUNTIME_OUTPUT_INTDIR}/lld-link${CMAKE_EXECUTABLE_SUFFIX})
144      elseif(NOT _cmake_system_name STREQUAL Darwin)
145        list(APPEND compiler_args -DCMAKE_LINKER=${LLVM_RUNTIME_OUTPUT_INTDIR}/ld.lld${CMAKE_EXECUTABLE_SUFFIX})
146      endif()
147    endif()
148    if(llvm-ar IN_LIST TOOLCHAIN_TOOLS)
149      if(_cmake_system_name STREQUAL Windows)
150        list(APPEND compiler_args -DCMAKE_AR=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-lib${CMAKE_EXECUTABLE_SUFFIX})
151      else()
152        list(APPEND compiler_args -DCMAKE_AR=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-ar${CMAKE_EXECUTABLE_SUFFIX})
153      endif()
154    endif()
155    if(llvm-libtool-darwin IN_LIST TOOLCHAIN_TOOLS)
156      list(APPEND compiler_args -DCMAKE_LIBTOOL=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-libtool-darwin${CMAKE_EXECUTABLE_SUFFIX})
157    endif()
158    if(llvm-lipo IN_LIST TOOLCHAIN_TOOLS)
159      list(APPEND compiler_args -DCMAKE_LIPO=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-lipo${CMAKE_EXECUTABLE_SUFFIX})
160    endif()
161    if(llvm-ranlib IN_LIST TOOLCHAIN_TOOLS)
162      list(APPEND compiler_args -DCMAKE_RANLIB=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-ranlib${CMAKE_EXECUTABLE_SUFFIX})
163    endif()
164    if(llvm-nm IN_LIST TOOLCHAIN_TOOLS)
165      list(APPEND compiler_args -DCMAKE_NM=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-nm${CMAKE_EXECUTABLE_SUFFIX})
166    endif()
167    if(llvm-objdump IN_LIST TOOLCHAIN_TOOLS)
168      list(APPEND compiler_args -DCMAKE_OBJDUMP=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-objdump${CMAKE_EXECUTABLE_SUFFIX})
169    endif()
170    if(llvm-objcopy IN_LIST TOOLCHAIN_TOOLS)
171      list(APPEND compiler_args -DCMAKE_OBJCOPY=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-objcopy${CMAKE_EXECUTABLE_SUFFIX})
172    endif()
173    if(llvm-strip IN_LIST TOOLCHAIN_TOOLS AND NOT ARG_STRIP_TOOL)
174      list(APPEND compiler_args -DCMAKE_STRIP=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-strip${CMAKE_EXECUTABLE_SUFFIX})
175    endif()
176    list(APPEND ARG_DEPENDS ${TOOLCHAIN_TOOLS})
177  endif()
178
179  if(ARG_STRIP_TOOL)
180    list(APPEND compiler_args -DCMAKE_STRIP=${ARG_STRIP_TOOL})
181  endif()
182
183  add_custom_command(
184    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp
185    DEPENDS ${ARG_DEPENDS}
186    COMMAND ${CMAKE_COMMAND} -E touch ${BINARY_DIR}/CMakeCache.txt
187    COMMAND ${CMAKE_COMMAND} -E touch ${STAMP_DIR}/${name}-mkdir
188    COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp
189    COMMENT "Clobbering bootstrap build and stamp directories"
190    )
191
192  add_custom_target(${name}-clobber
193    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp)
194
195  if(ARG_EXCLUDE_FROM_ALL)
196    set(exclude EXCLUDE_FROM_ALL 1)
197  endif()
198
199  if(CMAKE_SYSROOT)
200    set(sysroot_arg -DCMAKE_SYSROOT=${CMAKE_SYSROOT})
201  endif()
202
203  if(CMAKE_CROSSCOMPILING)
204    set(compiler_args -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
205                      -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
206                      -DCMAKE_LINKER=${CMAKE_LINKER}
207                      -DCMAKE_AR=${CMAKE_AR}
208                      -DCMAKE_RANLIB=${CMAKE_RANLIB}
209                      -DCMAKE_NM=${CMAKE_NM}
210                      -DCMAKE_OBJCOPY=${CMAKE_OBJCOPY}
211                      -DCMAKE_OBJDUMP=${CMAKE_OBJDUMP}
212                      -DCMAKE_STRIP=${CMAKE_STRIP})
213    set(llvm_config_path ${LLVM_CONFIG_PATH})
214
215    if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
216      string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION
217             ${PACKAGE_VERSION})
218      set(resource_dir "${LLVM_LIBRARY_DIR}/clang/${CLANG_VERSION}")
219      set(flag_types ASM C CXX MODULE_LINKER SHARED_LINKER EXE_LINKER)
220      foreach(type ${flag_types})
221        set(${type}_flag -DCMAKE_${type}_FLAGS=-resource-dir=${resource_dir})
222      endforeach()
223      string(REPLACE ";" "|" flag_string "${flag_types}")
224      foreach(arg ${ARG_CMAKE_ARGS})
225        if(arg MATCHES "^-DCMAKE_(${flag_string})_FLAGS")
226          foreach(type ${flag_types})
227            if(arg MATCHES "^-DCMAKE_${type}_FLAGS")
228              string(REGEX REPLACE "^-DCMAKE_${type}_FLAGS=(.*)$" "\\1" flag_value "${arg}")
229              set(${type}_flag "${${type}_flag} ${flag_value}")
230            endif()
231          endforeach()
232        else()
233          list(APPEND cmake_args ${arg})
234        endif()
235      endforeach()
236      foreach(type ${flag_types})
237        list(APPEND cmake_args ${${type}_flag})
238      endforeach()
239    endif()
240  else()
241    set(llvm_config_path "$<TARGET_FILE:llvm-config>")
242    set(cmake_args ${ARG_CMAKE_ARGS})
243  endif()
244
245  ExternalProject_Add(${name}
246    DEPENDS ${ARG_DEPENDS} llvm-config
247    ${name}-clobber
248    PREFIX ${CMAKE_BINARY_DIR}/projects/${name}
249    SOURCE_DIR ${source_dir}
250    STAMP_DIR ${STAMP_DIR}
251    BINARY_DIR ${BINARY_DIR}
252    ${exclude}
253    CMAKE_ARGS ${${nameCanon}_CMAKE_ARGS}
254               ${compiler_args}
255               -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
256               ${sysroot_arg}
257               -DLLVM_BINARY_DIR=${PROJECT_BINARY_DIR}
258               -DLLVM_CONFIG_PATH=${llvm_config_path}
259               -DLLVM_ENABLE_WERROR=${LLVM_ENABLE_WERROR}
260               -DLLVM_HOST_TRIPLE=${LLVM_HOST_TRIPLE}
261               -DLLVM_HAVE_LINK_VERSION_SCRIPT=${LLVM_HAVE_LINK_VERSION_SCRIPT}
262               -DLLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO=${LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO}
263               -DLLVM_USE_RELATIVE_PATHS_IN_FILES=${LLVM_USE_RELATIVE_PATHS_IN_FILES}
264               -DLLVM_LIT_ARGS=${LLVM_LIT_ARGS}
265               -DLLVM_SOURCE_PREFIX=${LLVM_SOURCE_PREFIX}
266               -DPACKAGE_VERSION=${PACKAGE_VERSION}
267               -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
268               -DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
269               -DCMAKE_EXPORT_COMPILE_COMMANDS=1
270               ${cmake_args}
271               ${PASSTHROUGH_VARIABLES}
272    INSTALL_COMMAND ""
273    STEP_TARGETS configure build
274    BUILD_ALWAYS 1
275    USES_TERMINAL_CONFIGURE 1
276    USES_TERMINAL_BUILD 1
277    USES_TERMINAL_INSTALL 1
278    LIST_SEPARATOR |
279    )
280
281  if(ARG_USE_TOOLCHAIN)
282    set(force_deps DEPENDS ${TOOLCHAIN_BINS})
283  endif()
284
285  llvm_ExternalProject_BuildCmd(run_clean clean ${BINARY_DIR})
286  ExternalProject_Add_Step(${name} clean
287    COMMAND ${run_clean}
288    COMMENT "Cleaning ${name}..."
289    DEPENDEES configure
290    ${force_deps}
291    WORKING_DIRECTORY ${BINARY_DIR}
292    EXCLUDE_FROM_MAIN 1
293    USES_TERMINAL 1
294    )
295  ExternalProject_Add_StepTargets(${name} clean)
296
297  if(ARG_USE_TOOLCHAIN)
298    add_dependencies(${name}-clean ${name}-clobber)
299    set_target_properties(${name}-clean PROPERTIES
300      SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${name}-clobber-stamp)
301  endif()
302
303  if(NOT ARG_NO_INSTALL)
304    install(CODE "execute_process\(COMMAND \${CMAKE_COMMAND} -DCMAKE_INSTALL_PREFIX=\${CMAKE_INSTALL_PREFIX} -DCMAKE_INSTALL_DO_STRIP=\${CMAKE_INSTALL_DO_STRIP} -P ${BINARY_DIR}/cmake_install.cmake\)"
305      COMPONENT ${name})
306
307    add_llvm_install_targets(install-${name}
308                             DEPENDS ${name}
309                             COMPONENT ${name})
310  endif()
311
312  # Add top-level targets
313  foreach(target ${ARG_EXTRA_TARGETS})
314    if(DEFINED ${target})
315      set(external_target "${${target}}")
316    else()
317      set(external_target "${target}")
318    endif()
319    llvm_ExternalProject_BuildCmd(build_runtime_cmd ${external_target} ${BINARY_DIR})
320    add_custom_target(${target}
321      COMMAND ${build_runtime_cmd}
322      DEPENDS ${name}-configure
323      WORKING_DIRECTORY ${BINARY_DIR}
324      VERBATIM
325      USES_TERMINAL)
326  endforeach()
327endfunction()
328