cmake_minimum_required(VERSION 3.21)
project(gecode_allocator_consumer LANGUAGES C CXX)
enable_testing()
find_package(Gecode CONFIG REQUIRED COMPONENTS support)
find_package(Threads REQUIRED)

set(GECODE_LINK_VARIANT shared CACHE STRING "Installed Gecode variant: shared or static")
option(GECODE_EXPECT_MIMALLOC "Require the mimalloc backend" OFF)
set(MIMALLOC_SOURCE_DIR "" CACHE PATH "Mimalloc sources for the host allocator coexistence check")
option(GECODE_HOST_MIMALLOC_OVERRIDE "Let the host mimalloc replace malloc" OFF)
if(GECODE_LINK_VARIANT STREQUAL "shared")
  add_library(allocator-boundary SHARED boundary.cpp)
elseif(GECODE_LINK_VARIANT STREQUAL "static")
  add_library(allocator-boundary STATIC boundary.cpp)
  target_compile_definitions(allocator-boundary PUBLIC ALLOCATOR_BOUNDARY_STATIC)
else()
  message(FATAL_ERROR "GECODE_LINK_VARIANT must be shared or static")
endif()
target_compile_definitions(allocator-boundary PRIVATE ALLOCATOR_BOUNDARY_BUILD)
target_link_libraries(allocator-boundary PUBLIC Gecode::gecodesupport_${GECODE_LINK_VARIANT})
add_executable(allocator-consumer main.cpp)
target_link_libraries(allocator-consumer PRIVATE allocator-boundary Threads::Threads)
target_compile_definitions(allocator-consumer PRIVATE GECODE_EXPECT_MIMALLOC=$<BOOL:${GECODE_EXPECT_MIMALLOC}>)
if(GECODE_EXPECT_MIMALLOC)
  if(NOT EXISTS "${MIMALLOC_SOURCE_DIR}/include/mimalloc.h")
    message(FATAL_ERROR "The host allocator check requires MIMALLOC_SOURCE_DIR")
  endif()
  # Embed the complete object so macOS includes malloc-zone registration.
  set(CMAKE_POLICY_DEFAULT_CMP0126 NEW)
  set(MI_OVERRIDE ${GECODE_HOST_MIMALLOC_OVERRIDE})
  set(MI_BUILD_SHARED OFF)
  set(MI_BUILD_STATIC OFF)
  set(MI_BUILD_OBJECT ON)
  set(MI_BUILD_TESTS OFF)
  set(MI_OPT_ARCH OFF)
  add_subdirectory("${MIMALLOC_SOURCE_DIR}" host-mimalloc EXCLUDE_FROM_ALL)
  get_directory_property(host_mi_libraries DIRECTORY "${MIMALLOC_SOURCE_DIR}" DEFINITION mi_libraries)
  target_link_libraries(allocator-consumer PRIVATE mimalloc-obj ${host_mi_libraries})
  target_compile_definitions(allocator-consumer PRIVATE CHECK_HOST_MIMALLOC
    GECODE_HOST_MIMALLOC_OVERRIDE=$<BOOL:${GECODE_HOST_MIMALLOC_OVERRIDE}>)
endif()
add_test(NAME allocator-consumer COMMAND allocator-consumer)
