onnxruntime

Форк
0
/
adjust_global_compile_flags.cmake 
367 строк · 14.7 Кб
1
# work around Android NDK bug which doesn't include -O flag for Release configuration
2
# https://github.com/android/ndk/issues/1740
3
# TODO: remove this when the NDK version(s) we support get fixed
4
if (CMAKE_SYSTEM_NAME STREQUAL "Android")
5
  # NB: attempting to match the effects of this fix: https://android-review.googlesource.com/c/platform/ndk/+/2168845
6
  string(APPEND CMAKE_C_FLAGS_RELEASE " -O3")
7
  string(APPEND CMAKE_CXX_FLAGS_RELEASE " -O3")
8
  string(APPEND CMAKE_ASM_FLAGS_RELEASE " -O3")
9
endif()
10

11
# Suggested by https://gitlab.kitware.com/cmake/cmake/-/issues/20132
12
# MacCatalyst is not well supported in CMake
13
# The error that can emerge without this flag can look like:
14
# "clang : error : overriding '-mmacosx-version-min=11.0' option with '-target x86_64-apple-ios14.0-macabi' [-Werror,-Woverriding-t-option]"
15
if (PLATFORM_NAME STREQUAL "macabi")
16
  add_compile_options(-Wno-overriding-t-option)
17
  add_link_options(-Wno-overriding-t-option)
18
endif()
19

20
# Enable space optimization for gcc/clang
21
# Cannot use "-ffunction-sections -fdata-sections" if we enable bitcode (iOS)
22
if (NOT MSVC AND NOT onnxruntime_ENABLE_BITCODE)
23
  string(APPEND CMAKE_CXX_FLAGS " -ffunction-sections -fdata-sections")
24
  string(APPEND CMAKE_C_FLAGS " -ffunction-sections -fdata-sections")
25
endif()
26

27
if (CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
28
  set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s ALLOW_UNIMPLEMENTED_SYSCALLS=1 -s DEFAULT_TO_CXX=1")
29

30
  # Enable LTO for release single-thread build
31
  if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
32
    # NOTES:
33
    # (1) LTO does not work for WebAssembly multi-thread. (segment fault in worker)
34
    # (2) "-flto=thin" does not work correctly for wasm-ld.
35
    #     we don't set onnxruntime_ENABLE_LTO because it appends flag "-flto=thin"
36
    #     instead, we manually set CMAKE_CXX_FLAGS "-flto"
37
    string(APPEND CMAKE_C_FLAGS " -flto")
38
    string(APPEND CMAKE_CXX_FLAGS " -flto")
39
  endif()
40

41
  if (onnxruntime_ENABLE_WEBASSEMBLY_DEBUG_INFO)
42
    # "-g3" generates DWARF format debug info.
43
    # NOTE: With debug info enabled, web assembly artifacts will be very huge (>1GB). So we offer an option to build without debug info.
44
    set(CMAKE_CXX_FLAGS_DEBUG "-g3")
45
  else()
46
    set(CMAKE_CXX_FLAGS_DEBUG "-g2")
47
  endif()
48

49
  if (onnxruntime_ENABLE_WEBASSEMBLY_SIMD)
50
    string(APPEND CMAKE_C_FLAGS " -msimd128")
51
    string(APPEND CMAKE_CXX_FLAGS " -msimd128")
52
  endif()
53

54
  if (onnxruntime_ENABLE_WEBASSEMBLY_EXCEPTION_CATCHING)
55
    string(APPEND CMAKE_C_FLAGS " -s DISABLE_EXCEPTION_CATCHING=0")
56
    string(APPEND CMAKE_CXX_FLAGS " -s DISABLE_EXCEPTION_CATCHING=0")
57
  endif()
58

59
  # Build WebAssembly with multi-threads support.
60
  if (onnxruntime_ENABLE_WEBASSEMBLY_THREADS)
61
    string(APPEND CMAKE_C_FLAGS " -pthread -Wno-pthreads-mem-growth")
62
    string(APPEND CMAKE_CXX_FLAGS " -pthread -Wno-pthreads-mem-growth")
63
  endif()
64
endif()
65

66
if (onnxruntime_EXTERNAL_TRANSFORMER_SRC_PATH)
67
  add_definitions(-DORT_TRAINING_EXTERNAL_GRAPH_TRANSFORMERS=1)
68
endif()
69

70
# ORT build with as much excluded as possible. Supports ORT flatbuffers models only.
71
if (onnxruntime_MINIMAL_BUILD)
72
  add_compile_definitions(ORT_MINIMAL_BUILD)
73

74
  if (onnxruntime_EXTENDED_MINIMAL_BUILD)
75
    # enable EPs that compile kernels at runtime
76
    add_compile_definitions(ORT_EXTENDED_MINIMAL_BUILD)
77
  endif()
78

79
  if (onnxruntime_MINIMAL_BUILD_CUSTOM_OPS)
80
    add_compile_definitions(ORT_MINIMAL_BUILD_CUSTOM_OPS)
81
  endif()
82

83
  if (MSVC)
84
    # undocumented internal flag to allow analysis of a minimal build binary size
85
    if (ADD_DEBUG_INFO_TO_MINIMAL_BUILD)
86
      string(APPEND CMAKE_CXX_FLAGS " /Zi")
87
      string(APPEND CMAKE_C_FLAGS " /Zi")
88
      string(APPEND CMAKE_SHARED_LINKER_FLAGS " /debug")
89
    endif()
90
  else()
91
    if (CMAKE_HOST_SYSTEM MATCHES "Darwin")
92
      add_link_options(-Wl, -dead_strip)
93
    else()
94
      add_link_options(-Wl,--gc-sections)
95
    endif()
96

97
    if (ADD_DEBUG_INFO_TO_MINIMAL_BUILD)
98
      string(APPEND CMAKE_CXX_FLAGS " -g")
99
      string(APPEND CMAKE_C_FLAGS " -g")
100
    endif()
101
  endif()
102
endif()
103

104
# Enable stream for all the non-minimal build
105
if (NOT onnxruntime_MINIMAL_BUILD)
106
  add_compile_definitions(ORT_ENABLE_STREAM)
107
endif()
108

109
if (onnxruntime_ENABLE_LTO)
110
    include(CheckIPOSupported)
111
    check_ipo_supported(RESULT ipo_enabled OUTPUT ipo_output)
112
    if (NOT ipo_enabled)
113
      message(WARNING "IPO is not supported by this compiler")
114
      set(onnxruntime_ENABLE_LTO OFF)
115
    else()
116
      set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON)
