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