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