117
    endif()
118
endif()
119

120
if (onnxruntime_REDUCED_OPS_BUILD)
121
  add_compile_definitions(REDUCED_OPS_BUILD)
122
endif()
123

124
if (onnxruntime_DISABLE_EXTERNAL_INITIALIZERS)
125
  add_definitions(-DDISABLE_EXTERNAL_INITIALIZERS=1)
126
endif()
127

128
if (onnxruntime_DISABLE_RTTI)
129
  add_compile_definitions(ORT_NO_RTTI)
130
  if (MSVC)
131
    # Disable RTTI and turn usage of dynamic_cast and typeid into errors
132
    add_compile_options("$<$<COMPILE_LANGUAGE:CXX>:/GR->" "$<$<COMPILE_LANGUAGE:CXX>:/we4541>")
133
  else()
134
    add_compile_options("$<$<COMPILE_LANGUAGE:CXX>:-fno-rtti>")
135
    if (onnxruntime_USE_WEBNN)
136
      # Avoid unboundTypeError for WebNN EP since unbound type names are illegal with RTTI disabled
137
      # in Embind API, relevant issue: https://github.com/emscripten-core/emscripten/issues/7001
138
      add_compile_options("$<$<COMPILE_LANGUAGE:CXX>:-DEMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0>")
139
    endif()
140
  endif()
141
else()
142
  #MSVC RTTI flag /GR is not added to CMAKE_CXX_FLAGS by default. But, anyway VC++2019 treats "/GR" default on.
143
  #So we don't need the following three lines. But it's better to make it more explicit.
144
  if (MSVC)
145
    add_compile_options("$<$<COMPILE_LANGUAGE:CXX>:/GR>")
146
  endif()
147
endif()
148

149
# If this is only enabled in an onnxruntime_ORT_MODEL_FORMAT_ONLY build we don't need ONNX changes
150
# as we (currently) only pull in data_type_utils.cc/h which doesn't throw
151
if (onnxruntime_DISABLE_EXCEPTIONS)
152
  if (NOT onnxruntime_MINIMAL_BUILD)
153
    message(FATAL_ERROR "onnxruntime_MINIMAL_BUILD required for onnxruntime_DISABLE_EXCEPTIONS")
