# Modifications Copyright (c) 2024-2026 Advanced Micro Devices, Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# 3.15 is the minimum.
# 3.17 for NVC++.
# 3.18 for C++17 + CUDA and clang-cuda support.
# 3.21 is for HIP
cmake_minimum_required(VERSION 3.21)

# Determine whether libhipcxx is the top-level project or included into
# another project via add_subdirectory().
if ("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_LIST_DIR}")
  set(LIBCUDACXX_TOPLEVEL_PROJECT ON)
endif()

if (LIBCUDACXX_TOPLEVEL_PROJECT)
  cmake_minimum_required(VERSION 3.21)
endif()

set(PACKAGE_NAME libhipcxx)
set(PACKAGE_VERSION 11.0)
set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}")

project(libhipcxx LANGUAGES CXX VERSION 3.4.0)

# Expose libcudacxx_SOURCE_DIR / libcudacxx_BINARY_DIR for parity with the
# upstream libcudacxx project name; lets all libhipcxx CMake code use the
# upstream variable name so vendored cmake/Libcudacxx*.cmake helpers stay
# byte-identical. Without the BINARY_DIR alias, code in subdirectories
# (notably codegen/CMakeLists.txt) that interpolates ${libcudacxx_BINARY_DIR}
# expands to an empty string, which silently produces broken absolute paths
# beginning with '/' (e.g. '/codegen/cuda_ptx_generated.h').
set(libcudacxx_SOURCE_DIR "${libhipcxx_SOURCE_DIR}")
set(libcudacxx_BINARY_DIR "${libhipcxx_BINARY_DIR}")

# rocm-cmake contains common cmake code for rocm projects to help
# setup and install
include(cmake/FindROCMCmake.cmake)
include(ROCMSetupVersion)
include(ROCMCreatePackage)
include(ROCMInstallTargets)
# include(ROCMPackageConfigHelpers)
# include(ROCMInstallSymlinks)
# include(ROCMHeaderWrapper)
# include(ROCMCheckTargetIds)
# include(ROCMClients)
option(libhipcxx_ENABLE_INSTALL_RULES "Enable installation of libcu++" ${LIBCUDACXX_TOPLEVEL_PROJECT})
if (libhipcxx_ENABLE_INSTALL_RULES)
  include(cmake/libhipcxxInstallRules.cmake)
endif()

# Define libhipcxx::libhipcxx from this source tree on every configure.
# add_subdirectory consumers stop below. The top-level build must define the
# same target: installed rocThrust links libhipcxx::libhipcxx, and
# find_package(libhipcxx) would select the headers installed under
# include/hipccl. The source config returns immediately when the target
# already exists.
include(cmake/libhipcxxAddSubdir.cmake)
if (NOT LIBCUDACXX_TOPLEVEL_PROJECT)
  return()
endif()

# Must be called in root CMakeLists.txt
include(CTest)
enable_testing()

# Add codegen module
option(
  libcudacxx_ENABLE_CODEGEN
  "Enable libcudacxx's atomics backend codegen and tests."
  OFF
)
if (libcudacxx_ENABLE_CODEGEN)
  add_subdirectory(codegen)
endif()

# NOTE(HIP/AMD): libhipcxx-specific cmake test option (not in upstream CCCL).
# The subdirectory itself is added further down, once LIBCUDACXX_ENABLE_HIP and
# find_package(hip) have run -- it needs both to pick hipcc for the exported-package
# consumer project.
option(libhipcxx_ENABLE_CMAKE_TESTS "Enable ctest-based testing." ON)

list(PREPEND CMAKE_MODULE_PATH "${libcudacxx_SOURCE_DIR}/cmake")
set(LLVM_PATH "${libcudacxx_SOURCE_DIR}" CACHE STRING "" FORCE)

# Configuration options.
option(LIBCUDACXX_ENABLE_CUDA "Enable the CUDA language support." OFF)
option(LIBCUDACXX_ENABLE_HIP "Enable the HIP language support." ON)

