1include(CMakeParseArguments)
2include(CompilerRTUtils)
3
4# On OS X SDKs can be installed anywhere on the base system and xcode-select can
5# set the default Xcode to use. This function finds the SDKs that are present in
6# the current Xcode.
7function(find_darwin_sdk_dir var sdk_name)
8  set(DARWIN_${sdk_name}_CACHED_SYSROOT "" CACHE STRING "Darwin SDK path for SDK ${sdk_name}.")
9  set(DARWIN_PREFER_PUBLIC_SDK OFF CACHE BOOL "Prefer Darwin public SDK, even when an internal SDK is present.")
10
11  if(DARWIN_${sdk_name}_CACHED_SYSROOT)
12    set(${var} ${DARWIN_${sdk_name}_CACHED_SYSROOT} PARENT_SCOPE)
13    return()
14  endif()
15  if(NOT DARWIN_PREFER_PUBLIC_SDK)
16    # Let's first try the internal SDK, otherwise use the public SDK.
17    execute_process(
18      COMMAND xcodebuild -version -sdk ${sdk_name}.internal Path
19      RESULT_VARIABLE result_process
20      OUTPUT_VARIABLE var_internal
21      OUTPUT_STRIP_TRAILING_WHITESPACE
22      ERROR_FILE /dev/null
23    )
24  endif()
25  if((NOT result_process EQUAL 0) OR "" STREQUAL "${var_internal}")
26    execute_process(
27      COMMAND xcodebuild -version -sdk ${sdk_name} Path
28      RESULT_VARIABLE result_process
29      OUTPUT_VARIABLE var_internal
30      OUTPUT_STRIP_TRAILING_WHITESPACE
31      ERROR_FILE /dev/null
32    )
33  else()
34    set(${var}_INTERNAL ${var_internal} PARENT_SCOPE)
35  endif()
36  if(result_process EQUAL 0)
37    set(${var} ${var_internal} PARENT_SCOPE)
38  endif()
39  set(DARWIN_${sdk_name}_CACHED_SYSROOT ${var_internal} CACHE STRING "Darwin SDK path for SDK ${sdk_name}." FORCE)
40endfunction()
41
42# There isn't a clear mapping of what architectures are supported with a given
43# target platform, but ld's version output does list the architectures it can
44# link for.
45function(darwin_get_toolchain_supported_archs output_var)
46  execute_process(
47    COMMAND "${CMAKE_LINKER}" -v
48    ERROR_VARIABLE LINKER_VERSION)
49
50  string(REGEX MATCH "configured to support archs: ([^\n]+)"
51         ARCHES_MATCHED "${LINKER_VERSION}")
52  if(ARCHES_MATCHED)
53    set(ARCHES "${CMAKE_MATCH_1}")
54    message(STATUS "Got ld supported ARCHES: ${ARCHES}")
55    string(REPLACE " " ";" ARCHES ${ARCHES})
56  else()
57    # If auto-detecting fails, fall back to a default set
58    message(WARNING "Detecting supported architectures from 'ld -v' failed. Returning default set.")
59    set(ARCHES "i386;x86_64;armv7;armv7s;arm64")
60  endif()
61
62  set(${output_var} ${ARCHES} PARENT_SCOPE)
63endfunction()
64
65# This function takes an OS and a list of architectures and identifies the
66# subset of the architectures list that the installed toolchain can target.
67function(darwin_test_archs os valid_archs)
68  if(${valid_archs})
69    message(STATUS "Using cached valid architectures for ${os}.")
70    return()
71  endif()
72
73  set(archs ${ARGN})
74  if(NOT TEST_COMPILE_ONLY)
75    message(STATUS "Finding valid architectures for ${os}...")
76    set(SIMPLE_C ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/src.c)
77    file(WRITE ${SIMPLE_C} "#include <stdio.h>\nint main() { printf(__FILE__); return 0; }\n")
78
79    set(os_linker_flags)
80    foreach(flag ${DARWIN_${os}_LINK_FLAGS})
81      set(os_linker_flags "${os_linker_flags} ${flag}")
82    endforeach()
83  endif()
84
85  # The simple program will build for x86_64h on the simulator because it is
86  # compatible with x86_64 libraries (mostly), but since x86_64h isn't actually
87  # a valid or useful architecture for the iOS simulator we should drop it.
88  if(${os} MATCHES "^(iossim|tvossim|watchossim)$")
89    list(REMOVE_ITEM archs "x86_64h")
90  endif()
91
92  set(working_archs)
93  foreach(arch ${archs})
94
95    set(arch_linker_flags "-arch ${arch} ${os_linker_flags}")
96    if(TEST_COMPILE_ONLY)
97      try_compile_only(CAN_TARGET_${os}_${arch} FLAGS -v -arch ${arch} ${DARWIN_${os}_CFLAGS})
98    else()
99      set(SAVED_CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS})
100      set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${arch_linker_flags}")
101      try_compile(CAN_TARGET_${os}_${arch} ${CMAKE_BINARY_DIR} ${SIMPLE_C}
102                  COMPILE_DEFINITIONS "-v -arch ${arch}" ${DARWIN_${os}_CFLAGS}
103                  OUTPUT_VARIABLE TEST_OUTPUT)
104      set(CMAKE_EXE_LINKER_FLAGS ${SAVED_CMAKE_EXE_LINKER_FLAGS})
105    endif()
106    if(${CAN_TARGET_${os}_${arch}})
107      list(APPEND working_archs ${arch})
108    else()
109      file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
110        "Testing compiler for supporting ${os}-${arch}:\n"
111        "${TEST_OUTPUT}\n")
112    endif()
113  endforeach()
114  set(${valid_archs} ${working_archs}
115    CACHE STRING "List of valid architectures for platform ${os}.")
116endfunction()
117
118# This function checks the host cpusubtype to see if it is post-haswell. Haswell
119# and later machines can run x86_64h binaries. Haswell is cpusubtype 8.
120function(darwin_filter_host_archs input output)
121  list_intersect(tmp_var DARWIN_osx_ARCHS ${input})
122  execute_process(
123    COMMAND sysctl hw.cpusubtype
124    OUTPUT_VARIABLE SUBTYPE)
125
126  string(REGEX MATCH "hw.cpusubtype: ([0-9]*)"
127         SUBTYPE_MATCHED "${SUBTYPE}")
128  set(HASWELL_SUPPORTED Off)
129  if(SUBTYPE_MATCHED)
130    if(${CMAKE_MATCH_1} GREATER 7)
131      set(HASWELL_SUPPORTED On)
132    endif()
133  endif()
134  if(NOT HASWELL_SUPPORTED)
135    list(REMOVE_ITEM tmp_var x86_64h)
136  endif()
137  set(${output} ${tmp_var} PARENT_SCOPE)
138endfunction()
139
140# Read and process the exclude file into a list of symbols
141function(darwin_read_list_from_file output_var file)
142  if(EXISTS ${file})
143    file(READ ${file} EXCLUDES)
144    string(REPLACE "\n" ";" EXCLUDES ${EXCLUDES})
145    set(${output_var} ${EXCLUDES} PARENT_SCOPE)
146  endif()
147endfunction()
148
149# this function takes an OS, architecture and minimum version and provides a
150# list of builtin functions to exclude
151function(darwin_find_excluded_builtins_list output_var)
152  cmake_parse_arguments(LIB
153    ""
154    "OS;ARCH;MIN_VERSION"
155    ""
156    ${ARGN})
157
158  if(NOT LIB_OS OR NOT LIB_ARCH)
159    message(FATAL_ERROR "Must specify OS and ARCH to darwin_find_excluded_builtins_list!")
160  endif()
161
162  darwin_read_list_from_file(${LIB_OS}_BUILTINS
163    ${DARWIN_EXCLUDE_DIR}/${LIB_OS}.txt)
164  darwin_read_list_from_file(${LIB_OS}_${LIB_ARCH}_BASE_BUILTINS
165    ${DARWIN_EXCLUDE_DIR}/${LIB_OS}-${LIB_ARCH}.txt)
166
167  if(LIB_MIN_VERSION)
168    file(GLOB builtin_lists ${DARWIN_EXCLUDE_DIR}/${LIB_OS}*-${LIB_ARCH}.txt)
169    foreach(builtin_list ${builtin_lists})
170      string(REGEX MATCH "${LIB_OS}([0-9\\.]*)-${LIB_ARCH}.txt" VERSION_MATCHED "${builtin_list}")
171      if (VERSION_MATCHED AND NOT CMAKE_MATCH_1 VERSION_LESS LIB_MIN_VERSION)
172        if(NOT smallest_version)
173          set(smallest_version ${CMAKE_MATCH_1})
174        elseif(CMAKE_MATCH_1 VERSION_LESS smallest_version)
175          set(smallest_version ${CMAKE_MATCH_1})
176        endif()
177      endif()
178    endforeach()
179
180    if(smallest_version)
181      darwin_read_list_from_file(${LIB_ARCH}_${LIB_OS}_BUILTINS
182        ${DARWIN_EXCLUDE_DIR}/${LIB_OS}${smallest_version}-${LIB_ARCH}.txt)
183    endif()
184  endif()
185
186  set(${output_var}
187      ${${LIB_ARCH}_${LIB_OS}_BUILTINS}
188      ${${LIB_OS}_${LIB_ARCH}_BASE_BUILTINS}
189      ${${LIB_OS}_BUILTINS} PARENT_SCOPE)
190endfunction()
191
192# adds a single builtin library for a single OS & ARCH
193macro(darwin_add_builtin_library name suffix)
194  cmake_parse_arguments(LIB
195    ""
196    "PARENT_TARGET;OS;ARCH"
197    "SOURCES;CFLAGS;DEFS"
198    ${ARGN})
199  set(libname "${name}.${suffix}_${LIB_ARCH}_${LIB_OS}")
200  add_library(${libname} STATIC ${LIB_SOURCES})
201  if(DARWIN_${LIB_OS}_SYSROOT)
202    set(sysroot_flag -isysroot ${DARWIN_${LIB_OS}_SYSROOT})
203  endif()
204
205  # Make a copy of the compilation flags.
206  set(builtin_cflags ${LIB_CFLAGS})
207
208  # Strip out any inappropriate flags for the target.
209  if("${LIB_ARCH}" MATCHES "^(armv7|armv7k|armv7s)$")
210    set(builtin_cflags "")
211    foreach(cflag "${LIB_CFLAGS}")
212      string(REPLACE "-fomit-frame-pointer" "" cflag "${cflag}")
213      list(APPEND builtin_cflags ${cflag})
214    endforeach(cflag)
215  endif()
216
217  set_target_compile_flags(${libname}
218    ${sysroot_flag}
219    ${DARWIN_${LIB_OS}_BUILTIN_MIN_VER_FLAG}
220    ${builtin_cflags})
221  set_property(TARGET ${libname} APPEND PROPERTY
222      COMPILE_DEFINITIONS ${LIB_DEFS})
223  set_target_properties(${libname} PROPERTIES
224      OUTPUT_NAME ${libname}${COMPILER_RT_OS_SUFFIX})
225  set_target_properties(${libname} PROPERTIES
226    OSX_ARCHITECTURES ${LIB_ARCH})
227
228  if(LIB_PARENT_TARGET)
229    add_dependencies(${LIB_PARENT_TARGET} ${libname})
230  endif()
231
232  list(APPEND ${LIB_OS}_${suffix}_libs ${libname})
233  list(APPEND ${LIB_OS}_${suffix}_lipo_flags -arch ${arch} $<TARGET_FILE:${libname}>)
234  set_target_properties(${libname} PROPERTIES FOLDER "Compiler-RT Libraries")
235endmacro()
236
237function(darwin_lipo_libs name)
238  cmake_parse_arguments(LIB
239    ""
240    "PARENT_TARGET;OUTPUT_DIR;INSTALL_DIR"
241    "LIPO_FLAGS;DEPENDS"
242    ${ARGN})
243  if(LIB_DEPENDS AND LIB_LIPO_FLAGS)
244    add_custom_command(OUTPUT ${LIB_OUTPUT_DIR}/lib${name}.a
245      COMMAND ${CMAKE_COMMAND} -E make_directory ${LIB_OUTPUT_DIR}
246      COMMAND lipo -output
247              ${LIB_OUTPUT_DIR}/lib${name}.a
248              -create ${LIB_LIPO_FLAGS}
249      DEPENDS ${LIB_DEPENDS}
250      )
251    add_custom_target(${name}
252      DEPENDS ${LIB_OUTPUT_DIR}/lib${name}.a)
253    set_target_properties(${name} PROPERTIES FOLDER "Compiler-RT Misc")
254    add_dependencies(${LIB_PARENT_TARGET} ${name})
255
256    if(CMAKE_CONFIGURATION_TYPES)
257      set(install_component ${LIB_PARENT_TARGET})
258    else()
259      set(install_component ${name})
260    endif()
261    install(FILES ${LIB_OUTPUT_DIR}/lib${name}.a
262      DESTINATION ${LIB_INSTALL_DIR}
263      COMPONENT ${install_component})
264    add_compiler_rt_install_targets(${name} PARENT_TARGET ${LIB_PARENT_TARGET})
265  else()
266    message(WARNING "Not generating lipo target for ${name} because no input libraries exist.")
267  endif()
268endfunction()
269
270# Generates builtin libraries for all operating systems specified in ARGN. Each
271# OS library is constructed by lipo-ing together single-architecture libraries.
272macro(darwin_add_builtin_libraries)
273  set(DARWIN_EXCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Darwin-excludes)
274
275  set(CFLAGS "-fPIC -O3 -fvisibility=hidden -DVISIBILITY_HIDDEN -Wall -fomit-frame-pointer")
276  set(CMAKE_C_FLAGS "")
277  set(CMAKE_CXX_FLAGS "")
278  set(CMAKE_ASM_FLAGS "")
279
280  set(PROFILE_SOURCES ../profile/InstrProfiling
281                      ../profile/InstrProfilingBuffer
282                      ../profile/InstrProfilingPlatformDarwin
283                      ../profile/InstrProfilingWriter)
284  foreach (os ${ARGN})
285    list_intersect(DARWIN_BUILTIN_ARCHS DARWIN_${os}_ARCHS BUILTIN_SUPPORTED_ARCH)
286    foreach (arch ${DARWIN_BUILTIN_ARCHS})
287      darwin_find_excluded_builtins_list(${arch}_${os}_EXCLUDED_BUILTINS
288                              OS ${os}
289                              ARCH ${arch}
290                              MIN_VERSION ${DARWIN_${os}_BUILTIN_MIN_VER})
291
292      filter_builtin_sources(filtered_sources
293        EXCLUDE ${arch}_${os}_EXCLUDED_BUILTINS
294        ${${arch}_SOURCES})
295
296      darwin_add_builtin_library(clang_rt builtins
297                              OS ${os}
298                              ARCH ${arch}
299                              SOURCES ${filtered_sources}
300                              CFLAGS ${CFLAGS} -arch ${arch}
301                              PARENT_TARGET builtins)
302    endforeach()
303
304    # Don't build cc_kext libraries for simulator platforms
305    if(NOT DARWIN_${os}_SKIP_CC_KEXT)
306      foreach (arch ${DARWIN_BUILTIN_ARCHS})
307        # By not specifying MIN_VERSION this only reads the OS and OS-arch lists.
308        # We don't want to filter out the builtins that are present in libSystem
309        # because kexts can't link libSystem.
310        darwin_find_excluded_builtins_list(${arch}_${os}_EXCLUDED_BUILTINS
311                              OS ${os}
312                              ARCH ${arch})
313
314        filter_builtin_sources(filtered_sources
315          EXCLUDE ${arch}_${os}_EXCLUDED_BUILTINS
316          ${${arch}_SOURCES})
317
318        # In addition to the builtins cc_kext includes some profile sources
319        darwin_add_builtin_library(clang_rt cc_kext
320                                OS ${os}
321                                ARCH ${arch}
322                                SOURCES ${filtered_sources} ${PROFILE_SOURCES}
323                                CFLAGS ${CFLAGS} -arch ${arch} -mkernel
324                                DEFS KERNEL_USE
325                                PARENT_TARGET builtins)
326      endforeach()
327      set(archive_name clang_rt.cc_kext_${os})
328      if(${os} STREQUAL "osx")
329        set(archive_name clang_rt.cc_kext)
330      endif()
331      darwin_lipo_libs(${archive_name}
332                      PARENT_TARGET builtins
333                      LIPO_FLAGS ${${os}_cc_kext_lipo_flags}
334                      DEPENDS ${${os}_cc_kext_libs}
335                      OUTPUT_DIR ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
336                      INSTALL_DIR ${COMPILER_RT_LIBRARY_INSTALL_DIR})
337    endif()
338  endforeach()
339
340  # We put the x86 sim slices into the archives for their base OS
341  foreach (os ${ARGN})
342    if(NOT ${os} MATCHES ".*sim$")
343      darwin_lipo_libs(clang_rt.${os}
344                        PARENT_TARGET builtins
345                        LIPO_FLAGS ${${os}_builtins_lipo_flags} ${${os}sim_builtins_lipo_flags}
346                        DEPENDS ${${os}_builtins_libs} ${${os}sim_builtins_libs}
347                        OUTPUT_DIR ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
348                        INSTALL_DIR ${COMPILER_RT_LIBRARY_INSTALL_DIR})
349    endif()
350  endforeach()
351  darwin_add_embedded_builtin_libraries()
352endmacro()
353
354macro(darwin_add_embedded_builtin_libraries)
355  # this is a hacky opt-out. If you can't target both intel and arm
356  # architectures we bail here.
357  set(DARWIN_SOFT_FLOAT_ARCHS armv6m armv7m armv7em armv7)
358  set(DARWIN_HARD_FLOAT_ARCHS armv7em armv7)
359  if(COMPILER_RT_SUPPORTED_ARCH MATCHES ".*armv.*")
360    list(FIND COMPILER_RT_SUPPORTED_ARCH i386 i386_idx)
361    if(i386_idx GREATER -1)
362      list(APPEND DARWIN_HARD_FLOAT_ARCHS i386)
363    endif()
364
365    list(FIND COMPILER_RT_SUPPORTED_ARCH x86_64 x86_64_idx)
366    if(x86_64_idx GREATER -1)
367      list(APPEND DARWIN_HARD_FLOAT_ARCHS x86_64)
368    endif()
369
370    set(MACHO_SYM_DIR ${CMAKE_CURRENT_SOURCE_DIR}/macho_embedded)
371
372    set(CFLAGS "-Oz -Wall -fomit-frame-pointer -ffreestanding")
373    set(CMAKE_C_FLAGS "")
374    set(CMAKE_CXX_FLAGS "")
375    set(CMAKE_ASM_FLAGS "")
376
377    set(SOFT_FLOAT_FLAG -mfloat-abi=soft)
378    set(HARD_FLOAT_FLAG -mfloat-abi=hard)
379
380    set(ENABLE_PIC Off)
381    set(PIC_FLAG -fPIC)
382    set(STATIC_FLAG -static)
383
384    set(DARWIN_macho_embedded_ARCHS armv6m armv7m armv7em armv7 i386 x86_64)
385
386    set(DARWIN_macho_embedded_LIBRARY_OUTPUT_DIR
387      ${COMPILER_RT_OUTPUT_DIR}/lib/macho_embedded)
388    set(DARWIN_macho_embedded_LIBRARY_INSTALL_DIR
389      ${COMPILER_RT_INSTALL_PATH}/lib/macho_embedded)
390
391    set(CFLAGS_armv7 "-target thumbv7-apple-darwin-eabi")
392    set(CFLAGS_i386 "-march=pentium")
393
394    darwin_read_list_from_file(common_FUNCTIONS ${MACHO_SYM_DIR}/common.txt)
395    darwin_read_list_from_file(thumb2_FUNCTIONS ${MACHO_SYM_DIR}/thumb2.txt)
396    darwin_read_list_from_file(thumb2_64_FUNCTIONS ${MACHO_SYM_DIR}/thumb2-64.txt)
397    darwin_read_list_from_file(arm_FUNCTIONS ${MACHO_SYM_DIR}/arm.txt)
398    darwin_read_list_from_file(i386_FUNCTIONS ${MACHO_SYM_DIR}/i386.txt)
399
400
401    set(armv6m_FUNCTIONS ${common_FUNCTIONS} ${arm_FUNCTIONS})
402    set(armv7m_FUNCTIONS ${common_FUNCTIONS} ${arm_FUNCTIONS} ${thumb2_FUNCTIONS})
403    set(armv7em_FUNCTIONS ${common_FUNCTIONS} ${arm_FUNCTIONS} ${thumb2_FUNCTIONS})
404    set(armv7_FUNCTIONS ${common_FUNCTIONS} ${arm_FUNCTIONS} ${thumb2_FUNCTIONS} ${thumb2_64_FUNCTIONS})
405    set(i386_FUNCTIONS ${common_FUNCTIONS} ${i386_FUNCTIONS})
406    set(x86_64_FUNCTIONS ${common_FUNCTIONS})
407
408    foreach(arch ${DARWIN_macho_embedded_ARCHS})
409      filter_builtin_sources(${arch}_filtered_sources
410        INCLUDE ${arch}_FUNCTIONS
411        ${${arch}_SOURCES})
412      if(NOT ${arch}_filtered_sources)
413        message(WARNING "${arch}_SOURCES: ${${arch}_SOURCES}")
414        message(WARNING "${arch}_FUNCTIONS: ${${arch}_FUNCTIONS}")
415        message(FATAL_ERROR "Empty filtered sources!")
416      endif()
417    endforeach()
418
419    foreach(float_type SOFT HARD)
420      foreach(type PIC STATIC)
421        string(TOLOWER "${float_type}_${type}" lib_suffix)
422        foreach(arch ${DARWIN_${float_type}_FLOAT_ARCHS})
423          set(DARWIN_macho_embedded_SYSROOT ${DARWIN_osx_SYSROOT})
424          set(float_flag)
425          if(${arch} MATCHES "^arm")
426            # x86 targets are hard float by default, but the complain about the
427            # float ABI flag, so don't pass it unless we're targeting arm.
428            set(float_flag ${${float_type}_FLOAT_FLAG})
429          endif()
430          darwin_add_builtin_library(clang_rt ${lib_suffix}
431                                OS macho_embedded
432                                ARCH ${arch}
433                                SOURCES ${${arch}_filtered_sources}
434                                CFLAGS ${CFLAGS} -arch ${arch} ${${type}_FLAG} ${float_flag} ${CFLAGS_${arch}}
435                                PARENT_TARGET builtins)
436        endforeach()
437        foreach(lib ${macho_embedded_${lib_suffix}_libs})
438          set_target_properties(${lib} PROPERTIES LINKER_LANGUAGE C)
439        endforeach()
440        darwin_lipo_libs(clang_rt.${lib_suffix}
441                      PARENT_TARGET builtins
442                      LIPO_FLAGS ${macho_embedded_${lib_suffix}_lipo_flags}
443                      DEPENDS ${macho_embedded_${lib_suffix}_libs}
444                      OUTPUT_DIR ${DARWIN_macho_embedded_LIBRARY_OUTPUT_DIR}
445                      INSTALL_DIR ${DARWIN_macho_embedded_LIBRARY_INSTALL_DIR})
446      endforeach()
447    endforeach()
448  endif()
449endmacro()
450