154
  endif()
155

156
  if (onnxruntime_ENABLE_PYTHON)
157
    # pybind11 highly depends on C++ exceptions.
158
    message(FATAL_ERROR "onnxruntime_ENABLE_PYTHON must be disabled for onnxruntime_DISABLE_EXCEPTIONS")
159
  endif()
160
  add_compile_definitions("ORT_NO_EXCEPTIONS")
161
  add_compile_definitions("MLAS_NO_EXCEPTION")
162
  add_compile_definitions("ONNX_NO_EXCEPTIONS")
163
  add_compile_definitions("JSON_NOEXCEPTION")  # https://json.nlohmann.me/api/macros/json_noexception/
164

165
  if (MSVC)
166
    string(REGEX REPLACE "/EHsc" "/EHs-c-" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
167
    # Eigen throw_std_bad_alloc calls 'new' instead of throwing which results in a nodiscard warning.
168
    # It also has unreachable code as there's no good way to avoid EIGEN_EXCEPTIONS being set in macros.h
169
    # TODO: see if we can limit the code this is disabled for.
170
    string(APPEND CMAKE_CXX_FLAGS " /wd4834 /wd4702")
171
    add_compile_definitions("_HAS_EXCEPTIONS=0")
172
  else()
173
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions -fno-unwind-tables -fno-asynchronous-unwind-tables")
174
  endif()
175
endif()
176

177

178
# Guarantee that the Eigen code that you are #including is licensed
179
# under the MPL2 and possibly more permissive licenses (like BSD).
180
add_definitions(-DEIGEN_MPL2_ONLY)
181
if (MSVC)
182
  add_definitions(-DEIGEN_HAS_CONSTEXPR -DEIGEN_HAS_VARIADIC_TEMPLATES -DEIGEN_HAS_CXX11_MATH -DEIGEN_HAS_CXX11_ATOMIC
183
          -DEIGEN_STRONG_INLINE=inline)
184
endif()
185

186
if ( onnxruntime_DONT_VECTORIZE )
187
  add_definitions(-DEIGEN_DONT_VECTORIZE=1)
188
endif()
189

190
if (onnxruntime_CROSS_COMPILING)
191
  set(CMAKE_CROSSCOMPILING ON)
192
  check_cxx_compiler_flag(-Wno-error HAS_NOERROR)
193
  if (HAS_NOERROR)
194
    string(APPEND CMAKE_CXX_FLAGS " -Wno-error=attributes")
195
    string(APPEND CMAKE_C_FLAGS " -Wno-error=attributes")
196
  endif()
197
endif()
198

199
if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9.0)
200
  check_cxx_compiler_flag(-Wno-error HAS_NOERROR)
201
  if (HAS_NOERROR)
202
    string(APPEND CMAKE_CXX_FLAGS " -Wno-error=attributes")
203
    string(APPEND CMAKE_C_FLAGS " -Wno-error=attributes")
204
  endif()
205
endif()
206

207
# Mark symbols to be invisible, for macOS/iOS/visionOS target only
208
# Due to many dependencies have different symbol visibility settings, set global compile flags here.
209
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin|iOS|visionOS")
210
  foreach(flags CMAKE_CXX_FLAGS CMAKE_OBJC_FLAGS CMAKE_OBJCXX_FLAGS)
211
    string(APPEND ${flags} " -fvisibility=hidden -fvisibility-inlines-hidden")
212
  endforeach()
213
endif()
214

215

216
macro(check_nvcc_compiler_flag _FLAG _RESULT)
217
    execute_process(COMMAND ${CUDAToolkit_BIN_DIR}/nvcc "${_FLAG}" RESULT_VARIABLE NVCC_OUT ERROR_VARIABLE NVCC_ERROR)
218
    message("NVCC_ERROR = ${NVCC_ERROR}")
219
    message("NVCC_OUT = ${NVCC_OUT}")
220
    if ("${NVCC_OUT}" MATCHES "0")
221
        set(${_RESULT} 1)
222
    else()
223
        set(${_RESULT} 0)
224
    endif()
225
endmacro()
226

227
#Set global compile flags for all the source code(including third_party code like protobuf)
228
#This section must be before any add_subdirectory, otherwise build may fail because /MD,/MT mismatch
229
if (MSVC)
230
  if (CMAKE_VS_PLATFORM_NAME)
231
    # Multi-platform generator