# NOTE(HIP/AMD): the hipCUB-backed pstl device backend is experimental and off by
# default -- see the rationale in <cuda/std/__internal/pstl_config.h>. Turning this
# on defines LIBHIPCXX_ENABLE_EXPERIMENTAL_HIPCUB_SHIM for everything that links
# libcudacxx.compiler_interface. Consumers of an installed libhipcxx are not
# covered by this option and must define the macro in their own build.
option(
  LIBCUDACXX_ENABLE_EXPERIMENTAL_HIPCUB_SHIM
  "Enable the experimental hipCUB-backed parallel algorithm backend."
  OFF
)

if (LIBCUDACXX_ENABLE_CUDA AND LIBCUDACXX_ENABLE_HIP)
  message(FATAL_ERROR "HIP and CUDA compilers cannot be used at the same time, CMake will exit." )
endif()

if (LIBCUDACXX_ENABLE_CUDA)
  message(FATAL_ERROR "CUDA backend support is currently not supported. CMake will exit.")
endif()

if (LIBCUDACXX_ENABLE_CUDA)
  enable_language(CUDA)
elseif (LIBCUDACXX_ENABLE_HIP)
  # sync variables used by HIP CMake package etc.
  if ("${AMDGPU_TARGETS}" STREQUAL "")
    set(AMDGPU_TARGETS ${CMAKE_HIP_ARCHITECTURES})
  elseif(NOT "${AMDGPU_TARGETS}" STREQUAL "${CMAKE_HIP_ARCHITECTURES}")
    message(WARNING "mismatch between CMAKE_HIP_ARCHITECTURES and AMDGPU_TARGETS! Using AMDGPU_TARGETS! CMAKE_HIP_ARCHITECTURES='${CMAKE_HIP_ARCHITECTURES}', AMDGPU_TARGETS='${AMDGPU_TARGETS}'")
    set(CMAKE_HIP_ARCHITECTURES ${AMDGPU_TARGETS})
  endif()
  if ("${GPU_TARGETS}" STREQUAL "")
    set(GPU_TARGETS ${CMAKE_HIP_ARCHITECTURES})
  elseif(NOT "${GPU_TARGETS}" STREQUAL "${CMAKE_HIP_ARCHITECTURES}")
    message(WARNING "mismatch between CMAKE_HIP_ARCHITECTURES and GPU_TARGETS! Using GPU_TARGETS! CMAKE_HIP_ARCHITECTURES='${CMAKE_HIP_ARCHITECTURES}', GPU_TARGETS='${GPU_TARGETS}'")
    set(CMAKE_HIP_ARCHITECTURES ${GPU_TARGETS})
  endif()

  find_package(hip REQUIRED)
  enable_language(HIP)
endif ()

if (libhipcxx_ENABLE_CMAKE_TESTS)
  add_subdirectory(cmake/test)
endif()

# For Windows we should avoid symlinks by copying the file content (test, utils, and include/hip folder)
function(libhipcxx_path_is_link_like path out_var)
  if(IS_SYMLINK "${path}")
    set(${out_var} TRUE PARENT_SCOPE)
    return()
  endif()

  if(NOT WIN32 OR NOT EXISTS "${path}")
    set(${out_var} FALSE PARENT_SCOPE)
    return()
  endif()

  if(NOT IS_DIRECTORY "${path}")
    set(${out_var} TRUE PARENT_SCOPE)
    return()
  endif()

  get_filename_component(_abs_path "${path}" ABSOLUTE)
  file(REAL_PATH "${path}" _real_path)
  file(TO_CMAKE_PATH "${_abs_path}" _abs_path_norm)
  file(TO_CMAKE_PATH "${_real_path}" _real_path_norm)
  string(REGEX REPLACE "/$" "" _abs_path_norm "${_abs_path_norm}")
  string(REGEX REPLACE "/$" "" _real_path_norm "${_real_path_norm}")
  string(TOLOWER "${_abs_path_norm}" _abs_path_lc)
  string(TOLOWER "${_real_path_norm}" _real_path_lc)

  if(NOT _abs_path_lc STREQUAL _real_path_lc)
    set(${out_var} TRUE PARENT_SCOPE)
  else()
    set(${out_var} FALSE PARENT_SCOPE)
  endif()
