# FHElium MLIR compiler: the logical, CKKS, RNS, NTT, collective, memory and
# exec dialects, their passes and conversions, link-plan and key analyses, exec
# schedules, the C API and the Python bindings.
#
# The top-level FHElium project builds this directory; it also configures as a
# standalone project. FHELIUM_MLIR_DIR (default: the FHELIUM_MLIR_DIR
# environment variable) names an LLVM/MLIR installation's lib/cmake/mlir;
# packaging/build_mlir.py builds the pinned installation. The Python package
# fhelium._mlir is installed at FHELIUM_MLIR_PYTHON_INSTALL_DIR.
cmake_minimum_required(VERSION 3.20)
project(fhelium-compiler LANGUAGES CXX C)

set(FHELIUM_LLVM_VERSION_MAJOR 23)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON)
# The extension modules share processes with other LLVM copies, such as
# Triton's, so only their module and C API entry points are exported.
set(CMAKE_C_VISIBILITY_PRESET hidden)
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN ON)

if(NOT FHELIUM_MLIR_DIR AND DEFINED ENV{FHELIUM_MLIR_DIR})
  set(FHELIUM_MLIR_DIR "$ENV{FHELIUM_MLIR_DIR}")
endif()
if(FHELIUM_MLIR_DIR)
  set(MLIR_DIR "${FHELIUM_MLIR_DIR}")
endif()
find_package(MLIR CONFIG)
if(NOT MLIR_FOUND OR NOT LLVM_VERSION_MAJOR EQUAL FHELIUM_LLVM_VERSION_MAJOR)
  message(
    FATAL_ERROR
      "The FHElium compiler requires LLVM/MLIR ${FHELIUM_LLVM_VERSION_MAJOR} "
      "(found: '${LLVM_PACKAGE_VERSION}'). Set FHELIUM_MLIR_DIR to the "
      "installation's lib/cmake/mlir; packaging/build_mlir.py builds the "
      "pinned version.")
endif()
message(STATUS "Using MLIR ${LLVM_PACKAGE_VERSION} from ${MLIR_DIR}")

set(LLVM_RUNTIME_OUTPUT_INTDIR ${PROJECT_BINARY_DIR}/bin)
set(LLVM_LIBRARY_OUTPUT_INTDIR ${PROJECT_BINARY_DIR}/lib)
set(MLIR_BINARY_DIR ${PROJECT_BINARY_DIR})
# The libraries are linked into the Python extensions; only the Python package
# is installed.
set(LLVM_INSTALL_TOOLCHAIN_ONLY ON)
list(APPEND CMAKE_MODULE_PATH "${MLIR_CMAKE_DIR}" "${LLVM_CMAKE_DIR}")
include(TableGen)
include(AddLLVM)
include(AddMLIR)
include(HandleLLVMOptions)

include_directories(${LLVM_INCLUDE_DIRS} ${MLIR_INCLUDE_DIRS}
                    ${PROJECT_SOURCE_DIR}/include ${PROJECT_BINARY_DIR}/include)
add_definitions(${LLVM_DEFINITIONS})

add_subdirectory(include)
add_subdirectory(lib)

# The build tree keeps the package at fhelium/_mlir so that stub generation can
# import it as fhelium._mlir.
set(FHELIUM_MLIR_PYTHON_BUILD_ROOT "${PROJECT_BINARY_DIR}/fhelium/_mlir")
if(NOT DEFINED FHELIUM_MLIR_PYTHON_INSTALL_DIR)
  set(FHELIUM_MLIR_PYTHON_INSTALL_DIR "fhelium/_mlir")
endif()
set(MLIR_PYTHON_PACKAGE_PREFIX
    "fhelium._mlir"
    CACHE STRING "" FORCE)
set(MLIR_BINDINGS_PYTHON_NB_DOMAIN
    "fhelium"
    CACHE STRING "" FORCE)
set(MLIR_BINDINGS_PYTHON_INSTALL_PREFIX
    "${FHELIUM_MLIR_PYTHON_INSTALL_DIR}"
    CACHE STRING "" FORCE)
include(MLIRDetectPythonEnv)
mlir_configure_python_dev_packages()
add_subdirectory(python)