232
    set(onnxruntime_target_platform ${CMAKE_VS_PLATFORM_NAME})
233
  else()
234
    set(onnxruntime_target_platform ${CMAKE_SYSTEM_PROCESSOR})
235
  endif()
236
  if (onnxruntime_target_platform STREQUAL "ARM64")
237
    set(onnxruntime_target_platform "ARM64")
238
    enable_language(ASM_MARMASM)
239
  elseif (onnxruntime_target_platform STREQUAL "ARM64EC")
240
    enable_language(ASM_MARMASM)
241
  elseif (onnxruntime_target_platform STREQUAL "ARM" OR CMAKE_GENERATOR MATCHES "ARM")
242
    set(onnxruntime_target_platform "ARM")
243
    enable_language(ASM_MARMASM)
244
  elseif (onnxruntime_target_platform STREQUAL "x64" OR onnxruntime_target_platform STREQUAL "x86_64" OR onnxruntime_target_platform STREQUAL "AMD64" OR CMAKE_GENERATOR MATCHES "Win64")
245
    set(onnxruntime_target_platform "x64")
246
    enable_language(ASM_MASM)
247
  elseif (onnxruntime_target_platform STREQUAL "Win32" OR onnxruntime_target_platform STREQUAL "x86" OR onnxruntime_target_platform STREQUAL "i386" OR onnxruntime_target_platform STREQUAL "i686")
248
    set(onnxruntime_target_platform "x86")
249
    enable_language(ASM_MASM)
250
    message("Enabling SAFESEH for x86 build")
251
    set(CMAKE_ASM_MASM_FLAGS "${CMAKE_ASM_MASM_FLAGS} /safeseh")
252
  else()