endfunction()

# OFF (default): no source-tree modification. On Win32 without
# LIBHIPCXX_COPY_TO_BUILD this requires working git symlinks in the
# source checkout (developer mode / core.symlinks=true). ON: legacy
# in-source fixup.
option(LIBHIPCXX_WIN32_REMOVE_SRC_SYMLINKS
  "On Win32, remove symlinks in the source tree and add copy of the target folder instead (modifies git-tracked files)." OFF)

# ON: copy the source tree into the build folder (TheRock tester needs
# this to re-configure/build/run lit from the build artifact). On Win32
# the copy is also the symlink-fixup target when REMOVE_SRC_SYMLINKS is OFF.
option(LIBHIPCXX_COPY_TO_BUILD
  "Copy source tree into build folder (set by TheRock; required for the tester pipeline)." OFF)

if(LIBHIPCXX_COPY_TO_BUILD)
  get_filename_component(_libhipcxx_src_name "${CMAKE_CURRENT_SOURCE_DIR}" NAME)
  set(_libhipcxx_build_src_copy "${CMAKE_CURRENT_BINARY_DIR}/${_libhipcxx_src_name}")
  file(COPY "${CMAKE_CURRENT_SOURCE_DIR}" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}")
endif()

# Win32: assemble fixup targets (source, build copy, both, or none).
set(_libhipcxx_win32_fixup_dirs)
if(WIN32)
  if(LIBHIPCXX_WIN32_REMOVE_SRC_SYMLINKS)
    list(APPEND _libhipcxx_win32_fixup_dirs "${CMAKE_CURRENT_SOURCE_DIR}")
  endif()
  if(LIBHIPCXX_COPY_TO_BUILD)
    list(APPEND _libhipcxx_win32_fixup_dirs "${_libhipcxx_build_src_copy}")
  endif()
endif()

# NOTE(HIP/AMD): 'test' and 'utils' are regular directories now (no longer
# symlinks into .upstream-tests/), so 'include/libhipcxx/hip' is the only
# symlink left to resolve.
foreach(_dir IN LISTS _libhipcxx_win32_fixup_dirs)
  message(STATUS "Resolving Win32 symlinks in: ${_dir}")
  libhipcxx_path_is_link_like("${_dir}/include/libhipcxx/hip" _is_link)
  if(_is_link)
    file(REMOVE_RECURSE "${_dir}/include/libhipcxx/hip")
  endif()
  file(MAKE_DIRECTORY "${_dir}/include/libhipcxx/hip")
  file(COPY "${_dir}/include/cuda/" DESTINATION "${_dir}/include/libhipcxx/hip/")
endforeach()

