xref: /netbsd-src/external/apache2/llvm/dist/llvm/cmake/modules/HandleLLVMOptions.cmake (revision 82d56013d7b633d116a93943de88e08335357a7c)
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 to avoid COFF 2**16 section limit.
415  if (NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang")
416    append("-Wa,-mbig-obj" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
417  endif()
418endif()
419
420option(LLVM_ENABLE_WARNINGS "Enable compiler warnings." ON)
421
422if( MSVC )
423  include(ChooseMSVCCRT)
424
425  # Add definitions that make MSVC much less annoying.
426  add_definitions(
427    # For some reason MS wants to deprecate a bunch of standard functions...
428    -D_CRT_SECURE_NO_DEPRECATE
429    -D_CRT_SECURE_NO_WARNINGS
430    -D_CRT_NONSTDC_NO_DEPRECATE
431    -D_CRT_NONSTDC_NO_WARNINGS
432    -D_SCL_SECURE_NO_DEPRECATE
433    -D_SCL_SECURE_NO_WARNINGS
434    )
435
436  # Tell MSVC to use the Unicode version of the Win32 APIs instead of ANSI.
437  add_definitions(
438    -DUNICODE
439    -D_UNICODE
440  )
441
442  # Allow setting clang-cl's /winsysroot flag.
443  set(LLVM_WINSYSROOT "" CACHE STRING
444    "If set, argument to clang-cl's /winsysroot")
445  if (LLVM_WINSYSROOT)
446    if (NOT CLANG_CL)
447      message(ERROR "LLVM_WINSYSROOT requires clang-cl")
448    endif()
449    append("/winsysroot${LLVM_WINSYSROOT}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
450  endif()
451
452  if (LLVM_ENABLE_WERROR)
453    append("/WX" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
454  endif (LLVM_ENABLE_WERROR)
455
456  append("/Zc:inline" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
457
458  # Some projects use the __cplusplus preprocessor macro to check support for
459  # a particular version of the C++ standard. When this option is not specified
460  # explicitly, macro's value is "199711L" that implies C++98 Standard.
461  # https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
462  append("/Zc:__cplusplus" CMAKE_CXX_FLAGS)
463
464  # Allow users to request PDBs in release mode. CMake offeres the
465  # RelWithDebInfo configuration, but it uses different optimization settings
466  # (/Ob1 vs /Ob2 or -O2 vs -O3). LLVM provides this flag so that users can get
467  # PDBs without changing codegen.
468  option(LLVM_ENABLE_PDB OFF)
469  if (LLVM_ENABLE_PDB AND uppercase_CMAKE_BUILD_TYPE STREQUAL "RELEASE")
470    append("/Zi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
471    # /DEBUG disables linker GC and ICF, but we want those in Release mode.
472    append("/DEBUG /OPT:REF /OPT:ICF"
473          CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS
474          CMAKE_SHARED_LINKER_FLAGS)
475  endif()
476
477  # Disable string literal const->non-const type conversion.
478  # "When specified, the compiler requires strict const-qualification
479  # conformance for pointers initialized by using string literals."
480  append("/Zc:strictStrings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
481
482  # "Generate Intrinsic Functions".
483  append("/Oi" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
484
485  # "Enforce type conversion rules".
486  append("/Zc:rvalueCast" CMAKE_CXX_FLAGS)
487
488  if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT LLVM_ENABLE_LTO)
489    # clang-cl and cl by default produce non-deterministic binaries because
490    # link.exe /incremental requires a timestamp in the .obj file.  clang-cl
491    # has the flag /Brepro to force deterministic binaries. We want to pass that
492    # whenever you're building with clang unless you're passing /incremental
493    # or using LTO (/Brepro with LTO would result in a warning about the flag
494    # being unused, because we're not generating object files).
495    # This checks CMAKE_CXX_COMPILER_ID in addition to check_cxx_compiler_flag()
496    # because cl.exe does not emit an error on flags it doesn't understand,
497    # letting check_cxx_compiler_flag() claim it understands all flags.
498    check_cxx_compiler_flag("/Brepro" SUPPORTS_BREPRO)
499    if (SUPPORTS_BREPRO)
500      # Check if /INCREMENTAL is passed to the linker and complain that it
501      # won't work with /Brepro.
502      string(TOUPPER "${CMAKE_EXE_LINKER_FLAGS}" upper_exe_flags)
503      string(TOUPPER "${CMAKE_MODULE_LINKER_FLAGS}" upper_module_flags)
504      string(TOUPPER "${CMAKE_SHARED_LINKER_FLAGS}" upper_shared_flags)
505
506      string(FIND "${upper_exe_flags} ${upper_module_flags} ${upper_shared_flags}"
507        "/INCREMENTAL" linker_flag_idx)
508
509      if (${linker_flag_idx} GREATER -1)
510        message(WARNING "/Brepro not compatible with /INCREMENTAL linking - builds will be non-deterministic")
511      else()
512        append("/Brepro" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
513      endif()
514    endif()
515  endif()
516  # By default MSVC has a 2^16 limit on the number of sections in an object file,
517  # but in many objects files need more than that. This flag is to increase the
518  # number of sections.
519  append("/bigobj" CMAKE_CXX_FLAGS)
520endif( MSVC )
521
522# Warnings-as-errors handling for GCC-compatible compilers:
523if ( LLVM_COMPILER_IS_GCC_COMPATIBLE )
524  append_if(LLVM_ENABLE_WERROR "-Werror" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
525  append_if(LLVM_ENABLE_WERROR "-Wno-error" CMAKE_REQUIRED_FLAGS)
526endif( LLVM_COMPILER_IS_GCC_COMPATIBLE )
527
528# Specific default warnings-as-errors for compilers accepting GCC-compatible warning flags:
529if ( LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL" )
530  add_flag_if_supported("-Werror=date-time" WERROR_DATE_TIME)
531  add_flag_if_supported("-Werror=unguarded-availability-new" WERROR_UNGUARDED_AVAILABILITY_NEW)
532endif( LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL" )
533
534# Modules enablement for GCC-compatible compilers:
535if ( LLVM_COMPILER_IS_GCC_COMPATIBLE AND LLVM_ENABLE_MODULES )
536  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
537  set(module_flags "-fmodules -fmodules-cache-path=${PROJECT_BINARY_DIR}/module.cache")
538  if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
539    # On Darwin -fmodules does not imply -fcxx-modules.
540    set(module_flags "${module_flags} -fcxx-modules")
541  endif()
542  if (LLVM_ENABLE_LOCAL_SUBMODULE_VISIBILITY)
543    set(module_flags "${module_flags} -Xclang -fmodules-local-submodule-visibility")
544  endif()
545  if (LLVM_ENABLE_MODULE_DEBUGGING AND
546      ((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
547       (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
548    set(module_flags "${module_flags} -gmodules")
549  endif()
550  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${module_flags}")
551
552  # Check that we can build code with modules enabled, and that repeatedly
553  # including <cassert> still manages to respect NDEBUG properly.
554  CHECK_CXX_SOURCE_COMPILES("#undef NDEBUG
555                             #include <cassert>
556                             #define NDEBUG
557                             #include <cassert>
558                             int main() { assert(this code is not compiled); }"
559                             CXX_SUPPORTS_MODULES)
560  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
561  if (CXX_SUPPORTS_MODULES)
562    append("${module_flags}" CMAKE_CXX_FLAGS)
563  else()
564    message(FATAL_ERROR "LLVM_ENABLE_MODULES is not supported by this compiler")
565  endif()
566endif( LLVM_COMPILER_IS_GCC_COMPATIBLE AND LLVM_ENABLE_MODULES )
567
568if (MSVC)
569  if (NOT CLANG_CL)
570    set(msvc_warning_flags
571      # Disabled warnings.
572      -wd4141 # Suppress ''modifier' : used more than once' (because of __forceinline combined with inline)
573      -wd4146 # Suppress 'unary minus operator applied to unsigned type, result still unsigned'
574      -wd4244 # Suppress ''argument' : conversion from 'type1' to 'type2', possible loss of data'
575      -wd4267 # Suppress ''var' : conversion from 'size_t' to 'type', possible loss of data'
576      -wd4291 # Suppress ''declaration' : no matching operator delete found; memory will not be freed if initialization throws an exception'
577      -wd4351 # Suppress 'new behavior: elements of array 'array' will be default initialized'
578      -wd4456 # Suppress 'declaration of 'var' hides local variable'
579      -wd4457 # Suppress 'declaration of 'var' hides function parameter'
580      -wd4458 # Suppress 'declaration of 'var' hides class member'
581      -wd4459 # Suppress 'declaration of 'var' hides global declaration'
582      -wd4503 # Suppress ''identifier' : decorated name length exceeded, name was truncated'
583      -wd4624 # Suppress ''derived class' : destructor could not be generated because a base class destructor is inaccessible'
584      -wd4722 # Suppress 'function' : destructor never returns, potential memory leak
585      -wd4100 # Suppress 'unreferenced formal parameter'
586      -wd4127 # Suppress 'conditional expression is constant'
587      -wd4512 # Suppress 'assignment operator could not be generated'
588      -wd4505 # Suppress 'unreferenced local function has been removed'
589      -wd4610 # Suppress '<class> can never be instantiated'
590      -wd4510 # Suppress 'default constructor could not be generated'
591      -wd4702 # Suppress 'unreachable code'
592      -wd4245 # Suppress ''conversion' : conversion from 'type1' to 'type2', signed/unsigned mismatch'
593      -wd4706 # Suppress 'assignment within conditional expression'
594      -wd4310 # Suppress 'cast truncates constant value'
595      -wd4701 # Suppress 'potentially uninitialized local variable'
596      -wd4703 # Suppress 'potentially uninitialized local pointer variable'
597      -wd4389 # Suppress 'signed/unsigned mismatch'
598      -wd4611 # Suppress 'interaction between '_setjmp' and C++ object destruction is non-portable'
599      -wd4805 # Suppress 'unsafe mix of type <type> and type <type> in operation'
600      -wd4204 # Suppress 'nonstandard extension used : non-constant aggregate initializer'
601      -wd4577 # Suppress 'noexcept used with no exception handling mode specified; termination on exception is not guaranteed'
602      -wd4091 # Suppress 'typedef: ignored on left of '' when no variable is declared'
603          # C4592 is disabled because of false positives in Visual Studio 2015
604          # Update 1. Re-evaluate the usefulness of this diagnostic with Update 2.
605      -wd4592 # Suppress ''var': symbol will be dynamically initialized (implementation limitation)
606      -wd4319 # Suppress ''operator' : zero extending 'type' to 'type' of greater size'
607          # C4709 is disabled because of a bug with Visual Studio 2017 as of
608          # v15.8.8. Re-evaluate the usefulness of this diagnostic when the bug
609          # is fixed.
610      -wd4709 # Suppress comma operator within array index expression
611
612      # Ideally, we'd like this warning to be enabled, but even MSVC 2019 doesn't
613      # support the 'aligned' attribute in the way that clang sources requires (for
614      # any code that uses the LLVM_ALIGNAS macro), so this is must be disabled to
615      # avoid unwanted alignment warnings.
616      -wd4324 # Suppress 'structure was padded due to __declspec(align())'
617
618      # Promoted warnings.
619      -w14062 # Promote 'enumerator in switch of enum is not handled' to level 1 warning.
620
621      # Promoted warnings to errors.
622      -we4238 # Promote 'nonstandard extension used : class rvalue used as lvalue' to error.
623      )
624  endif(NOT CLANG_CL)
625
626  # Enable warnings
627  if (LLVM_ENABLE_WARNINGS)
628    # Put /W4 in front of all the -we flags. cl.exe doesn't care, but for
629    # clang-cl having /W4 after the -we flags will re-enable the warnings
630    # disabled by -we.
631    set(msvc_warning_flags "/W4 ${msvc_warning_flags}")
632    # CMake appends /W3 by default, and having /W3 followed by /W4 will result in
633    # cl : Command line warning D9025 : overriding '/W3' with '/W4'.  Since this is
634    # a command line warning and not a compiler warning, it cannot be suppressed except
635    # by fixing the command line.
636    string(REGEX REPLACE " /W[0-4]" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
637    string(REGEX REPLACE " /W[0-4]" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
638
639    if (LLVM_ENABLE_PEDANTIC)
640      # No MSVC equivalent available
641    endif (LLVM_ENABLE_PEDANTIC)
642  endif (LLVM_ENABLE_WARNINGS)
643
644  foreach(flag ${msvc_warning_flags})
645    append("${flag}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
646  endforeach(flag)
647endif (MSVC)
648
649if (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
650
651  # Don't add -Wall for clang-cl, because it maps -Wall to -Weverything for
652  # MSVC compatibility.  /W4 is added above instead.
653  if (NOT CLANG_CL)
654    append("-Wall" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
655  endif()
656
657  append("-Wextra -Wno-unused-parameter -Wwrite-strings" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
658  append("-Wcast-qual" CMAKE_CXX_FLAGS)
659
660  # Turn off missing field initializer warnings for gcc to avoid noise from
661  # false positives with empty {}. Turn them on otherwise (they're off by
662  # default for clang).
663  check_cxx_compiler_flag("-Wmissing-field-initializers" CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
664  if (CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG)
665    if (CMAKE_COMPILER_IS_GNUCXX)
666      append("-Wno-missing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
667    else()
668      append("-Wmissing-field-initializers" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
669    endif()
670  endif()
671
672  if (LLVM_ENABLE_PEDANTIC AND LLVM_COMPILER_IS_GCC_COMPATIBLE)
673    append("-pedantic" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
674    append("-Wno-long-long" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
675
676    # GCC warns about redundant toplevel semicolons (enabled by -pedantic
677    # above), while Clang doesn't. Enable the corresponding Clang option to
678    # pick up on these even in builds with Clang.
679    add_flag_if_supported("-Wc++98-compat-extra-semi" CXX98_COMPAT_EXTRA_SEMI_FLAG)
680  endif()
681
682  add_flag_if_supported("-Wimplicit-fallthrough" IMPLICIT_FALLTHROUGH_FLAG)
683  add_flag_if_supported("-Wcovered-switch-default" COVERED_SWITCH_DEFAULT_FLAG)
684  append_if(USE_NO_UNINITIALIZED "-Wno-uninitialized" CMAKE_CXX_FLAGS)
685  append_if(USE_NO_MAYBE_UNINITIALIZED "-Wno-maybe-uninitialized" CMAKE_CXX_FLAGS)
686
687  # Disable -Wclass-memaccess, a C++-only warning from GCC 8 that fires on
688  # LLVM's ADT classes.
689  check_cxx_compiler_flag("-Wclass-memaccess" CXX_SUPPORTS_CLASS_MEMACCESS_FLAG)
690  append_if(CXX_SUPPORTS_CLASS_MEMACCESS_FLAG "-Wno-class-memaccess" CMAKE_CXX_FLAGS)
691
692  # Disable -Wredundant-move and -Wpessimizing-move on GCC>=9. GCC wants to
693  # remove std::move in code like "A foo(ConvertibleToA a) {
694  # return std::move(a); }", but this code does not compile (or uses the copy
695  # constructor instead) on clang<=3.8. Clang also has a -Wredundant-move and
696  # -Wpessimizing-move, but they only fire when the types match exactly, so we
697  # can keep them here.
698  if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
699    check_cxx_compiler_flag("-Wredundant-move" CXX_SUPPORTS_REDUNDANT_MOVE_FLAG)
700    append_if(CXX_SUPPORTS_REDUNDANT_MOVE_FLAG "-Wno-redundant-move" CMAKE_CXX_FLAGS)
701    check_cxx_compiler_flag("-Wpessimizing-move" CXX_SUPPORTS_PESSIMIZING_MOVE_FLAG)
702    append_if(CXX_SUPPORTS_PESSIMIZING_MOVE_FLAG "-Wno-pessimizing-move" CMAKE_CXX_FLAGS)
703  endif()
704
705  # The LLVM libraries have no stable C++ API, so -Wnoexcept-type is not useful.
706  check_cxx_compiler_flag("-Wnoexcept-type" CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG)
707  append_if(CXX_SUPPORTS_NOEXCEPT_TYPE_FLAG "-Wno-noexcept-type" CMAKE_CXX_FLAGS)
708
709  # Check if -Wnon-virtual-dtor warns even though the class is marked final.
710  # If it does, don't add it. So it won't be added on clang 3.4 and older.
711  # This also catches cases when -Wnon-virtual-dtor isn't supported by
712  # the compiler at all.  This flag is not activated for gcc since it will
713  # incorrectly identify a protected non-virtual base when there is a friend
714  # declaration. Don't activate this in general on Windows as this warning has
715  # too many false positives on COM-style classes, which are destroyed with
716  # Release() (PR32286).
717  if (NOT CMAKE_COMPILER_IS_GNUCXX AND NOT WIN32)
718    set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
719    set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -std=c++11 -Werror=non-virtual-dtor")
720    CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();protected: ~base();};
721                               class derived final : public base { public: ~derived();};
722                               int main() { return 0; }"
723                              CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR)
724    set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
725    append_if(CXX_WONT_WARN_ON_FINAL_NONVIRTUALDTOR
726              "-Wnon-virtual-dtor" CMAKE_CXX_FLAGS)
727  endif()
728
729  # Enable -Wdelete-non-virtual-dtor if available.
730  add_flag_if_supported("-Wdelete-non-virtual-dtor" DELETE_NON_VIRTUAL_DTOR_FLAG)
731
732  # Enable -Wsuggest-override if it's available, and only if it doesn't
733  # suggest adding 'override' to functions that are already marked 'final'
734  # (which means it is disabled for GCC < 9.2).
735  check_cxx_compiler_flag("-Wsuggest-override" CXX_SUPPORTS_SUGGEST_OVERRIDE_FLAG)
736  if (CXX_SUPPORTS_SUGGEST_OVERRIDE_FLAG)
737    set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
738    set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror=suggest-override")
739    CHECK_CXX_SOURCE_COMPILES("class base {public: virtual void anchor();};
740                               class derived : base {public: void anchor() final;};
741                               int main() { return 0; }"
742                              CXX_WSUGGEST_OVERRIDE_ALLOWS_ONLY_FINAL)
743    set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
744    append_if(CXX_WSUGGEST_OVERRIDE_ALLOWS_ONLY_FINAL "-Wsuggest-override" CMAKE_CXX_FLAGS)
745  endif()
746
747  # Check if -Wcomment is OK with an // comment ending with '\' if the next
748  # line is also a // comment.
749  set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS})
750  set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -Werror -Wcomment")
751  CHECK_C_SOURCE_COMPILES("// \\\\\\n//\\nint main() {return 0;}"
752                          C_WCOMMENT_ALLOWS_LINE_WRAP)
753  set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS})
754  if (NOT C_WCOMMENT_ALLOWS_LINE_WRAP)
755    append("-Wno-comment" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
756  endif()
757
758  # Enable -Wstring-conversion to catch misuse of string literals.
759  add_flag_if_supported("-Wstring-conversion" STRING_CONVERSION_FLAG)
760
761  # Prevent bugs that can happen with llvm's brace style.
762  add_flag_if_supported("-Wmisleading-indentation" MISLEADING_INDENTATION_FLAG)
763endif (LLVM_ENABLE_WARNINGS AND (LLVM_COMPILER_IS_GCC_COMPATIBLE OR CLANG_CL))
764
765if (LLVM_COMPILER_IS_GCC_COMPATIBLE AND NOT LLVM_ENABLE_WARNINGS)
766  append("-w" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
767endif()
768
769macro(append_common_sanitizer_flags)
770  if (NOT MSVC)
771    # Append -fno-omit-frame-pointer and turn on debug info to get better
772    # stack traces.
773    add_flag_if_supported("-fno-omit-frame-pointer" FNO_OMIT_FRAME_POINTER)
774    if (NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND
775        NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")
776      add_flag_if_supported("-gline-tables-only" GLINE_TABLES_ONLY)
777    endif()
778    # Use -O1 even in debug mode, otherwise sanitizers slowdown is too large.
779    if (uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND LLVM_OPTIMIZE_SANITIZED_BUILDS)
780      add_flag_if_supported("-O1" O1)
781    endif()
782  elseif (CLANG_CL)
783    # Keep frame pointers around.
784    append("/Oy-" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
785    # Always ask the linker to produce symbols with asan.
786    append("/Z7" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
787    append("-debug" CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
788  endif()
789endmacro()
790
791# Turn on sanitizers if necessary.
792if(LLVM_USE_SANITIZER)
793  if (LLVM_ON_UNIX)
794    if (LLVM_USE_SANITIZER STREQUAL "Address")
795      append_common_sanitizer_flags()
796      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
797    elseif (LLVM_USE_SANITIZER STREQUAL "HWAddress")
798      append_common_sanitizer_flags()
799      append("-fsanitize=hwaddress" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
800    elseif (LLVM_USE_SANITIZER MATCHES "Memory(WithOrigins)?")
801      append_common_sanitizer_flags()
802      append("-fsanitize=memory" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
803      if(LLVM_USE_SANITIZER STREQUAL "MemoryWithOrigins")
804        append("-fsanitize-memory-track-origins" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
805      endif()
806    elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
807      append_common_sanitizer_flags()
808      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
809    elseif (LLVM_USE_SANITIZER STREQUAL "Thread")
810      append_common_sanitizer_flags()
811      append("-fsanitize=thread" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
812    elseif (LLVM_USE_SANITIZER STREQUAL "DataFlow")
813      append("-fsanitize=dataflow" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
814    elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
815            LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
816      append_common_sanitizer_flags()
817      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
818      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
819    elseif (LLVM_USE_SANITIZER STREQUAL "Leaks")
820      append_common_sanitizer_flags()
821      append("-fsanitize=leak" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
822    else()
823      message(FATAL_ERROR "Unsupported value of LLVM_USE_SANITIZER: ${LLVM_USE_SANITIZER}")
824    endif()
825  elseif(MINGW)
826    if (LLVM_USE_SANITIZER STREQUAL "Address")
827      append_common_sanitizer_flags()
828      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
829    elseif (LLVM_USE_SANITIZER STREQUAL "Undefined")
830      append_common_sanitizer_flags()
831      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
832    elseif (LLVM_USE_SANITIZER STREQUAL "Address;Undefined" OR
833            LLVM_USE_SANITIZER STREQUAL "Undefined;Address")
834      append_common_sanitizer_flags()
835      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
836      append("${LLVM_UBSAN_FLAGS}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
837    else()
838      message(FATAL_ERROR "This sanitizer not yet supported in a MinGW environment: ${LLVM_USE_SANITIZER}")
839    endif()
840  elseif(MSVC)
841    if (LLVM_USE_SANITIZER STREQUAL "Address")
842      append_common_sanitizer_flags()
843      append("-fsanitize=address" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
844    else()
845      message(FATAL_ERROR "This sanitizer not yet supported in the MSVC environment: ${LLVM_USE_SANITIZER}")
846    endif()
847  else()
848    message(FATAL_ERROR "LLVM_USE_SANITIZER is not supported on this platform.")
849  endif()
850  if (LLVM_USE_SANITIZER MATCHES "(Undefined;)?Address(;Undefined)?")
851    add_flag_if_supported("-fsanitize-address-use-after-scope"
852                          FSANITIZE_USE_AFTER_SCOPE_FLAG)
853  endif()
854  if (LLVM_USE_SANITIZE_COVERAGE)
855    append("-fsanitize=fuzzer-no-link" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
856  endif()
857  if (LLVM_USE_SANITIZER MATCHES ".*Undefined.*")
858    set(BLACKLIST_FILE "${CMAKE_SOURCE_DIR}/utils/sanitizers/ubsan_blacklist.txt")
859    if (EXISTS "${BLACKLIST_FILE}")
860      append("-fsanitize-blacklist=${BLACKLIST_FILE}"
861             CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
862    endif()
863  endif()
864endif()
865
866# Turn on -gsplit-dwarf if requested in debug builds.
867if (LLVM_USE_SPLIT_DWARF AND
868    ((uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG") OR
869     (uppercase_CMAKE_BUILD_TYPE STREQUAL "RELWITHDEBINFO")))
870  # Limit to clang and gcc so far. Add compilers supporting this option.
871  if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
872      CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
873    add_compile_options(-gsplit-dwarf)
874  endif()
875endif()
876
877add_definitions( -D__STDC_CONSTANT_MACROS )
878add_definitions( -D__STDC_FORMAT_MACROS )
879add_definitions( -D__STDC_LIMIT_MACROS )
880
881# clang and gcc don't default-print colored diagnostics when invoked from Ninja.
882if (UNIX AND
883    CMAKE_GENERATOR STREQUAL "Ninja" AND
884    (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
885     (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
886      NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9))))
887  append("-fdiagnostics-color" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
888endif()
889
890# lld doesn't print colored diagnostics when invoked from Ninja
891if (UNIX AND CMAKE_GENERATOR STREQUAL "Ninja")
892  include(LLVMCheckLinkerFlag)
893  llvm_check_linker_flag(CXX "-Wl,--color-diagnostics" LINKER_SUPPORTS_COLOR_DIAGNOSTICS)
894  append_if(LINKER_SUPPORTS_COLOR_DIAGNOSTICS "-Wl,--color-diagnostics"
895    CMAKE_EXE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
896endif()
897
898# Add flags for add_dead_strip().
899# FIXME: With MSVS, consider compiling with /Gy and linking with /OPT:REF?
900# But MinSizeRel seems to add that automatically, so maybe disable these
901# flags instead if LLVM_NO_DEAD_STRIP is set.
902if(NOT CYGWIN AND NOT MSVC)
903  if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Darwin" AND
904     NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG")
905    check_c_compiler_flag("-Werror -fno-function-sections" C_SUPPORTS_FNO_FUNCTION_SECTIONS)
906    if (C_SUPPORTS_FNO_FUNCTION_SECTIONS)
907      # Don't add -ffunction-sections if it can't be disabled with -fno-function-sections.
908      # Doing so will break sanitizers.
909      add_flag_if_supported("-ffunction-sections" FFUNCTION_SECTIONS)
910    elseif (CMAKE_CXX_COMPILER_ID MATCHES "XL")
911      append("-qfuncsect" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
912    endif()
913    add_flag_if_supported("-fdata-sections" FDATA_SECTIONS)
914  endif()
915elseif(MSVC)
916  if( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL "DEBUG" )
917    append("/Gw" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
918  endif()
919endif()
920
921if(MSVC)
922  # Remove flags here, for exceptions and RTTI.
923  # Each target property or source property should be responsible to control
924  # them.
925  # CL.EXE complains to override flags like "/GR /GR-".
926  string(REGEX REPLACE "(^| ) */EH[-cs]+ *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
927  string(REGEX REPLACE "(^| ) */GR-? *( |$)" "\\1 \\2" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
928endif()
929
930# Provide public options to globally control RTTI and EH
931option(LLVM_ENABLE_EH "Enable Exception handling" OFF)
932option(LLVM_ENABLE_RTTI "Enable run time type information" OFF)
933if(LLVM_ENABLE_EH AND NOT LLVM_ENABLE_RTTI)
934  message(FATAL_ERROR "Exception handling requires RTTI. You must set LLVM_ENABLE_RTTI to ON")
935endif()
936
937option(LLVM_USE_NEWPM "Build LLVM using the experimental new pass manager" Off)
938mark_as_advanced(LLVM_USE_NEWPM)
939if (LLVM_USE_NEWPM)
940  append("-fexperimental-new-pass-manager"
941    CMAKE_CXX_FLAGS
942    CMAKE_C_FLAGS
943    CMAKE_EXE_LINKER_FLAGS
944    CMAKE_SHARED_LINKER_FLAGS)
945endif()
946
947option(LLVM_ENABLE_IR_PGO "Build LLVM and tools with IR PGO instrumentation (deprecated)" Off)
948mark_as_advanced(LLVM_ENABLE_IR_PGO)
949
950set(LLVM_BUILD_INSTRUMENTED OFF CACHE STRING "Build LLVM and tools with PGO instrumentation. May be specified as IR or Frontend")
951set(LLVM_VP_COUNTERS_PER_SITE "1.5" CACHE STRING "Value profile counters to use per site for IR PGO with Clang")
952mark_as_advanced(LLVM_BUILD_INSTRUMENTED LLVM_VP_COUNTERS_PER_SITE)
953string(TOUPPER "${LLVM_BUILD_INSTRUMENTED}" uppercase_LLVM_BUILD_INSTRUMENTED)
954
955if (LLVM_BUILD_INSTRUMENTED)
956  if (LLVM_ENABLE_IR_PGO OR uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "IR")
957    append("-fprofile-generate=\"${LLVM_PROFILE_DATA_DIR}\""
958      CMAKE_CXX_FLAGS
959      CMAKE_C_FLAGS)
960    if(NOT LINKER_IS_LLD_LINK)
961        append("-fprofile-generate=\"${LLVM_PROFILE_DATA_DIR}\""
962          CMAKE_EXE_LINKER_FLAGS
963          CMAKE_SHARED_LINKER_FLAGS)
964    endif()
965    # Set this to avoid running out of the value profile node section
966    # under clang in dynamic linking mode.
967    if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND
968        CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 11 AND
969        LLVM_LINK_LLVM_DYLIB)
970      append("-Xclang -mllvm -Xclang -vp-counters-per-site=${LLVM_VP_COUNTERS_PER_SITE}"
971        CMAKE_CXX_FLAGS
972        CMAKE_C_FLAGS)
973    endif()
974  elseif(uppercase_LLVM_BUILD_INSTRUMENTED STREQUAL "CSIR")
975    append("-fcs-profile-generate=\"${LLVM_CSPROFILE_DATA_DIR}\""
976      CMAKE_CXX_FLAGS
977      CMAKE_C_FLAGS)
978    if(NOT LINKER_IS_LLD_LINK)
979      append("-fcs-profile-generate=\"${LLVM_CSPROFILE_DATA_DIR}\""
980        CMAKE_EXE_LINKER_FLAGS
981        CMAKE_SHARED_LINKER_FLAGS)
982    endif()
983  else()
984    append("-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\""
985      CMAKE_CXX_FLAGS
986      CMAKE_C_FLAGS)
987    if(NOT LINKER_IS_LLD_LINK)
988      append("-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\""
989        CMAKE_EXE_LINKER_FLAGS
990        CMAKE_SHARED_LINKER_FLAGS)
991    endif()
992  endif()
993endif()
994
995# When using clang-cl with an instrumentation-based tool, add clang's library
996# resource directory to the library search path. Because cmake invokes the
997# linker directly, it isn't sufficient to pass -fsanitize=* to the linker.
998if (CLANG_CL AND (LLVM_BUILD_INSTRUMENTED OR LLVM_USE_SANITIZER))
999  execute_process(
1000    COMMAND ${CMAKE_CXX_COMPILER} /clang:-print-libgcc-file-name /clang:--rtlib=compiler-rt
1001    OUTPUT_VARIABLE clang_compiler_rt_file
1002    ERROR_VARIABLE clang_cl_stderr
1003    OUTPUT_STRIP_TRAILING_WHITESPACE
1004    ERROR_STRIP_TRAILING_WHITESPACE
1005    RESULT_VARIABLE clang_cl_exit_code)
1006  if (NOT "${clang_cl_exit_code}" STREQUAL "0")
1007    message(FATAL_ERROR
1008      "Unable to invoke clang-cl to find resource dir: ${clang_cl_stderr}")
1009  endif()
1010  file(TO_CMAKE_PATH "${clang_compiler_rt_file}" clang_compiler_rt_file)
1011  get_filename_component(clang_runtime_dir "${clang_compiler_rt_file}" DIRECTORY)
1012  append("/libpath:${clang_runtime_dir}"
1013    CMAKE_EXE_LINKER_FLAGS
1014    CMAKE_MODULE_LINKER_FLAGS
1015    CMAKE_SHARED_LINKER_FLAGS)
1016endif()
1017
1018if(LLVM_PROFDATA_FILE AND EXISTS ${LLVM_PROFDATA_FILE})
1019  if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" )
1020    append("-fprofile-instr-use=\"${LLVM_PROFDATA_FILE}\""
1021      CMAKE_CXX_FLAGS
1022      CMAKE_C_FLAGS)
1023    if(NOT LINKER_IS_LLD_LINK)
1024      append("-fprofile-instr-use=\"${LLVM_PROFDATA_FILE}\""
1025        CMAKE_EXE_LINKER_FLAGS
1026        CMAKE_SHARED_LINKER_FLAGS)
1027    endif()
1028  else()
1029    message(FATAL_ERROR "LLVM_PROFDATA_FILE can only be specified when compiling with clang")
1030  endif()
1031endif()
1032
1033option(LLVM_BUILD_INSTRUMENTED_COVERAGE "Build LLVM and tools with Code Coverage instrumentation" Off)
1034mark_as_advanced(LLVM_BUILD_INSTRUMENTED_COVERAGE)
1035append_if(LLVM_BUILD_INSTRUMENTED_COVERAGE "-fprofile-instr-generate=\"${LLVM_PROFILE_FILE_PATTERN}\" -fcoverage-mapping"
1036  CMAKE_CXX_FLAGS
1037  CMAKE_C_FLAGS
1038  CMAKE_EXE_LINKER_FLAGS
1039  CMAKE_SHARED_LINKER_FLAGS)
1040
1041if (LLVM_BUILD_INSTRUMENTED AND LLVM_BUILD_INSTRUMENTED_COVERAGE)
1042  message(FATAL_ERROR "LLVM_BUILD_INSTRUMENTED and LLVM_BUILD_INSTRUMENTED_COVERAGE cannot both be specified")
1043endif()
1044
1045if(LLVM_ENABLE_LTO AND LLVM_ON_WIN32 AND NOT LINKER_IS_LLD_LINK AND NOT MINGW)
1046  message(FATAL_ERROR "When compiling for Windows, LLVM_ENABLE_LTO requires using lld as the linker (point CMAKE_LINKER at lld-link.exe)")
1047endif()
1048if(uppercase_LLVM_ENABLE_LTO STREQUAL "THIN")
1049  append("-flto=thin" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1050  if(NOT LINKER_IS_LLD_LINK)
1051    append("-flto=thin" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1052  endif()
1053  # If the linker supports it, enable the lto cache. This improves initial build
1054  # time a little since we re-link a lot of the same objects, and significantly
1055  # improves incremental build time.
1056  # FIXME: We should move all this logic into the clang driver.
1057  if(APPLE)
1058    append("-Wl,-cache_path_lto,${PROJECT_BINARY_DIR}/lto.cache"
1059           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1060  elseif((UNIX OR MINGW) AND LLVM_USE_LINKER STREQUAL "lld")
1061    append("-Wl,--thinlto-cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
1062           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1063  elseif(LLVM_USE_LINKER STREQUAL "gold")
1064    append("-Wl,--plugin-opt,cache-dir=${PROJECT_BINARY_DIR}/lto.cache"
1065           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1066  elseif(LINKER_IS_LLD_LINK)
1067    append("/lldltocache:${PROJECT_BINARY_DIR}/lto.cache"
1068           CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1069  endif()
1070elseif(uppercase_LLVM_ENABLE_LTO STREQUAL "FULL")
1071  append("-flto=full" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1072  if(NOT LINKER_IS_LLD_LINK)
1073    append("-flto=full" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1074  endif()
1075elseif(LLVM_ENABLE_LTO)
1076  append("-flto" CMAKE_CXX_FLAGS CMAKE_C_FLAGS)
1077  if(NOT LINKER_IS_LLD_LINK)
1078    append("-flto" CMAKE_EXE_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS)
1079  endif()
1080endif()
1081
1082# Set an AIX default for LLVM_EXPORT_SYMBOLS_FOR_PLUGINS based on whether we are
1083# doing dynamic linking (see below).
1084set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default OFF)
1085if (NOT (BUILD_SHARED_LIBS OR LLVM_LINK_LLVM_DYLIB))
1086  set(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default ON)
1087endif()
1088
1089# This option makes utils/extract_symbols.py be used to determine the list of
1090# symbols to export from LLVM tools. This is necessary when on AIX or when using
1091# MSVC if you want to allow plugins. On AIX we don't show this option, and we
1092# enable it by default except when the LLVM libraries are set up for dynamic
1093# linking (due to incompatibility). With MSVC, note that the plugin has to
1094# explicitly link against (exactly one) tool so we can't unilaterally turn on
1095# LLVM_ENABLE_PLUGINS when it's enabled.
1096CMAKE_DEPENDENT_OPTION(LLVM_EXPORT_SYMBOLS_FOR_PLUGINS
1097       "Export symbols from LLVM tools so that plugins can import them" OFF
1098       "NOT ${CMAKE_SYSTEM_NAME} MATCHES AIX" ${LLVM_EXPORT_SYMBOLS_FOR_PLUGINS_AIX_default})
1099if(BUILD_SHARED_LIBS AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1100  message(FATAL_ERROR "BUILD_SHARED_LIBS not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
1101endif()
1102if(LLVM_LINK_LLVM_DYLIB AND LLVM_EXPORT_SYMBOLS_FOR_PLUGINS)
1103  message(FATAL_ERROR "LLVM_LINK_LLVM_DYLIB not compatible with LLVM_EXPORT_SYMBOLS_FOR_PLUGINS")
1104endif()
1105
1106# By default we should enable LLVM_ENABLE_IDE only for multi-configuration
1107# generators. This option disables optional build system features that make IDEs
1108# less usable.
1109set(LLVM_ENABLE_IDE_default OFF)
1110if (CMAKE_CONFIGURATION_TYPES)
1111  set(LLVM_ENABLE_IDE_default ON)
1112endif()
1113option(LLVM_ENABLE_IDE
1114       "Disable optional build system features that cause problems for IDE generators"
1115       ${LLVM_ENABLE_IDE_default})
1116if (CMAKE_CONFIGURATION_TYPES AND NOT LLVM_ENABLE_IDE)
1117  message(WARNING "Disabling LLVM_ENABLE_IDE on multi-configuration generators is not recommended.")
1118endif()
1119
1120function(get_compile_definitions)
1121  get_directory_property(top_dir_definitions DIRECTORY ${CMAKE_SOURCE_DIR} COMPILE_DEFINITIONS)
1122  foreach(definition ${top_dir_definitions})
1123    if(DEFINED result)
1124      string(APPEND result " -D${definition}")
1125    else()
1126      set(result "-D${definition}")
1127    endif()
1128  endforeach()
1129  set(LLVM_DEFINITIONS "${result}" PARENT_SCOPE)
1130endfunction()
1131get_compile_definitions()
1132
1133option(LLVM_FORCE_ENABLE_STATS "Enable statistics collection for builds that wouldn't normally enable it" OFF)
1134
1135check_symbol_exists(os_signpost_interval_begin "os/signpost.h" macos_signposts_available)
1136if(macos_signposts_available)
1137  check_cxx_source_compiles(
1138    "#include <os/signpost.h>
1139    int main() { os_signpost_interval_begin(nullptr, 0, \"\", \"\"); return 0; }"
1140    macos_signposts_usable)
1141  if(macos_signposts_usable)
1142    set(LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS "WITH_ASSERTS" CACHE STRING
1143        "Enable support for Xcode signposts. Can be WITH_ASSERTS, FORCE_ON, FORCE_OFF")
1144    string(TOUPPER "${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}"
1145                   uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS)
1146    if( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "WITH_ASSERTS" )
1147      if( LLVM_ENABLE_ASSERTIONS )
1148        set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
1149      endif()
1150    elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_ON" )
1151      set( LLVM_SUPPORT_XCODE_SIGNPOSTS 1 )
1152    elseif( uppercase_LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS STREQUAL "FORCE_OFF" )
1153      # We don't need to do anything special to turn off signposts.
1154    elseif( NOT DEFINED LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS )
1155      # Treat LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS like "FORCE_OFF" when it has not been
1156      # defined.
1157    else()
1158      message(FATAL_ERROR "Unknown value for LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS:"
1159                          " \"${LLVM_ENABLE_SUPPORT_XCODE_SIGNPOSTS}\"!")
1160    endif()
1161  endif()
1162endif()
1163
1164set(LLVM_SOURCE_PREFIX "" CACHE STRING "Use prefix for sources")
1165
1166option(LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO "Use relative paths in debug info" OFF)
1167
1168if(LLVM_USE_RELATIVE_PATHS_IN_DEBUG_INFO)
1169  check_c_compiler_flag("-fdebug-prefix-map=foo=bar" SUPPORTS_FDEBUG_PREFIX_MAP)
1170  if(LLVM_ENABLE_PROJECTS_USED)
1171    get_filename_component(source_root "${LLVM_MAIN_SRC_DIR}/.." ABSOLUTE)
1172  else()
1173    set(source_root "${LLVM_MAIN_SRC_DIR}")
1174  endif()
1175  file(RELATIVE_PATH relative_root "${source_root}" "${CMAKE_BINARY_DIR}")
1176  append_if(SUPPORTS_FDEBUG_PREFIX_MAP "-fdebug-prefix-map=${CMAKE_BINARY_DIR}=${relative_root}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1177  append_if(SUPPORTS_FDEBUG_PREFIX_MAP "-fdebug-prefix-map=${source_root}/=${LLVM_SOURCE_PREFIX}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1178  add_flag_if_supported("-no-canonical-prefixes" NO_CANONICAL_PREFIXES)
1179endif()
1180
1181option(LLVM_USE_RELATIVE_PATHS_IN_FILES "Use relative paths in sources and debug info" OFF)
1182
1183if(LLVM_USE_RELATIVE_PATHS_IN_FILES)
1184  check_c_compiler_flag("-ffile-prefix-map=foo=bar" SUPPORTS_FFILE_PREFIX_MAP)
1185  if(LLVM_ENABLE_PROJECTS_USED)
1186    get_filename_component(source_root "${LLVM_MAIN_SRC_DIR}/.." ABSOLUTE)
1187  else()
1188    set(source_root "${LLVM_MAIN_SRC_DIR}")
1189  endif()
1190  file(RELATIVE_PATH relative_root "${source_root}" "${CMAKE_BINARY_DIR}")
1191  append_if(SUPPORTS_FFILE_PREFIX_MAP "-ffile-prefix-map=${CMAKE_BINARY_DIR}=${relative_root}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1192  append_if(SUPPORTS_FFILE_PREFIX_MAP "-ffile-prefix-map=${source_root}/=${LLVM_SOURCE_PREFIX}" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
1193  add_flag_if_supported("-no-canonical-prefixes" NO_CANONICAL_PREFIXES)
1194endif()
1195
1196if(LLVM_INCLUDE_TESTS)
1197  # Lit test suite requires at least python 3.6
1198  set(LLVM_MINIMUM_PYTHON_VERSION 3.6)
1199else()
1200  # FIXME: it is unknown if this is the actual minimum bound
1201  set(LLVM_MINIMUM_PYTHON_VERSION 3.0)
1202endif()
1203