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