option(LIBCUDACXX_ENABLE_LIBCUDACXX_TESTS "Enable libcu++ tests." ON)
# NOTE(HIP/AMD): the CCCL dependency infrastructure set up in this block
# (cccl_build_compiler_targets, CCCLGetDependencies' cccl_get_* macros,
# CCCL_{SOURCE,BINARY}_DIR, CCCL::CCCL, the dialect defaults and
# libcudacxx_build_compiler_targets) is required by BOTH the libcu++ tests AND
# the benchmarks (benchmarks/cmake/CCCLBenchmarkRegistry.cmake calls
# cccl_get_cudatoolkit(), nvbench_helper/ calls cccl_get_nvbench()/_cub()/...).
# In an upstream CCCL build the parent project provides it; libhipcxx is
# standalone, so set it up whenever tests OR benchmarks are enabled. The
# test-only pieces (header-testing helpers + add_subdirectory(test)) remain
# guarded on LIBCUDACXX_ENABLE_LIBCUDACXX_TESTS below.
if (LIBCUDACXX_ENABLE_LIBCUDACXX_TESTS OR CCCL_ENABLE_BENCHMARKS)
  enable_testing()

  # Pull in the CCCL infrastructure that our Libcudacxx*.cmake helpers
  # depend on. In the upstream CCCL workflow these are loaded by the parent
  # CCCL CMakeLists.txt before libcudacxx is added as a subdirectory; since
  # libhipcxx is a standalone project we load them here directly.
  # - AppendOptionIfAvailable.cmake provides append_option_if_available()
  # - CCCLBuildCompilerTargets.cmake provides cccl_build_compiler_interface()
  #   and cccl_build_compiler_targets() which creates the
  #   cccl.compiler_interface_cppXX targets that libcudacxx links against.
  # - CCCLConfigureTarget.cmake provides cccl_configure_target() used by the
  #   header-testing helpers below.
  # CCCL_{SOURCE,BINARY}_DIR are referenced by some cccl_get_* macros
  # (e.g. cccl_get_c2h() pulls add_subdirectory("${CCCL_SOURCE_DIR}/c2h"
  # "${CCCL_BINARY_DIR}/c2h")). In a normal CCCL parent build these get
  # set by the parent CMakeLists.txt; libhipcxx is standalone so we
  # alias them to our own source / binary directories. Must precede the
  # includes: CCCLConfigureTarget.cmake reads CCCL_BINARY_DIR at include time.
  if (NOT DEFINED CCCL_SOURCE_DIR)
    set(CCCL_SOURCE_DIR "${libcudacxx_SOURCE_DIR}")
  endif()
  if (NOT DEFINED CCCL_BINARY_DIR)
    set(CCCL_BINARY_DIR "${CMAKE_BINARY_DIR}")
  endif()

  include(cmake/AppendOptionIfAvailable.cmake)
  include(cmake/CCCLBuildCompilerTargets.cmake)
  include(cmake/CCCLConfigureTarget.cmake)
  include(cmake/CCCLGetDependencies.cmake)
  # NOTE(HIP/AMD): CCCLEnsureMetaTargets/CCCLAddExecutable/CCCLAddTidyTarget are
  # dependencies of CCCLGenerateHeaderTests; in a full CCCL parent build these
  # are loaded by the top-level CCCL CMakeLists.txt. In the standalone libhipcxx
  # build we must include them explicitly before the header-test cmake files.
  include(cmake/CCCLEnsureMetaTargets.cmake)
  include(cmake/CCCLAddTidyTarget.cmake)
  include(cmake/CCCLAddExecutable.cmake)
  include(cmake/CCCLGenerateHeaderTests.cmake)
  cccl_build_compiler_targets()

  # On HIP we ship a Catch2-only stripped-down c2h (see c2h/CMakeLists.txt)
  # that does not pull thrust / cub / cudaToolkit. The upstream
  # c2h/CMakeLists.txt links cccl.c2h against CCCL::CCCL (the umbrella
  # target normally provided by find_package(CCCL) -- which would also
  # transitively try to find CUB, Thrust, ...). On HIP we don't have
  # any of that, so pre-define CCCL::CCCL as an alias for
  # libcudacxx::libcudacxx (the only CCCL component we ship under HIP)
  # and have the c2h CMakeLists skip the find_package(CCCL) call on
  # HIP. The libcudacxx::libcudacxx target is created by the libcudacxx
  # package config below.
  if (LIBCUDACXX_ENABLE_HIP AND NOT TARGET CCCL::CCCL)
    include("${libcudacxx_SOURCE_DIR}/lib/cmake/libcudacxx/libcudacxx-config-version.cmake")
    include("${libcudacxx_SOURCE_DIR}/lib/cmake/libcudacxx/libcudacxx-config.cmake")
    # NOTE(HIP/AMD): in 3.2.1+ 'libcudacxx::libcudacxx' is itself an ALIAS, and
    # CMake forbids aliasing an alias. Create CCCL::CCCL as a real INTERFACE
    # IMPORTED target that links the alias instead.
    add_library(CCCL::CCCL INTERFACE IMPORTED GLOBAL)
    target_link_libraries(CCCL::CCCL INTERFACE libcudacxx::libcudacxx)
  endif()

  # libcudacxx_build_compiler_targets() links libcudacxx.compiler_interface
  # against cccl.compiler_interface_cpp${CMAKE_CUDA_STANDARD}. When CUDA is
  # not enabled (HIP-only build) CMAKE_CUDA_STANDARD is empty and the link
  # resolves to a non-existent target. Default to 17 to mirror the upstream
  # libcudacxx CMakePresets baseline.
  if (NOT CMAKE_CUDA_STANDARD)
    set(CMAKE_CUDA_STANDARD 17)
  endif()

  # NOTE(HIP/AMD): cccl_configure_target() is invoked without an explicit
  # DIALECT for the header-test targets (upstream form), so it falls back to
  # the global CMAKE_CXX_STANDARD. In the standalone libhipcxx build (no CCCL
  # parent) that variable is otherwise empty, which makes
  # set_target_properties(... CXX_STANDARD ${CMAKE_CXX_STANDARD} ...) fail.
  # Default to the libcudacxx C++17 baseline.
  if (NOT CMAKE_CXX_STANDARD)
    set(CMAKE_CXX_STANDARD 17)
  endif()

  # Create the compiler targets with the common compile flags
  include(cmake/LibcudacxxBuildCompilerTargets.cmake)
  libcudacxx_build_compiler_targets()

  if (LIBCUDACXX_ENABLE_LIBCUDACXX_TESTS)
    # Test all public and internal headers. The upstream helpers below
    # are HIP-aware (they tag the configured TUs with LANGUAGE HIP and
    # apply a HIP-side skip list when LIBCUDACXX_ENABLE_HIP is set), so
    # they can be included unconditionally for both CUDA and HIP builds.
    include(cmake/LibcudacxxInternalHeaderTesting.cmake)
    include(cmake/LibcudacxxPublicHeaderTesting.cmake)
    include(cmake/LibcudacxxPublicHeaderTestingHost.cmake)

    # On Win32 with the build copy available and no source modification use the build folder
    # (the build copy has no symlinks but a copy of the target folders).
    if(WIN32 AND LIBHIPCXX_COPY_TO_BUILD AND NOT LIBHIPCXX_WIN32_REMOVE_SRC_SYMLINKS)
      set(libhipcxx_SOURCE_DIR "${_libhipcxx_build_src_copy}")
      set(libcudacxx_SOURCE_DIR "${libhipcxx_SOURCE_DIR}")
      add_subdirectory("${libhipcxx_SOURCE_DIR}/test" "${CMAKE_CURRENT_BINARY_DIR}/test")
    else()
      add_subdirectory(test)
    endif()
  endif()
endif()

if (CCCL_ENABLE_BENCHMARKS)
  add_subdirectory(benchmarks)
endif()

# Package configuration
set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")

set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE.TXT")
set(CPACK_RPM_PACKAGE_LICENSE "ASL 2.0 AND MIT")

if(NOT CPACK_PACKAGING_INSTALL_PREFIX)
  set(CPACK_PACKAGING_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
endif()

set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "\${CPACK_PACKAGING_INSTALL_PREFIX}" )

rocm_create_package(
  NAME libhipcxx
  DESCRIPTION "ROCm libhipcxx library"
  # FIXME(HIP/AMD): A maintainer string is required
  # Set to the following when available:
  # MAINTAINER "libhipcxx-maintainer@amd.com"
  MAINTAINER "AMD, Inc."
  HEADER_ONLY
)
