include(utils/CompilerUtils)

test_and_set_c_compiler_flag_global(-std=c89)
test_and_set_c_compiler_flag_global(-Wall)
# -Wextra may fail on clobbered warning due to pthread_cleanup
test_and_set_c_compiler_flag_global(-Wno-clobbered)
test_and_set_c_compiler_flag_global(-Wextra)
# explicitly add other flags in -Wextra
test_and_set_c_compiler_flag_global(-Wempty-body)
test_and_set_c_compiler_flag_global(-Wignored-qualifiers)
test_and_set_c_compiler_flag_global(-Wimplicit-fallthrough=4)
test_and_set_c_compiler_flag_global(-Wmissing-field-initializers)
test_and_set_c_compiler_flag_global(-Wmissing-parameter-type)
test_and_set_c_compiler_flag_global(-Wold-style-declaration)
test_and_set_c_compiler_flag_global(-Woverride-init)
test_and_set_c_compiler_flag_global(-Wsign-compare)
test_and_set_c_compiler_flag_global(-Wtype-limits)
test_and_set_c_compiler_flag_global(-Wuninitialized)
test_and_set_c_compiler_flag_global(-Wshift-negative-value)
test_and_set_c_compiler_flag_global(-Wunused-parameter)
test_and_set_c_compiler_flag_global(-Wunused-but-set-parameter)
test_and_set_c_compiler_flag_global(-Werror)
test_and_set_c_compiler_flag_global(-Wundef)
test_and_set_c_compiler_flag_global(-Wpointer-arith)
test_and_set_c_compiler_flag_global(-Wstrict-prototypes)
test_and_set_c_compiler_flag_global(-Wvla)
test_and_set_c_compiler_flag_global(-Wswitch-default)
test_and_set_c_compiler_flag_global(-Wreturn-type)
test_and_set_c_compiler_flag_global(-Wunreachable-code)
test_and_set_c_compiler_flag_global(-Wdeclaration-after-statement)
test_and_set_c_compiler_flag_global(-Winfinite-recursion)
test_and_set_c_compiler_flag_global(-fmax-errors=5)

if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE "Release" CACHE STRING
      "Build type (Release, Debug, DebugASan, DebugTSan, DebugLSan, DebugUSan, DebugAnalyzer)" FORCE)
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
  test_and_set_c_compiler_flag_global(-O3)
elseif(CMAKE_BUILD_TYPE STREQUAL "Debug")
  test_and_set_c_compiler_flag_global(-g)
elseif(CMAKE_BUILD_TYPE STREQUAL "DebugASan")
  test_and_set_c_compiler_flag_global(-g)
  test_and_set_c_compiler_flag_global(-fsanitize=address)
  add_link_options(-fsanitize=address)
elseif(CMAKE_BUILD_TYPE STREQUAL "DebugTSan")
  test_and_set_c_compiler_flag_global(-g)
  test_and_set_c_compiler_flag_global(-fsanitize=thread)
  add_link_options(-fsanitize=thread)
elseif(CMAKE_BUILD_TYPE STREQUAL "DebugLSan")
  test_and_set_c_compiler_flag_global(-g)
  test_and_set_c_compiler_flag_global(-fsanitize=leak)
  add_link_options(-fsanitize=leak)
elseif(CMAKE_BUILD_TYPE STREQUAL "DebugUSan")
  test_and_set_c_compiler_flag_global(-g)
  test_and_set_c_compiler_flag_global(-fsanitize=undefined)
  add_link_options(-fsanitize=undefined)
elseif(CMAKE_BUILD_TYPE STREQUAL "DebugAnalyzer")
  test_and_set_c_compiler_flag_global(-g)
  test_and_set_c_compiler_flag_global(-fanalyzer)
else()
  message(FATAL_ERROR "Unknown build type ${CMAKE_BUILD_TYPE}")
endif()