253
    message(FATAL_ERROR "Unknown CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
254
  endif()
255

256

257
  #Always enable exception handling, even for Windows ARM
258
  if (NOT onnxruntime_DISABLE_EXCEPTIONS)
259
    string(APPEND CMAKE_CXX_FLAGS " /EHsc")
260
    string(APPEND CMAKE_C_FLAGS " /EHsc")
261

262
    string(APPEND CMAKE_CXX_FLAGS " /wd26812")
263
    string(APPEND CMAKE_C_FLAGS " /wd26812")
264
  endif()
265

266
  if (onnxruntime_USE_AVX)
267
    string(APPEND CMAKE_CXX_FLAGS " /arch:AVX")
268
    string(APPEND CMAKE_C_FLAGS " /arch:AVX")
269
  elseif (onnxruntime_USE_AVX2)
270
    string(APPEND CMAKE_CXX_FLAGS " /arch:AVX2")
271
    string(APPEND CMAKE_C_FLAGS " /arch:AVX2")
272
  elseif (onnxruntime_USE_AVX512)
273
    string(APPEND CMAKE_CXX_FLAGS " /arch:AVX512")
274
    string(APPEND CMAKE_C_FLAGS " /arch:AVX512")
275
  endif()
276

277
  if (onnxruntime_ENABLE_LTO AND NOT onnxruntime_USE_CUDA)
278
    set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Gw /GL")
279
    set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /Gw /GL")
280
    set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /Gw /GL")
281
  endif()
282
else()
283
  if (NOT APPLE)
284
    #XXX: Sometimes the value of CMAKE_SYSTEM_PROCESSOR is set but it's wrong. For example, if you run an armv7 docker
285
    #image on an aarch64 machine with an aarch64 Ubuntu host OS, in the docker instance cmake may still report
286
    # CMAKE_SYSTEM_PROCESSOR as aarch64 by default. Given compiling this code may need more than 2GB memory, we do not
287
    # support compiling for ARM32 natively(only support cross-compiling), we will ignore this issue for now.
288
    if(NOT CMAKE_SYSTEM_PROCESSOR)
289
      message(WARNING "CMAKE_SYSTEM_PROCESSOR is not set. Please set it in your toolchain cmake file.")
290
      # Try to detect it
291
      if("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang")
292
        execute_process(
293
		COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
294
		OUTPUT_VARIABLE GCC_DUMP_MACHINE_OUT OUTPUT_STRIP_TRAILING_WHITESPACE
295
		ERROR_VARIABLE _err
296
		RESULT_VARIABLE _res
297
		)
298
		if(NOT _res EQUAL 0)
299
			message(SEND_ERROR "Failed to run 'gcc -dumpmachine':\n ${_res}")
300
		endif()
301
		string(REPLACE "-" ";" GCC_DUMP_MACHINE_OUT_LIST "${GCC_DUMP_MACHINE_OUT}")
302
		list(LENGTH GCC_DUMP_MACHINE_OUT_LIST GCC_TRIPLET_LEN)
303
		if(GCC_TRIPLET_LEN EQUAL 4)
304
		  list(GET GCC_DUMP_MACHINE_OUT_LIST 0 CMAKE_SYSTEM_PROCESSOR)
305
          message("Setting CMAKE_SYSTEM_PROCESSOR to ${CMAKE_SYSTEM_PROCESSOR}")
306
        endif()
307
      endif()
308
    endif()
309
    set(onnxruntime_target_platform ${CMAKE_SYSTEM_PROCESSOR})
310
  endif()
311
  if (onnxruntime_BUILD_FOR_NATIVE_MACHINE)
312
    string(APPEND CMAKE_CXX_FLAGS " -march=native -mtune=native")
313
    string(APPEND CMAKE_C_FLAGS " -march=native -mtune=native")
314
  elseif (onnxruntime_USE_AVX)
315
    string(APPEND CMAKE_CXX_FLAGS " -mavx")
316
    string(APPEND CMAKE_C_FLAGS " -mavx")
317
  elseif (onnxruntime_USE_AVX2)
318
    string(APPEND CMAKE_CXX_FLAGS " -mavx2")
319
    string(APPEND CMAKE_C_FLAGS " -mavx2")
320
  elseif (onnxruntime_USE_AVX512)
321
    string(APPEND CMAKE_CXX_FLAGS " -mavx512f -mavx512cd -mavx512bw -mavx512dq -mavx512vl")
322
    string(APPEND CMAKE_C_FLAGS " -mavx512f -mavx512cd -mavx512bw -mavx512dq -mavx512vl")
323
  endif()
324
  if (CMAKE_SYSTEM_NAME STREQUAL "Android" AND onnxruntime_GCOV_COVERAGE)
325
    string(APPEND CMAKE_CXX_FLAGS " -g -O0 --coverage ")
326
    string(APPEND CMAKE_C_FLAGS   " -g -O0 --coverage ")
327
  endif()
328
  if("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU")
329
    # suppress warnings from flatbuffers
330
    string(APPEND CMAKE_CXX_FLAGS " -Wno-restrict ")
331
    string(APPEND CMAKE_C_FLAGS   " -Wno-restrict ")
332
  endif()
333
  # Check support for AVX and f16c.
334
  include(CheckCXXCompilerFlag)
335
  check_cxx_compiler_flag("-mf16c" COMPILER_SUPPORT_MF16C)
336
  if (NOT COMPILER_SUPPORT_MF16C)
337
    message("F16C instruction set is not supported.")
338
  endif()
339

340
  check_cxx_compiler_flag("-mfma" COMPILER_SUPPORT_FMA)
341
  if (NOT COMPILER_SUPPORT_FMA)
342
    message("FMA instruction set is not supported.")
343
  endif()
344

345
  check_cxx_compiler_flag("-mavx" COMPILER_SUPPORT_AVX)
346
  if (NOT COMPILER_SUPPORT_AVX)
347
    message("AVX instruction set is not supported.")
348
  endif()
349

350
  if (CMAKE_SYSTEM_NAME STREQUAL "Android" AND onnxruntime_ENABLE_TRAINING_APIS)
351
    message("F16C, FMA and AVX flags are not supported on Android for ort training.")
352
  endif()
353

354
  if (NOT (COMPILER_SUPPORT_MF16C AND COMPILER_SUPPORT_FMA AND COMPILER_SUPPORT_AVX) OR
355
    (CMAKE_SYSTEM_NAME STREQUAL "Android" AND onnxruntime_ENABLE_TRAINING_APIS))
356
    message("One or more AVX/F16C instruction flags are not supported. ")
357
    set(onnxruntime_ENABLE_CPU_FP16_OPS FALSE)
358
  endif()
359

360
endif()
361

362
if (WIN32)
363
    # required to be set explicitly to enable Eigen-Unsupported SpecialFunctions
364
    string(APPEND CMAKE_CXX_FLAGS " -DEIGEN_HAS_C99_MATH")
365
elseif(LINUX)
366
    add_compile_definitions("_GNU_SOURCE")
367
endif()
368

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.