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