1# This CMake module is responsible for interpreting the user defined LLVM_
2# options and executing the appropriate CMake commands to realize the users'
3# selections.
4
5# This is commonly needed so make sure it's defined before we include anything
6# else.
7string(TOUPPER "${CMAKE_BUILD_TYPE}" uppercase_CMAKE_BUILD_TYPE)
8
9include(CheckCompilerVersion)
10include(HandleLLVMStdlib)
11include(CheckCCompilerFlag)
12include(CheckCXXCompilerFlag)
13include(CheckSymbolExists)
14include(CMakeDependentOption)
15include(LLVMProcessSources)
16
17if(CMAKE_LINKER MATCHES "lld-link" OR (MSVC AND (LLVM_USE_LINKER STREQUAL "lld" OR LLVM_ENABLE_LLD)))
18  set(LINKER_IS_LLD_LINK TRUE)
19else()
20  set(LINKER_IS_LLD_LINK FALSE)
21endif()
22
23set(LLVM_ENABLE_LTO OFF CACHE STRING "Build LLVM with LTO. May be specified as Thin or Full to use a particular kind of LTO")
24string(TOUPPER "${LLVM_ENABLE_LTO}" uppercase_LLVM_ENABLE_LTO)
25
26# Ninja Job Pool support
27# The following only works with the Ninja generator in CMake >= 3.0.
28set(LLVM_PARALLEL_COMPILE_JOBS "" CACHE STRING
29  "Define the maximum number of concurrent compilation jobs (Ninja only).")
30if(LLVM_PARALLEL_COMPILE_JOBS)
31  if(NOT CMAKE_GENERATOR STREQUAL "Ninja")
32    message(WARNING "Job pooling is only available with Ninja generators.")
33  else()
34    set_property(GLOBAL APPEND PROPERTY JOB_POOLS compile_job_pool=${LLVM_PARALLEL_COMPILE_JOBS})
35    set(CMAKE_JOB_POOL_COMPILE compile_job_pool)
36  endif()
37endif()
38
39set(LLVM_PARALLEL_LINK_JOBS "" CACHE STRING
40  "Define the maximum number of concurrent link jobs (Ninja only).")
41if(CMAKE_GENERATOR STREQUAL "Ninja")
42  if(NOT LLVM_PARALLEL_LINK_JOBS AND uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
43    message(STATUS "ThinLTO provides its own parallel linking - limiting parallel link jobs to 2.")
44    set(LLVM_PARALLEL_LINK_JOBS "2")
45  endif()
46  if(LLVM_PARALLEL_LINK_JOBS)
47    set_property(GLOBAL APPEND PROPERTY JOB_POOLS link_job_pool=${LLVM_PARALLEL_LINK_JOBS})
48    set(CMAKE_JOB_POOL_LINK link_job_pool)
49  endif()
50elseif(LLVM_PARALLEL_LINK_JOBS)
51  message(WARNING "Job pooling is only available with Ninja generators.")
52endif()
53
54if( LLVM_ENABLE_ASSERTIONS )
55  # MSVC doesn't like _DEBUG on release builds. See PR 4379.
56  if( NOT MSVC )
57    add_definitions( -D_DEBUG )
58  endif()
59  # On non-Debug builds cmake automatically defines NDEBUG, so we
60  # explicitly undefine it:
61  if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
62    # NOTE: use `add_compile_options` rather than `add_definitions` since
63    # `add_definitions` does not support generator expressions.
64    add_compile_options($<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-UNDEBUG>)
65    if (MSVC)
66      # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines.
67      foreach (flags_var_to_scrub
68          CMAKE_CXX_FLAGS_RELEASE
69          CMAKE_CXX_FLAGS_RELWITHDEBINFO
70          CMAKE_CXX_FLAGS_MINSIZEREL
71          CMAKE_C_FLAGS_RELEASE
72          CMAKE_C_FLAGS_RELWITHDEBINFO
73          CMAKE_C_FLAGS_MINSIZEREL)
74        string (REGEX REPLACE "(^| )[/-]D *NDEBUG($| )" " "
75          "${flags_var_to_scrub}" "${${flags_var_to_scrub}}")
76      endforeach()
77     endif()
78  endif()
79endif()
80
81if(LLVM_ENABLE_EXPENSIVE_CHECKS)
82  add_definitions(-DEXPENSIVE_CHECKS)
83
84  # In some libstdc++ versions, std::min_element is not constexpr when
85  # _GLIBCXX_DEBUG is enabled.
86  CHECK_CXX_SOURCE_COMPILES("
87    #define _GLIBCXX_DEBUG
88    #include <algorithm>
89    int main(int argc, char** argv) {
90      static constexpr int data[] = {0, 1};
91      constexpr const int* min_elt = std::min_element(&data[0], &data[2]);
92      return 0;
93    }" CXX_SUPPORTS_GLIBCXX_DEBUG)
94  if(CXX_SUPPORTS_GLIBCXX_DEBUG)
95    add_definitions(-D_GLIBCXX_DEBUG)
96  else()
97    add_definitions(-D_GLIBCXX_ASSERTIONS)
98  endif()
99endif()
100
101if (LLVM_ENABLE_STRICT_FIXED_SIZE_VECTORS)
102  add_definitions(-DSTRICT_FIXED_SIZE_VECTORS)
103endif()
104
105string(TOUPPER "${LLVM_ABI_BREAKING_CHECKS}" uppercase_LLVM_ABI_BREAKING_CHECKS)
106
107if( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "WITH_ASSERTS" )
108  if( LLVM_ENABLE_ASSERTIONS )
109    set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
110  endif()
111elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_ON" )
112  set( LLVM_ENABLE_ABI_BREAKING_CHECKS 1 )
113elseif( uppercase_LLVM_ABI_BREAKING_CHECKS STREQUAL "FORCE_OFF" )
114  # We don't need to do anything special to turn off ABI breaking checks.
115elseif( NOT DEFINED LLVM_ABI_BREAKING_CHECKS )
116  # Treat LLVM_ABI_BREAKING_CHECKS like "FORCE_OFF" when it has not been
117  # defined.
118else()
119  message(FATAL_ERROR "Unknown value for LLVM_ABI_BREAKING_CHECKS: \"${LLVM_ABI_BREAKING_CHECKS}\"!")
120endif()
121
122if( LLVM_REVERSE_ITERATION )
123  set( LLVM_ENABLE_REVERSE_ITERATION 1 )
124endif()
125
126if(WIN32)
127  set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
128  if(CYGWIN)
129    set(LLVM_ON_WIN32 0)
130    set(LLVM_ON_UNIX 1)
131  else(CYGWIN)
132    set(LLVM_ON_WIN32 1)
133    set(LLVM_ON_UNIX 0)
134  endif(CYGWIN)
135else(WIN32)
136  if(FUCHSIA OR UNIX)
137    set(LLVM_ON_WIN32 0)
138    set(LLVM_ON_UNIX 1)
139    if(APPLE OR ${CMAKE_SYSTEM_NAME} MATCHES "AIX")
140      set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
141    else()
142      set(LLVM_HAVE_LINK_VERSION_SCRIPT 1)
143    endif()
144  else(FUCHSIA OR UNIX)
145    MESSAGE(SEND_ERROR "Unable to determine platform")
146  endif(FUCHSIA OR UNIX)
147endif(WIN32)
148
149if (CMAKE_SYSTEM_NAME MATCHES "OS390")
150  set(LLVM_HAVE_LINK_VERSION_SCRIPT 0)
151endif()
152
153set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX})
154set(LTDL_SHLIB_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
155
156# We use *.dylib rather than *.so on darwin, but we stick with *.so on AIX.
157if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
158  set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_MODULE_SUFFIX})
159else()
160  set(LLVM_PLUGIN_EXT ${CMAKE_SHARED_LIBRARY_SUFFIX})
161endif()
162
163if(APPLE)
164  if(LLVM_ENABLE_LLD AND LLVM_ENABLE_LTO)
165    message(FATAL_ERROR "lld does not support LTO on Darwin")
166  endif()
167  # Darwin-specific linker flags for loadable modules.
168  set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-flat_namespace -Wl,-undefined -Wl,suppress")
169endif()
170
171if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
172  # RHEL7 has ar and ranlib being non-deterministic by default. The D flag forces determinism,
173  # however only GNU version of ar and ranlib (2.27) have this option.
174  # RHEL DTS7 is also affected by this, which uses GNU binutils 2.28
175  execute_process(COMMAND ${CMAKE_AR} rD t.a
176                  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
177                  RESULT_VARIABLE AR_RESULT
178                  OUTPUT_QUIET
179                  ERROR_QUIET
180                  )
181  if(${AR_RESULT} EQUAL 0)
182    execute_process(COMMAND ${CMAKE_RANLIB} -D t.a
183                    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
184                    RESULT_VARIABLE RANLIB_RESULT
185                    OUTPUT_QUIET
186                    ERROR_QUIET
187                    )
188    if(${RANLIB_RESULT} EQUAL 0)
189      set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> Dqc <TARGET> <LINK_FLAGS> <OBJECTS>")
190      set(CMAKE_C_ARCHIVE_APPEND "<CMAKE_AR> Dq  <TARGET> <LINK_FLAGS> <OBJECTS>")
191      set(CMAKE_C_ARCHIVE_FINISH "<CMAKE_RANLIB> -D <TARGET>")
192
193      set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> Dqc <TARGET> <LINK_FLAGS> <OBJECTS>")
194      set(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> Dq  <TARGET> <LINK_FLAGS> <OBJECTS>")
195      set(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -D <TARGET>")
196    endif()
197    file(REMOVE ${CMAKE_BINARY_DIR}/t.a)
198  endif()
199endif()
200
201if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
202  # -fPIC does not enable the large code model for GCC on AIX but does for XL.
203  if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
204    append("-mcmodel=large" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
205  elseif(CMAKE_CXX_COMPILER_ID MATCHES "XL")
206    # XL generates a small number of relocations not of the large model, -bbigtoc is needed.
207    append("-Wl,-bbigtoc"
208           CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
209    # The default behaviour on AIX processes dynamic initialization of non-local variables with
210    # static storage duration even for archive members that are otherwise unreferenced.
211    # Since `--whole-archive` is not used by the LLVM build to keep such initializations for Linux,
212    # we can limit the processing for archive members to only those that are otherwise referenced.
213    append("-bcdtors:mbr"
214           CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
215  endif()
216  if(BUILD_SHARED_LIBS)
217    # See rpath handling in AddLLVM.cmake
218    # FIXME: Remove this warning if this rpath is no longer hardcoded.
219    message(WARNING "Build and install environment path info may be exposed; binaries will also be unrelocatable.")
220  endif()
221endif()
222
223# Pass -Wl,-z,defs. This makes sure all symbols are defined. Otherwise a DSO
224# build might work on ELF but fail on MachO/COFF.
225if(NOT (CMAKE_SYSTEM_NAME MATCHES "Darwin|FreeBSD|OpenBSD|DragonFly|AIX|SunOS|OS390" OR
226        WIN32 OR CYGWIN) AND
227   NOT LLVM_USE_SANITIZER)
228  set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,defs")
229endif()
230
231# Pass -Wl,-z,nodelete. This makes sure our shared libraries are not unloaded
232# by dlclose(). We need that since the CLI API relies on cross-references
233# between global objects which became horribly broken when one of the libraries
234# is unloaded.
235if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
236  set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,nodelete")
237  set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -Wl,-z,nodelete")
238endif()
239
240
241function(append value)
242  foreach(variable ${ARGN})
243    set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
244  endforeach(variable)
245endfunction()
246
247function(append_if condition value)
248  if (${condition})
249    foreach(variable ${ARGN})
250      set(${variable} "${${variable}} ${value}" PARENT_SCOPE)
251    endforeach(variable)
252  endif()
253endfunction()
254
255macro(add_flag_if_supported flag name)
256  check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
257  append_if("C_SUPPORTS_${name}" "${flag}" CMAKE_C_FLAGS)
258  check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
259  append_if("CXX_SUPPORTS_${name}" "${flag}" CMAKE_CXX_FLAGS)
260endmacro()
261
262function(add_flag_or_print_warning flag name)
263  check_c_compiler_flag("-Werror ${flag}" "C_SUPPORTS_${name}")
264  check_cxx_compiler_flag("-Werror ${flag}" "CXX_SUPPORTS_${name}")
265  if (C_SUPPORTS_${name} AND CXX_SUPPORTS_${name})
266    message(STATUS "Building with ${flag}")
267    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}" PARENT_SCOPE)
268    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}" PARENT_SCOPE)
269    set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} ${flag}" PARENT_SCOPE)
270  else()
271    message(WARNING "${flag} is not supported.")
272  endif()
273endfunction()
274
275if( LLVM_ENABLE_LLD )
276  if ( LLVM_USE_LINKER )
277    message(FATAL_ERROR "LLVM_ENABLE_LLD and LLVM_USE_LINKER can't be set at the same time")
278  endif()
279  # In case of MSVC cmake always invokes the linker directly, so the linker
280  # should be specified by CMAKE_LINKER cmake variable instead of by -fuse-ld
281  # compiler option.
282  if ( NOT MSVC )
283    set(LLVM_USE_LINKER "lld")
284  endif()
285endif()
286
287if( LLVM_USE_LINKER )
288  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
289  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -fuse-ld=${LLVM_USE_LINKER}")
290  check_cxx_source_compiles("int main() { return 0; }" CXX_SUPPORTS_CUSTOM_LINKER)
291  if ( NOT CXX_SUPPORTS_CUSTOM_LINKER )
292    message(FATAL_ERROR "Host compiler does not support '-fuse-ld=${LLVM_USE_LINKER}'")
293  endif()
294  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
295  append("-fuse-ld=${LLVM_USE_LINKER}"
296    CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
297endif()
298
299if( LLVM_ENABLE_PIC )
300  if( XCODE )
301    # Xcode has -mdynamic-no-pic on by default, which overrides -fPIC. I don't
302    # know how to disable this, so just force ENABLE_PIC off for now.
303    message(WARNING "-fPIC not supported with Xcode.")
304  elseif( WIN32 OR CYGWIN)
305    # On Windows all code is PIC. MinGW warns if -fPIC is used.
306  else()
307    add_flag_or_print_warning("-fPIC" FPIC)
308  endif()
309  # GCC for MIPS can miscompile LLVM due to PR37701.
310  if(CMAKE_COMPILER_IS_GNUCXX AND LLVM_NATIVE_ARCH STREQUAL "Mips" AND
311         NOT Uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
312    add_flag_or_print_warning("-fno-shrink-wrap" FNO_SHRINK_WRAP)
313  endif()
314  # gcc with -O3 -fPIC generates TLS sequences that violate the spec on
315  # Solaris/sparcv9, causing executables created with the system linker
316  # to SEGV (GCC PR target/96607).
317  # clang with -O3 -fPIC generates code that SEGVs.
318  # Both can be worked around by compiling with -O instead.
319  if(${CMAKE_SYSTEM_NAME} STREQUAL "SunOS" AND LLVM_NATIVE_ARCH STREQUAL "Sparc")
320    llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O[23]" "-O")
321    llvm_replace_compiler_option(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O[23]" "-O")
322  endif()
323endif()
324
325if(NOT WIN32 AND NOT CYGWIN AND NOT (${CMAKE_SYSTEM_NAME} MATCHES "AIX" AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU"))
326  # MinGW warns if -fvisibility-inlines-hidden is used.
327  # GCC on AIX warns if -fvisibility-inlines-hidden is used.
328  check_cxx_compiler_flag("-fvisibility-inlines-hidden" SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG)
329  append_if(SUPPORTS_FVISIBILITY_INLINES_HIDDEN_FLAG "-fvisibility-inlines-hidden" CMAKE_CXX_FLAGS)
330endif()
331
332if(CMAKE_SIZEOF_VOID_P EQUAL 8 AND MINGW)
333  add_definitions( -D_FILE_OFFSET_BITS=64 )
334endif()
335
336if( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
337  # TODO: support other platforms and toolchains.
338  if( LLVM_BUILD_32_BITS )
339    message(STATUS "Building 32 bits executables and libraries.")
340    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")
341    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
342    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -m32")
343    set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32")
344    set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -m32")
345
346    # FIXME: CMAKE_SIZEOF_VOID_P is still 8
347    add_definitions(-D_LARGEFILE_SOURCE)
348    add_definitions(-D_FILE_OFFSET_BITS=64)
349  endif( LLVM_BUILD_32_BITS )
350endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 )
351
352# If building on a GNU specific 32-bit system, make sure off_t is 64 bits
353# so that off_t can stored offset > 2GB.
354# Android until version N (API 24) doesn't support it.
355if (ANDROID AND (ANDROID_NATIVE_API_LEVEL LESS 24))
356  set(LLVM_FORCE_SMALLFILE_FOR_ANDROID TRUE)
357endif()
358if( CMAKE_SIZEOF_VOID_P EQUAL 4 AND NOT LLVM_FORCE_SMALLFILE_FOR_ANDROID)
359  # FIXME: It isn't handled in LLVM_BUILD_32_BITS.
360  add_definitions( -D_LARGEFILE_SOURCE )
361  add_definitions( -D_FILE_OFFSET_BITS=64 )
362endif()
363
364if( XCODE )
365  # For Xcode enable several build settings that correspond to
366  # many warnings that are on by default in Clang but are
367  # not enabled for historical reasons.  For versions of Xcode
368  # that do not support these options they will simply
369  # be ignored.
370  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_RETURN_TYPE "YES")
371  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE "YES")
372  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VALUE "YES")
373  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_VARIABLE "YES")
374  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_SIGN_COMPARE "YES")
375  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNUSED_FUNCTION "YES")
376  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED "YES")
377  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS "YES")
378  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_UNINITIALIZED_AUTOS "YES")
379  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_BOOL_CONVERSION "YES")
380  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_EMPTY_BODY "YES")
381  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_ENUM_CONVERSION "YES")
382  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_INT_CONVERSION "YES")
383  set(CMAKE_XCODE_ATTRIBUTE_CLANG_WARN_CONSTANT_CONVERSION "YES")
384  set(CMAKE_XCODE_ATTRIBUTE_GCC_WARN_NON_VIRTUAL_DESTRUCTOR "YES")
385endif()
386
387# On Win32 using MS tools, provide an option to set the number of parallel jobs
388# to use.
389if( MSVC_IDE )
390  set(LLVM_COMPILER_JOBS "0" CACHE STRING
391    "Number of parallel compiler jobs. 0 means use all processors. Default is 0.")
392  if( NOT LLVM_COMPILER_JOBS STREQUAL "1" )
393    if( LLVM_COMPILER_JOBS STREQUAL "0" )
394      add_definitions( /MP )
395    else()
396      message(STATUS "Number of parallel compiler jobs set to " ${LLVM_COMPILER_JOBS})
397      add_definitions( /MP${LLVM_COMPILER_JOBS} )
398    endif()
399  else()
400    message(STATUS "Parallel compilation disabled")
401  endif()
402endif()
403
404# set stack reserved size to ~10MB
405if(MSVC)
406  # CMake previously automatically set this value for MSVC builds, but the
407  # behavior was changed in CMake 2.8.11 (Issue 12437) to use the MSVC default
408  # value (1 MB) which is not enough for us in tasks such as parsing recursive
409  # C++ templates in Clang.
410  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /STACK:10000000")
411elseif(MINGW) # FIXME: Also cygwin?
412  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--stack,16777216")
413
414  # Pass -mbig-obj to mingw gas on Win64. COFF has a 2**16 section limit, and
415  # on Win64, every COMDAT function creates at least 3 sections: .text, .pdata,
416  # and .xdata.
417  if (CMAKE_SIZEOF_VOID_P EQUAL 8)
418    append("-Wa,-mbig-obj" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
419  endif()
420endif()
421
422option(LLVM_ENABLE_WARNINGS "Enable compiler warnings." ON)
423
424if( MSVC )
425  include(ChooseMSVCCRT)
426
427  # Add definitions that make MSVC much less annoying.
428  add_definitions(
429    # For some reason MS wants to deprecate a bunch of standard functions...
430    -D_CRT_SECURE_NO_DEPRECATE
431    -D_CRT_SECURE_NO_WARNINGS
432    -D_CRT_NONSTDC_NO_DEPRECATE
433    -D_CRT_NONSTDC_NO_WARNINGS
434    -D_SCL_SECURE_NO_DEPRECATE
435    -D_SCL_SECURE_NO_WARNINGS
436    )
437
438  # Tell MSVC to use the Unicode version of the Win32 APIs instead of ANSI.
439  add_definitions(
440    -DUNICODE
441    -D_UNICODE
442  )
443
444  # Allow setting clang-cl's /winsysroot flag.
445  set(LLVM_WINSYSROOT "" CACHE STRING
446    "If set, argument to clang-cl's /winsysroot")
447  if (LLVM_WINSYSROOT)
448    if (NOT CLANG_CL)
449      message(ERROR "LLVM_WINSYSROOT requires clang-cl")
450    endif()
451    append("/winsysroot${LLVM_WINSYSROOT}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
452  endif()
453
454  if (LLVM_ENABLE_WERROR)
455    append("/WX" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
456  endif (LLVM_ENABLE_WERROR)
457
458  append("/Zc:inline" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
459
460  # Some projects use the __cplusplus preprocessor macro to check support for
461  # a particular version of the C++ standard. When this option is not specified
462  # explicitly, macro's value is "199711L" that implies C++98 Standard.
463  # https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
464  append("/Zc:__cplusplus" CMAKE_CXX_FLAGS)
465
466  # Allow users to request PDBs in release mode. CMake offeres the
467  # RelWithDebInfo configuration, but it uses different optimization settings
468  # (/Ob1 vs /Ob2 or -O2 vs -O3). LLVM provides this flag so that users can get
469  # PDBs without changing codegen.
470  option(LLVM_ENABLE_PDB OFF)
471  if (LLVM_ENABLE_PDB AND uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE")
472    append("/Zi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
473    # /DEBUG disables linker GC and ICF, but we want those in Release mode.
474    append("/DEBUG /OPT:REF /OPT:ICF"
475          CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS
476          CMAKE_SHARED_LINKER_FLAGS)
477  endif()
478
479  # Disable string literal const->non-const type conversion.
480  # "When specified, the compiler requires strict const-qualification
481  # conformance for pointers initialized by using string literals."
482  append("/Zc:strictStrings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
483
484  # "Generate Intrinsic Functions".
485  append("/Oi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
486
487  # "Enforce type conversion rules".
488  append("/Zc:rvalueCast" CMAKE_CXX_FLAGS)
489
490  if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT LLVM_ENABLE_LTO)
491    # clang-cl and cl by default produce non-deterministic binaries because
492    # link.exe /incremental requires a timestamp in the .obj file.  clang-cl
493    # has the flag /Brepro to force deterministic binaries. We want to pass that
494    # whenever you're building with clang unless you're passing /incremental
495    # or using LTO (/Brepro with LTO would result in a warning about the flag
496    # being unused, because we're not generating object files).
497    # This checks CMAKE_CXX_COMPILER_ID in addition to check_cxx_compiler_flag()
498    # because cl.exe does not emit an error on flags it doesn't understand,
499    # letting check_cxx_compiler_flag() claim it understands all flags.
500    check_cxx_compiler_flag("/Brepro" SUPPORTS_BREPRO)
501    if (SUPPORTS_BREPRO)
502      # Check if /INCREMENTAL is passed to the linker and complain that it
503      # won't work with /Brepro.
504      string(TOUPPER "${CMAKE_EXE_LINKER_FLAGS}" upper_exe_flags)
505      string(TOUPPER "${CMAKE_MODULE_LINKER_FLAGS}" upper_module_flags)
506      string(TOUPPER "${CMAKE_SHARED_LINKER_FLAGS}" upper_shared_flags)
507
508      string(FIND "${upper_exe_flags} ${upper_module_flags} ${upper_shared_flags}"
509        "/INCREMENTAL" linker_flag_idx)
510
511      if (${linker_flag_idx} GREATER -1)
512        message(WARNING "/Brepro not compatible with /INCREMENTAL linking - builds will be non-deterministic")
513      else()
514        append("/Brepro" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
515      endif()
516    endif()
517  endif()
518  # By default MSVC has a 2^16 limit on the number of sections in an object file,
519  # but in many objects files need more than that. This flag is to increase the
520  # number of sections.
521  append("/bigobj" CMAKE_CXX_FLAGS)
522endif( MSVC )
523
524# Warnings-as-errors handling for GCC-compatible compilers:
525if ( LLVM_COMPILER_IS_GCC_COMPATIBLE )
526  append_if(LLVM_ENABLE_WERROR "-Werror" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
527  append_if(LLVM_ENABLE_WERROR "-Wno-error" CMAKE_REQUIRED_FLAGS)
528endif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
529
530# Specific default warnings-as-errors for compilers accepting GCC-compatible warning flags:
531if ( LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL" )
532  add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME)
533  add_flag_if_supported("-Werror=unguarded-availability-new" WERROR_UNGUARDED_AVAILABILITY_NEW)
534endif( LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL" )
535
536# Modules enablement for GCC-compatible compilers:
537if ( LLVM_COMPILER_IS_GCC_COMPATIBLE AND LLVM_ENABLE_MODULES )
538  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
539  set(module_flags "-fmodules -fmodules-cache-path=${PROJECT_BINARY_DIR}/module.cache")
540  if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
541    # On Darwin -fmodules does not imply -fcxx-modules.
542    set(module_flags "${module_flags} -fcxx-modules")
543  endif()
544  if (LLVM_ENABLE_LOCAL_SUBMODULE_VISIBILITY)
545    set(module_flags "${module_flags} -Xclang -fmodules-local-submodule-visibility")
546  endif()
547  if (LLVM_ENABLE_MODULE_DEBUGGING AND
548      ((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
549       (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
550    set(module_flags "${module_flags} -gmodules")
551  endif()
552  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${module_flags}")
553
554  # Check that we can build code with modules enabled, and that repeatedly
555  # including <cassert> still manages to respect NDEBUG properly.
556  CHECK_CXX_SOURCE_COMPILES("#undef NDEBUG
557                             #include <cassert>
558                             #define NDEBUG
559                             #include <cassert>
560                             int main() { assert(this code is not compiled); }"
561                             CXX_SUPPORTS_MODULES)
562  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
563  if (CXX_SUPPORTS_MODULES)
564    append("${module_flags}" CMAKE_CXX_FLAGS)
565  else()
566    message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler")
567  endif()
568endif( LLVM_COMPILER_IS_GCC_COMPATIBLE AND LLVM_ENABLE_MODULES )
569
570if (MSVC)
571  if (NOT CLANG_CL)
572    set(msvc_warning_flags
573      # Disabled warnings.
574      -wd4141 # Suppress ''modifier' : used more than once' (because of __forceinline combined with inline)
575      -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned'
576      -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data'
577      -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data'
578      -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception'
579      -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized'
580      -wd4456 # Suppress 'declaration of 'var' hides local variable'
581      -wd4457 # Suppress 'declaration of 'var' hides function parameter'
582      -wd4458 # Suppress 'declaration of 'var' hides class member'
583      -wd4459 # Suppress 'declaration of 'var' hides global declaration'
584      -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated'
585      -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible'
586      -wd4722 # Suppress 'function' : destructor never returns, potential memory leak
587      -wd4100 # Suppress 'unreferenced formal parameter'
588      -wd4127 # Suppress 'conditional expression is constant'
589      -wd4512 # Suppress 'assignment operator could not be generated'
590      -wd4505 # Suppress 'unreferenced local function has been removed'
591      -wd4610 # Suppress '<class> can never be instantiated'
592      -wd4510 # Suppress 'default constructor could not be generated'
593      -wd4702 # Suppress 'unreachable code'
594      -wd4245 # Suppress ''conversion' : conversion from 'type1' to 'type2', signed/unsigned mismatch'
595      -wd4706 # Suppress 'assignment within conditional expression'
596      -wd4310 # Suppress 'cast truncates constant value'
597      -wd4701 # Suppress 'potentially uninitialized local variable'
598      -wd4703 # Suppress 'potentially uninitialized local pointer variable'
599      -wd4389 # Suppress 'signed/unsigned mismatch'
600      -wd4611 # Suppress 'interaction between '_setjmp' and C++ object destruction is non-portable'
601      -wd4805 # Suppress 'unsafe mix of type <type> and type <type> in operation'
602      -wd4204 # Suppress 'nonstandard extension used : non-constant aggregate initializer'
603      -wd4577 # Suppress 'noexcept used with no exception handling mode specified; termination on exception is not guaranteed'
604      -wd4091 # Suppress 'typedef: ignored on left of '' when no variable is declared'
605          # C4592 is disabled because of false positives in Visual Studio 2015
606          # Update 1. Re-evaluate the usefulness of this diagnostic with Update 2.
607      -wd4592 # Suppress ''var': symbol will be dynamically initialized (implementation limitation)
608      -wd4319 # Suppress ''operator' : zero extending 'type' to 'type' of greater size'
609          # C4709 is disabled because of a bug with Visual Studio 2017 as of
610          # v15.8.8. Re-evaluate the usefulness of this diagnostic when the bug
611          # is fixed.
612      -wd4709 # Suppress comma operator within array index expression
613
614      # Ideally, we'd like this warning to be enabled, but even MSVC 2019 doesn't
615      # support the 'aligned' attribute in the way that clang sources requires (for
616      # any code that uses the LLVM_ALIGNAS macro), so this is must be disabled to
617      # avoid unwanted alignment warnings.
618      -wd4324 # Suppress 'structure was padded due to __declspec(align())'
619
620      # Promoted warnings.
621      -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.
622
623      # Promoted warnings to errors.
624      -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error.
625      )
626  endif(NOT CLANG_CL)
627
628  # Enable warnings
629  if (LLVM_ENABLE_WARNINGS)
630    # Put /W4 in front of all the -we flags. cl.exe doesn't care, but for
631    # clang-cl having /W4 after the -we flags will re-enable the warnings
632    # disabled by -we.
633    set(msvc_warning_flags "/W4 ${msvc_warning_flags}")
634    # CMake appends /W3 by default, and having /W3 followed by /W4 will result in
635    # cl : Command line warning D9025 : overriding '/W3' with '/W4'.  Since this is
636    # a command line warning and not a compiler warning, it cannot be suppressed except
637    # by fixing the command line.
638    string(REGEX REPLACE " /W[0-4]" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
639    string(REGEX REPLACE " /W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
640
641    if (LLVM_ENABLE_PEDANTIC)
642      # No MSVC equivalent available
643    endif (LLVM_ENABLE_PEDANTIC)
644  endif (LLVM_ENABLE_WARNINGS)
645
646  foreach(flag ${msvc_warning_flags})
647    append("${flag}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
648  endforeach(flag)
649endif (MSVC)
650
651if (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
652
653  # Don't add -Wall for clang-cl, because it maps -Wall to -Weverything for
654  # MSVC compatibility.  /W4 is added above instead.
655  if (NOT CLANG_CL)
656    append("-Wall" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
657  endif()
658
659  append("-Wextra -Wno-unused-parameter -Wwrite-strings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
660  append("-Wcast-qual" CMAKE_CXX_FLAGS)
661
662  # Turn off missing field initializer warnings for gcc to avoid noise from
663  # false positives with empty {}. Turn them on otherwise (they're off by
664  # default for clang).
665  check_cxx_compiler_flag("-Wmissing-field-initializers" CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
666  if (CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
667    if (CMAKE_COMPILER_IS_GNUCXX)
668      append("-Wno-missing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
669    else()
670      append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
671    endif()
672  endif()
673
674  if (LLVM_ENABLE_PEDANTIC AND LLVM_COMPILER_IS_GCC_COMPATIBLE)
675    append("-pedantic" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
676    append("-Wno-long-long" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
677
678    # GCC warns about redundant toplevel semicolons (enabled by -pedantic
679    # above), while Clang doesn't. Enable the corresponding Clang option to
680    # pick up on these even in builds with Clang.
681    add_flag_if_supported("-Wc++98-compat-extra-semi" CXX98_COMPAT_EXTRA_SEMI_FLAG)
682  endif()
683
684  add_flag_if_supported("-Wimplicit-fallthrough" IMPLICIT_FALLTHROUGH_FLAG)
685  add_flag_if_supported("-Wcovered-switch-default" COVERED_SWITCH_DEFAULT_FLAG)
686  append_if(USE_NO_UNINITIALIZED "-Wno-uninitialized" CMAKE_CXX_FLAGS)
687  append_if(USE_NO_MAYBE_UNINITIALIZED "-Wno-maybe-uninitialized" CMAKE_CXX_FLAGS)
688
689  # Disable -Wclass-memaccess, a C++-only warning from GCC 8 that fires on
690  # LLVM's ADT classes.
691  check_cxx_compiler_flag("-Wclass-memaccess" CXX_SUPPORTS_CLASS_MEMACCESS_FLAG)
692  append_if(CXX_SUPPORTS_CLASS_MEMACCESS_FLAG "-Wno-class-memaccess" CMAKE_CXX_FLAGS)
693
694  # Disable -Wredundant-move and -Wpessimizing-move on GCC>=9. GCC wants to
695  # remove std::move in code like "A foo(ConvertibleToA a) {
696  # return std::move(a); }", but this code does not compile (or uses the copy
697  # constructor instead) on clang<=3.8. Clang also has a -Wredundant-move and
698  # -Wpessimizing-move, but they only fire when the types match exactly, so we
699  # can keep them here.
700  if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
701    check_cxx_compiler_flag("-Wredundant-move" CXX_SUPPORTS_REDUNDANT_MOVE_FLAG)
702    append_if(CXX_SUPPORTS_REDUNDANT_MOVE_FLAG "-Wno-redundant-move" CMAKE_CXX_FLAGS)
703    check_cxx_compiler_flag("-Wpessimizing-move" CXX_SUPPORTS_PESSIMIZING_MOVE_FLAG)
704    append_if(CXX_SUPPORTS_PESSIMIZING_MOVE_FLAG "-Wno-pessimizing-move" CMAKE_CXX_FLAGS)
705  endif()
706
707  # The LLVM libraries have no stable C++ API, so -Wnoexcept-type is not useful.
708  check_cxx_compiler_flag("-Wnoexcept-type" CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG)
709  append_if(CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG "-Wno-noexcept-type" CMAKE_CXX_FLAGS)
710
711  # Check if -Wnon-virtual-dtor warns even though the class is marked final.
712  # If it does, don't add it. So it won't be added on clang 3.4 and older.
713  # This also catches cases when -Wnon-virtual-dtor isn't supported by
714  # the compiler at all.  This flag is not activated for gcc since it will
715  # incorrectly identify a protected non-virtual base when there is a friend
716  # declaration. Don't activate this in general on Windows as this warning has
717  # too many false positives on COM-style classes, which are destroyed with
718  # Release() (PR32286).
719  if (NOT CMAKE_COMPILER_IS_GNUCXX AND NOT WIN32)
720    set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
721    set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++11 -Werror=non-virtual-dtor")
722    CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();protected: ~base();};
723                               class derived final : public base { public: ~derived();};
724                               int main() { return 0; }"
725                              CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR)
726    set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
727    append_if(CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR
728              "-Wnon-virtual-dtor" CMAKE_CXX_FLAGS)
729  endif()
730
731  # Enable -Wdelete-non-virtual-dtor if available.
732  add_flag_if_supported("-Wdelete-non-virtual-dtor" DELETE_NON_VIRTUAL_DTOR_FLAG)
733
734  # Enable -Wsuggest-override if it's available, and only if it doesn't
735  # suggest adding 'override' to functions that are already marked 'final'
736  # (which means it is disabled for GCC < 9.2).
737  check_cxx_compiler_flag("-Wsuggest-override" CXX_SUPPORTS_SUGGEST_OVERRIDE_FLAG)
738  if (CXX_SUPPORTS_SUGGEST_OVERRIDE_FLAG)
739    set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
740    set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror=suggest-override")
741    CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();};
742                               class derived : base {public: void anchor() final;};
743                               int main() { return 0; }"
744                              CXX_WSUGGEST_OVERRIDE_ALLOWS_ONLY_FINAL)
745    set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
746    append_if(CXX_WSUGGEST_OVERRIDE_ALLOWS_ONLY_FINAL "-Wsuggest-override" CMAKE_CXX_FLAGS)
747  endif()
748
749  # Check if -Wcomment is OK with an // comment ending with '\' if the next
750  # line is also a // comment.
751  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
752  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror -Wcomment")
753  CHECK_C_SOURCE_COMPILES("// \\\\\\n//\\nint main() {return 0;}"
754                          C_WCOMMENT_ALLOWS_LINE_WRAP)
755  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
756  if (NOT C_WCOMMENT_ALLOWS_LINE_WRAP)
757    append("-Wno-comment" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
758  endif()
759
760  # Enable -Wstring-conversion to catch misuse of string literals.
761  add_flag_if_supported("-Wstring-conversion" STRING_CONVERSION_FLAG)
762endif (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
763
764if (LLVM_COMPILER_IS_GCC_COMPATIBLE AND NOT LLVM_ENABLE_WARNINGS)
765  append("-w" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
766endif()
767
768macro(append_common_sanitizer_flags)
769  if (NOT MSVC)
770    # Append -fno-omit-frame-pointer and turn on debug info to get better
771    # stack traces.
772    add_flag_if_supported("-fno-omit-frame-pointer" FNO_OMIT_FRAME_POINTER)
773    if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND
774        NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")
775      add_flag_if_supported("-gline-tables-only" GLINE_TABLES_ONLY)
776    endif()
777    # Use -O1 even in debug mode, otherwise sanitizers slowdown is too large.
778    if (uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND LLVM_OPTIMIZE_SANITIZED_BUILDS)
779      add_flag_if_supported("-O1" O1)
780    endif()
781  elseif (CLANG_CL)
782    # Keep frame pointers around.
783    append("/Oy-" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
784    # Always ask the linker to produce symbols with asan.
785    append("/Z7" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
786    append("-debug" CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
787  endif()
788endmacro()
789
790# Turn on sanitizers if necessary.
791if(LLVM_USE_SANITIZER)
792  if (LLVM_ON_UNIX)
793    if (LLVM_USE_SANITIZER STREQUAL "Address")
794      append_common_sanitizer_flags()
795      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
796    elseif (LLVM_USE_SANITIZER STREQUAL "HWAddress")
797      append_common_sanitizer_flags()
798      append("-fsanitize=hwaddress" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
799    elseif (LLVM_USE_SANITIZER MATCHES "Memory(WithOrigins)?")
800      append_common_sanitizer_flags()
801      append("-fsanitize=memory" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
802      if(LLVM_USE_SANITIZER STREQUAL "MemoryWithOrigins")
803        append("-fsanitize-memory-track-origins" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
804      endif()
805    elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
806      append_common_sanitizer_flags()
807      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
808    elseif (LLVM_USE_SANITIZER STREQUAL "Thread")
809      append_common_sanitizer_flags()
810      append("-fsanitize=thread" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
811    elseif (LLVM_USE_SANITIZER STREQUAL "DataFlow")
812      append("-fsanitize=dataflow" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
813    elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
814            LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
815      append_common_sanitizer_flags()
816      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
817      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
818    elseif (LLVM_USE_SANITIZER STREQUAL "Leaks")
819      append_common_sanitizer_flags()
820      append("-fsanitize=leak" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
821    else()
822      message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}")
823    endif()
824  elseif(MINGW)
825    if (LLVM_USE_SANITIZER STREQUAL "Address")
826      append_common_sanitizer_flags()
827      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
828    elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
829      append_common_sanitizer_flags()
830      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
831    elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
832            LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
833      append_common_sanitizer_flags()
834      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
835      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
836    else()
837      message(FATAL_ERROR "This sanitizer not yet supported in a MinGW environment: ${LLVM_USE_SANITIZER}")
838    endif()
839  elseif(MSVC)
840    if (LLVM_USE_SANITIZER STREQUAL "Address")
841      append_common_sanitizer_flags()
842      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
843    else()
844      message(FATAL_ERROR "This sanitizer not yet supported in the MSVC environment: ${LLVM_USE_SANITIZER}")
845    endif()
846  else()
847    message(FATAL_ERROR "LLVM_USE_SANITIZER is not supported on this platform.")
848  endif()
849  if (LLVM_USE_SANITIZER MATCHES "(Undefined;)?Address(;Undefined)?")
850    add_flag_if_supported("-fsanitize-address-use-after-scope"
851                          FSANITIZE_USE_AFTER_SCOPE_FLAG)
852  endif()
853  if (LLVM_USE_SANITIZE_COVERAGE)
854    append("-fsanitize=fuzzer-no-link" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
855  endif()
856  if (LLVM_USE_SANITIZER MATCHES ".*Undefined.*")
857    set(BLACKLIST_FILE "${CMAKE_SOURCE_DIR}/utils/sanitizers/ubsan_blacklist.txt")
858    if (EXISTS "${BLACKLIST_FILE}")
859      append("-fsanitize-blacklist=${BLACKLIST_FILE}"
860             CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
861    endif()
862  endif()
863endif()
864
865# Turn on -gsplit-dwarf if requested in debug builds.
866if (LLVM_USE_SPLIT_DWARF AND
867    ((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
868     (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
869  # Limit to clang and gcc so far. Add compilers supporting this option.
870  if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
871      CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
872    add_compile_options(-gsplit-dwarf)
873  endif()
874endif()
875
876add_definitions( -D__STDC_CONSTANT_MACROS )
877add_definitions( -D__STDC_FORMAT_MACROS )
878add_definitions( -D__STDC_LIMIT_MACROS )
879
880# clang and gcc don't default-print colored diagnostics when invoked from Ninja.
881if (UNIX AND
882    CMAKE_GENERATOR STREQUAL "Ninja" AND
883    (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
884     (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
885      NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9))))
886  append("-fdiagnostics-color" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
887endif()
888
889# lld doesn't print colored diagnostics when invoked from Ninja
890if (UNIX AND CMAKE_GENERATOR STREQUAL "Ninja")
891  include(LLVMCheckLinkerFlag)
892  llvm_check_linker_flag(CXX "-Wl,--color-diagnostics" LINKER_SUPPORTS_COLOR_DIAGNOSTICS)
893  append_if(LINKER_SUPPORTS_COLOR_DIAGNOSTICS "-Wl,--color-diagnostics"
894    CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
895endif()
896
897# Add flags for add_dead_strip().
898# FIXME: With MSVS, consider compiling with /Gy and linking with /OPT:REF?
899# But MinSizeRel seems to add that automatically, so maybe disable these
900# flags instead if LLVM_NO_DEAD_STRIP is set.
901if(NOT CYGWIN AND NOT MSVC)
902  if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND
903     NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
904    check_c_compiler_flag("-Werror -fno-function-sections" C_SUPPORTS_FNO_FUNCTION_SECTIONS)
905    if (C_SUPPORTS_FNO_FUNCTION_SECTIONS)
906      # Don't add -ffunction-sections if it can't be disabled with -fno-function-sections.
907      # Doing so will break sanitizers.
908      add_flag_if_supported("-ffunction-sections" FFUNCTION_SECTIONS)
909    elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
910      append("-qfuncsect" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
911    endif()
912    add_flag_if_supported("-fdata-sections" FDATA_SECTIONS)
913  endif()
914elseif(MSVC)
915  if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
916    append("/Gw" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
917  endif()
918endif()
919
920if(MSVC)
921  # Remove flags here, for exceptions and RTTI.
922  # Each target property or source property should be responsible to control
923  # them.
924  # CL.EXE complains to override flags like "/GR /GR-".
925  string(REGEX REPLACE "(^| ) */EH[-cs]+ *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
926  string(REGEX REPLACE "(^| ) */GR-? *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
927endif()
928
929# Provide public options to globally control RTTI and EH
930option(LLVM_ENABLE_EH "Enable Exception handling" OFF)
931option(LLVM_ENABLE_RTTI "Enable run time type information" OFF)
932if(LLVM_ENABLE_EH AND NOT LLVM_ENABLE_RTTI)
933  message(FATAL_ERROR "Exception handling requires RTTI. You must set LLVM_ENABLE_RTTI to ON")
934endif()
935
936option(LLVM_USE_NEWPM "Build LLVM using the experimental new pass manager" Off)
937mark_as_advanced(LLVM_USE_NEWPM)
938if (LLVM_USE_NEWPM)
939  append("-fexperimental-new-pass-manager"
940    CMAKE_CXX_FLAGS
941    CMAKE_C_FLAGS
942    CMAKE_EXE_LINKER_FLAGS
943    CMAKE_SHARED_LINKER_FLAGS)
944endif()
945
946option(LLVM_ENABLE_IR_PGO "Build LLVM and tools with IR PGO instrumentation (deprecated)" Off)
947mark_as_advanced(LLVM_ENABLE_IR_PGO)
948
949set(LLVM_BUILD_INSTRUMENTED OFF CACHE STRING "Build LLVM and tools with PGO instrumentation. May be specified as IR or Frontend")
950set(LLVM_VP_COUNTERS_PER_SITE "1.5" CACHE STRING "Value profile counters to use per site for IR PGO with Clang")
951mark_as_advanced(LLVM_BUILD_INSTRUMENTED LLVM_VP_COUNTERS_PER_SITE)
952string(TOUPPER "${LLVM_BUILD_INSTRUMENTED}" uppercase_LLVM_BUILD_INSTRUMENTED)
953
954if (LLVM_BUILD_INSTRUMENTED)
955  if (LLVM_ENABLE_IR_PGO OR uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "IR")
956    append("-fprofile-generate=\"${LLVM_PROFILE_DATA_DIR}\""
957      CMAKE_CXX_FLAGS
958      CMAKE_C_FLAGS)
959    if(NOT LINKER_IS_LLD_LINK)
960        append("-fprofile-generate=\"${LLVM_PROFILE_DATA_DIR}\""
961          CMAKE_EXE_LINKER_FLAGS
962          CMAKE_SHARED_LINKER_FLAGS)
963    endif()
964    # Set this to avoid running out of the value profile node section
965    # under clang in dynamic linking mode.
966    if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND
967        CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 11 AND
968        LLVM_LINK_LLVM_DYLIB)
969      append("-Xclang -mllvm -Xclang -vp-counters-per-site=${LLVM_VP_COUNTERS_PER_SITE}"
970        CMAKE_CXX_FLAGS
971        CMAKE_C_FLAGS)
972    endif()
973  elseif(uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "CSIR")
974    append("-fcs-profile-generate=\"${LLVM_CSPROFILE_DATA_DIR}\""
975      CMAKE_CXX_FLAGS
976      CMAKE_C_FLAGS)
977    if(NOT LINKER_IS_LLD_LINK)
978      append("-fcs-profile-generate=\"${LLVM_CSPROFILE_DATA_DIR}\""
979        CMAKE_EXE_LINKER_FLAGS
980        CMAKE_SHARED_LINKER_FLAGS)
981    endif()
982  else()
983    append("-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\""
984      CMAKE_CXX_FLAGS
985      CMAKE_C_FLAGS)
986    if(NOT LINKER_IS_LLD_LINK)
987      append("-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\""
988        CMAKE_EXE_LINKER_FLAGS
989        CMAKE_SHARED_LINKER_FLAGS)
990    endif()
991  endif()
992endif()
993
994# When using clang-cl with an instrumentation-based tool, add clang's library
995# resource directory to the library search path. Because cmake invokes the
996# linker directly, it isn't sufficient to pass -fsanitize=* to the linker.
997if (CLANG_CL AND (LLVM_BUILD_INSTRUMENTED OR LLVM_USE_SANITIZER))
998  execute_process(
999    COMMAND ${CMAKE_CXX_COMPILER} /clang:-print-libgcc-file-name /clang:--rtlib=compiler-rt
1000    OUTPUT_VARIABLE clang_compiler_rt_file
1001    ERROR_VARIABLE clang_cl_stderr
1002    OUTPUT_STRIP_TRAILING_WHITESPACE
1003    ERROR_STRIP_TRAILING_WHITESPACE
1004    RESULT_VARIABLE clang_cl_exit_code)
1005  if (NOT "${clang_cl_exit_code}" STREQUAL "0")
1006    message(FATAL_ERROR
1007      "Unable to invoke clang-cl to find resource dir: ${clang_cl_stderr}")
1008  endif()
1009  file(TO_CMAKE_PATH "${clang_compiler_rt_file}" clang_compiler_rt_file)
1010  get_filename_component(clang_runtime_dir "${clang_compiler_rt_file}" DIRECTORY)
1011  append("/libpath:${clang_runtime_dir}"
1012    CMAKE_EXE_LINKER_FLAGS
1013    CMAKE_MODULE_LINKER_FLAGS
1014    CMAKE_SHARED_LINKER_FLAGS)
1015endif()
1016
1017if(LLVM_PROFDATA_FILE AND EXISTS ${LLVM_PROFDATA_FILE})
1018  if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" )
1019    append("-fprofile-instr-use=\"${LLVM_PROFDATA_FILE}\""
1020      CMAKE_CXX_FLAGS
1021      CMAKE_C_FLAGS)
1022    if(NOT LINKER_IS_LLD_LINK)
1023      append("-fprofile-instr-use=\"${LLVM_PROFDATA_FILE}\""
1024        CMAKE_EXE_LINKER_FLAGS
1025        CMAKE_SHARED_LINKER_FLAGS)
1026    endif()
1027  else()
1028    message(FATAL_ERROR "LLVM_PROFDATA_FILE can only be specified when compiling with clang")
1029  endif()
1030endif()
1031
1032option(LLVM_BUILD_INSTRUMENTED_COVERAGE "Build LLVM and tools with Code Coverage instrumentation" Off)
1033mark_as_advanced(LLVM_BUILD_INSTRUMENTED_COVERAGE)
1034append_if(LLVM_BUILD_INSTRUMENTED_COVERAGE "-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\" -fcoverage-mapping"
1035  CMAKE_CXX_FLAGS
1036  CMAKE_C_FLAGS
1037  CMAKE_EXE_LINKER_FLAGS
1038  CMAKE_SHARED_LINKER_FLAGS)
1039
1040if (LLVM_BUILD_INSTRUMENTED AND LLVM_BUILD_INSTRUMENTED_COVERAGE)
1041  message(FATAL_ERROR "LLVM_BUILD_INSTRUMENTED and LLVM_BUILD_INSTRUMENTED_COVERAGE cannot both be specified")
1042endif()
1043
1044if(LLVM_ENABLE_LTO AND LLVM_ON_WIN32 AND NOT LINKER_IS_LLD_LINK AND NOT MINGW)
1045  message(FATAL_ERROR "When compiling for Windows, LLVM_ENABLE_LTO requires using lld as the linker (point CMAKE_LINKER at lld-link.exe)")
1046endif()
1047if(uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
1048  append("-flto=thin" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1049  if(NOT LINKER_IS_LLD_LINK)
1050    append("-flto=thin" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1051  endif()
1052  # If the linker supports it, enable the lto cache. This improves initial build
1053  # time a little since we re-link a lot of the same objects, and significantly
1054  # improves incremental build time.
1055  # FIXME: We should move all this logic into the clang driver.
1056  if(APPLE)
1057    append("-Wl,-cache_path_lto,${PROJECT_BINARY_DIR}/lto.cache"
1058           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1059  elseif((UNIX OR MINGW) AND LLVM_USE_LINKER STREQUAL "lld")
1060    append("-Wl,--thinlto-cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
1061           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1062  elseif(LLVM_USE_LINKER STREQUAL "gold")
1063    append("-Wl,--plugin-opt,cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
1064           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1065  elseif(LINKER_IS_LLD_LINK)
1066    append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
1067           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1068  endif()
1069elseif(uppercase_LLVM_ENABLE_LTO STREQUAL "FULL")
1070  append("-flto=full" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1071  if(NOT LINKER_IS_LLD_LINK)
1072    append("-flto=full" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1073  endif()
1074elseif(LLVM_ENABLE_LTO)
1075  append("-flto" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1076  if(NOT LINKER_IS_LLD_LINK)
1077    append("-flto" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1078  endif()
1079endif()
1080
1081# Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we are
1082# doing dynamic linking (see below).
1083set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)
1084if (NOT (BUILD_SHARED_LIBS OR LLVM_LINK_LLVM_DYLIB))
1085  set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default ON)
1086endif()
1087
1088# This option makes utils/extract_symbols.py be used to determine the list of
1089# symbols to export from LLVM tools. This is necessary when on AIX or when using
1090# MSVC if you want to allow plugins. On AIX we don't show this option, and we
1091# enable it by default except when the LLVM libraries are set up for dynamic
1092# linking (due to incompatibility). With MSVC, note that the plugin has to
1093# explicitly link against (exactly one) tool so we can't unilaterally turn on
1094# LLVM_ENABLE_PLUGINS when it's enabled.
1095CMAKE_DEPENDENT_OPTION(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS
1096       "Export symbols from LLVM tools so that plugins can import them" OFF
1097       "NOT ${CMAKE_SYSTEM_NAME} MATCHES AIX" ${LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default})
1098if(BUILD_SHARED_LIBS AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1099  message(FATAL_ERROR "BUILD_SHARED_LIBS not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
1100endif()
1101if(LLVM_LINK_LLVM_DYLIB AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1102  message(FATAL_ERROR "LLVM_LINK_LLVM_DYLIB not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
1103endif()
1104
1105# By default we should enable LLVM_ENABLE_IDE only for multi-configuration
1106# generators. This option disables optional build system features that make IDEs
1107# less usable.
1108set(LLVM_ENABLE_IDE_default OFF)
1109if (CMAKE_CONFIGURATION_TYPES)
1110  set(LLVM_ENABLE_IDE_default ON)
1111endif()
1112option(LLVM_ENABLE_IDE
1113       "Disable optional build system features that cause problems for IDE generators"
1114       ${LLVM_ENABLE_IDE_default})
1115if (CMAKE_CONFIGURATION_TYPES AND NOT LLVM_ENABLE_IDE)
1116  message(WARNING "Disabling LLVM_ENABLE_IDE on multi-configuration generators is not recommended.")
1117endif()
1118
1119function(get_compile_definitions)
1120  get_directory_property(top_dir_definitions DIRECTORY ${CMAKE_SOURCE_DIR} COMPILE_DEFINITIONS)
1121  foreach(definition ${top_dir_definitions})
1122    if(DEFINED result)
1123      string(APPEND result " -D${definition}")
1124    else()
1125      set(result "-D${definition}")
1126    endif()
1127  endforeach()
1128  set(LLVM_DEFINITIONS "${result}" PARENT_SCOPE)
1129endfunction()
1130get_compile_definitions()
1131
1132option(LLVM_FORCE_ENABLE_STATS "Enable statistics collection for builds that wouldn't normally enable it" OFF)
1133
1134check_symbol_exists(os_signpost_interval_begin "os/signpost.h" macos_signposts_available)
1135if(macos_signposts_available)
1136  check_cxx_source_compiles(
1137    "#include <os/signpost.h>
1138    int main() { os_signpost_interval_begin(nullptr, 0, \"\", \"\"); return 0; }"
1139    macos_signposts_usable)
1140  if(macos_signposts_usable)
1141    set(LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS "WITH_ASSERTS" CACHE STRING
1142        "Enable support for Xcode signposts. Can be WITH_ASSERTS, FORCE_ON, FORCE_OFF")
1143    string(TOUPPER "${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}"
1144                   uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS)
1145    if( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "WITH_ASSERTS" )
1146      if( LLVM_ENABLE_ASSERTIONS )
1147        set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
1148      endif()
1149    elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_ON" )
1150      set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
1151    elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_OFF" )
1152      # We don't need to do anything special to turn off signposts.
1153    elseif( NOT DEFINED LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS )
1154      # Treat LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS like "FORCE_OFF" when it has not been
1155      # defined.
1156    else()
1157      message(FATAL_ERROR "Unknown value for LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS:"
1158                          " \"${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}\"!")
1159    endif()
1160  endif()
1161endif()
1162
1163set(LLVM_SOURCE_PREFIX "" CACHE STRING "Use prefix for sources")
1164
1165option(LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO "Use relative paths in debug info" OFF)
1166
1167if(LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO)
1168  check_c_compiler_flag("-fdebug-prefix-map=foo=bar" SUPPORTS_FDEBUG_PREFIX_MAP)
1169  if(LLVM_ENABLE_PROJECTS_USED)
1170    get_filename_component(source_root "${LLVM_MAIN_SRC_DIR}/.." ABSOLUTE)
1171  else()
1172    set(source_root "${LLVM_MAIN_SRC_DIR}")
1173  endif()
1174  file(RELATIVE_PATH relative_root "${source_root}" "${CMAKE_BINARY_DIR}")
1175  append_if(SUPPORTS_FDEBUG_PREFIX_MAP "-fdebug-prefix-map=${CMAKE_BINARY_DIR}=${relative_root}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1176  append_if(SUPPORTS_FDEBUG_PREFIX_MAP "-fdebug-prefix-map=${source_root}/=${LLVM_SOURCE_PREFIX}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1177  add_flag_if_supported("-no-canonical-prefixes" NO_CANONICAL_PREFIXES)
1178endif()
1179
1180option(LLVM_USE_RELATIVE_PATHS_IN_FILES "Use relative paths in sources and debug info" OFF)
1181
1182if(LLVM_USE_RELATIVE_PATHS_IN_FILES)
1183  check_c_compiler_flag("-ffile-prefix-map=foo=bar" SUPPORTS_FFILE_PREFIX_MAP)
1184  if(LLVM_ENABLE_PROJECTS_USED)
1185    get_filename_component(source_root "${LLVM_MAIN_SRC_DIR}/.." ABSOLUTE)
1186  else()
1187    set(source_root "${LLVM_MAIN_SRC_DIR}")
1188  endif()
1189  file(RELATIVE_PATH relative_root "${source_root}" "${CMAKE_BINARY_DIR}")
1190  append_if(SUPPORTS_FFILE_PREFIX_MAP "-ffile-prefix-map=${CMAKE_BINARY_DIR}=${relative_root}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1191  append_if(SUPPORTS_FFILE_PREFIX_MAP "-ffile-prefix-map=${source_root}/=${LLVM_SOURCE_PREFIX}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1192  add_flag_if_supported("-no-canonical-prefixes" NO_CANONICAL_PREFIXES)
1193endif()
1194
1195if(LLVM_INCLUDE_TESTS)
1196  # Lit test suite requires at least python 3.6
1197  set(LLVM_MINIMUM_PYTHON_VERSION 3.6)
1198else()
1199  # FIXME: it is unknown if this is the actual minimum bound
1200  set(LLVM_MINIMUM_PYTHON_VERSION 3.0)
1201endif()
1202