
CHECK_CXX_SOURCE_COMPILES("
#ifdef _WIN32
#include <intrin.h> /* Workaround for PR19898. */
#include <windows.h>
#endif
int main() {
#ifdef _WIN32
        volatile LONG val = 1;
        MemoryBarrier();
        InterlockedCompareExchange(&val, 0, 1);
        InterlockedIncrement(&val);
        InterlockedDecrement(&val);
#else
        volatile unsigned long val = 1;
        __sync_synchronize();
        __sync_val_compare_and_swap(&val, 1, 0);
        __sync_add_and_fetch(&val, 1);
        __sync_sub_and_fetch(&val, 1);
#endif
        return 0;
      }
" COMPILER_RT_TARGET_HAS_ATOMICS)

CHECK_CXX_SOURCE_COMPILES("
#if defined(__linux__)
#include <unistd.h>
#endif
#include <fcntl.h>
int fd;
int main() {
 struct flock s_flock;

 s_flock.l_type = F_WRLCK;
 fcntl(fd, F_SETLKW, &s_flock);
 return 0;
}

" COMPILER_RT_TARGET_HAS_FCNTL_LCK)

CHECK_CXX_SOURCE_COMPILES("
#include <sys/file.h>

int fd;
int main() {
  flock(fd, LOCK_EX);
  return 0;
}

" COMPILER_RT_TARGET_HAS_FLOCK)

CHECK_CXX_SOURCE_COMPILES("
#include <sys/utsname.h>
int main() {
 return 0;
}

" COMPILER_RT_TARGET_HAS_UNAME)

add_compiler_rt_component(profile)

set(PROFILE_SOURCES
  InstrProfiling.c
  InstrProfilingInternal.c
  InstrProfilingBuffer.c
  InstrProfilingMerge.c
  InstrProfilingMergeFile.c
  InstrProfilingNameVar.c
  InstrProfilingVersionVar.c
  InstrProfilingWriter.c
  InstrProfilingPlatformAIX.c
  InstrProfilingPlatformDarwin.c
  InstrProfilingPlatformFuchsia.c
  InstrProfilingPlatformLinux.c
  InstrProfilingPlatformOther.c
  InstrProfilingPlatformWindows.c
  InstrProfilingPlatformGPU.c
  )

if (NOT COMPILER_RT_PROFILE_BAREMETAL)
  # For baremetal, exclude the following:
  # - Anything that contains filesystem operations (InstrProfilingFile.c,
  #   InstrProfilingUtils.c)
  # - Initialization, because it isn't necesary without the filesystem bits
  #   on ELF targets (InstrProfilingRuntime.cpp).
  # - Value profiling, because it requires malloc (InstrProfilingValue.c).
  #   This could be optional if someone needs it.
  # - GCDA profiling, which is unrelated (GCDAProfiling.c)
  list(APPEND PROFILE_SOURCES
    GCDAProfiling.c
    InstrProfilingFile.c
    InstrProfilingRuntime.cpp
    InstrProfilingUtil.c
    InstrProfilingValue.c
    )
endif()

set(PROFILE_HEADERS
  InstrProfiling.h
  InstrProfilingInternal.h
  InstrProfilingPort.h
  InstrProfilingUtil.h
  WindowsMMap.h
  )

if(WIN32)
  list(APPEND PROFILE_SOURCES
    WindowsMMap.c
  )
endif()

include_directories(..)
include_directories(../../include)

if(FUCHSIA OR UNIX)
 set(EXTRA_FLAGS
     -fPIC
     -Wno-pedantic)
endif()

if(CMAKE_SYSTEM_NAME STREQUAL "WASI")
  set(EXTRA_FLAGS
      ${EXTRA_FLAGS}
      -D_WASI_EMULATED_MMAN
      -D_WASI_EMULATED_GETPID)
endif()

if(COMPILER_RT_TARGET_HAS_ATOMICS)
 set(EXTRA_FLAGS
     ${EXTRA_FLAGS}
     -DCOMPILER_RT_HAS_ATOMICS=1)
endif()

if(COMPILER_RT_TARGET_HAS_FCNTL_LCK)
 set(EXTRA_FLAGS
     ${EXTRA_FLAGS}
     -DCOMPILER_RT_HAS_FCNTL_LCK=1)
endif()

if(COMPILER_RT_TARGET_HAS_FLOCK)
  set(EXTRA_FLAGS
      ${EXTRA_FLAGS}
      -DCOMPILER_RT_HAS_FLOCK=1)
endif()

if(COMPILER_RT_TARGET_HAS_UNAME)
 set(EXTRA_FLAGS
     ${EXTRA_FLAGS}
     -DCOMPILER_RT_HAS_UNAME=1)
endif()

if(COMPILER_RT_PROFILE_BAREMETAL)
 set(EXTRA_FLAGS
     ${EXTRA_FLAGS}
     -DCOMPILER_RT_PROFILE_BAREMETAL=1)
endif()

if(COMPILER_RT_TARGET_AMDGPU OR "${COMPILER_RT_DEFAULT_TARGET_ARCH}" MATCHES "nvptx")
  append_list_if(COMPILER_RT_HAS_FFREESTANDING_FLAG -ffreestanding EXTRA_FLAGS)
  append_list_if(COMPILER_RT_HAS_NOGPULIB_FLAG -nogpulib EXTRA_FLAGS)
  append_list_if(COMPILER_RT_HAS_FLTO_FLAG -flto EXTRA_FLAGS)
  if(COMPILER_RT_TARGET_AMDGPU)
    append_list_if(COMPILER_RT_HAS_CODE_OBJECT_VERSION_FLAG
                   "SHELL:-Xclang -mcode-object-version=none" EXTRA_FLAGS)
  elseif("${COMPILER_RT_DEFAULT_TARGET_ARCH}" MATCHES "nvptx")
    list(APPEND EXTRA_FLAGS --cuda-feature=+ptx63)
  endif()
endif()

if(MSVC)
  # profile historically has only been supported with the static runtime
  # on windows
  set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded)
endif()

# We don't use the C++ Standard Library here, so avoid including it by mistake.
append_list_if(COMPILER_RT_HAS_NOSTDINCXX_FLAG -nostdinc++ EXTRA_FLAGS)
# XRay uses C++ standard library headers.
string(REGEX REPLACE "-?-stdlib=[a-zA-Z+]*" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")

# This appears to be a C-only warning banning the use of locals in aggregate
# initializers. All other compilers accept this, though.
# nonstandard extension used : 'identifier' : cannot be initialized using address of automatic variable
append_list_if(COMPILER_RT_HAS_WD4221_FLAG /wd4221 EXTRA_FLAGS)

# Disable 'nonstandard extension used: translation unit is empty'.
append_list_if(COMPILER_RT_HAS_WD4206_FLAG /wd4206 EXTRA_FLAGS)

# In the GPU runtimes build, link `runtimes-libc-headers` for its
# `-isystem` include dir and for waiting on header generation.
# The target is created at compiler-rt top level from `HandleLibC.cmake`
# when `LLVM_RUNTIMES_BUILD` is set.
set(PROFILE_LINK_LIBS)
if(COMPILER_RT_GPU_BUILD AND TARGET runtimes-libc-headers)
  list(APPEND PROFILE_LINK_LIBS runtimes-libc-headers)
endif()

if(APPLE)
  add_compiler_rt_runtime(clang_rt.profile
    STATIC
    OS ${PROFILE_SUPPORTED_OS}
    ARCHS ${PROFILE_SUPPORTED_ARCH}
    CFLAGS ${EXTRA_FLAGS}
    SOURCES ${PROFILE_SOURCES}
    ADDITIONAL_HEADERS ${PROFILE_HEADERS}
    LINK_LIBS ${PROFILE_LINK_LIBS}
    PARENT_TARGET profile)
else()
  add_compiler_rt_runtime(clang_rt.profile
    STATIC
    ARCHS ${PROFILE_SUPPORTED_ARCH}
    CFLAGS ${EXTRA_FLAGS}
    SOURCES ${PROFILE_SOURCES}
    ADDITIONAL_HEADERS ${PROFILE_HEADERS}
    LINK_LIBS ${PROFILE_LINK_LIBS}
    PARENT_TARGET profile)
endif()

set(PROFILE_ROCM_SUPPORTED_OS OFF)
if("${CMAKE_SYSTEM_NAME}" MATCHES "^(Linux|Windows)$")
  set(PROFILE_ROCM_SUPPORTED_OS ON)
endif()

# clang_rt.profile_rocm: self-contained host-side profile runtime for HIP/ROCm
# device PGO on Linux and Windows. It is a superset of clang_rt.profile (all
# base sources plus InstrProfilingPlatformROCm.cpp and its interceptor
# dependency), built entirely /MD on Windows so a single CRT model holds within
# the archive and clang_rt.profile is left untouched (/MT, no ROCm). The driver
# links it ahead of clang_rt.profile, which then stays inert.
if(COMPILER_RT_BUILD_PROFILE_ROCM AND NOT COMPILER_RT_PROFILE_BAREMETAL
   AND PROFILE_ROCM_SUPPORTED_OS AND COMPILER_RT_HAS_INTERCEPTION
   AND TARGET RTInterception.${COMPILER_RT_DEFAULT_TARGET_ARCH}
   AND TARGET RTSanitizerCommon.${COMPILER_RT_DEFAULT_TARGET_ARCH}
   AND TARGET RTSanitizerCommonLibc.${COMPILER_RT_DEFAULT_TARGET_ARCH})

  set(PROFILE_ROCM_SOURCES ${PROFILE_SOURCES}
    InstrProfilingPlatformROCm.cpp
    InstrProfilingPlatformROCmHSA.cpp)

  # Enables the device-collection call in InstrProfilingFile.c.
  set(PROFILE_ROCM_FLAGS ${EXTRA_FLAGS} -DCOMPILER_RT_BUILD_PROFILE_ROCM=1)

  # The archive is linked from C, so the C++ ROCm source must not emit an
  # exception personality (__gxx_personality_v0).
  append_list_if(COMPILER_RT_HAS_FNO_EXCEPTIONS_FLAG -fno-exceptions
                 PROFILE_ROCM_FLAGS)

  # Optional build-time verification of the mirrored HSA ABI in
  # InstrProfilingPlatformROCmHSA.cpp. HSA is dlopened (never linked), so the
  # declarations are hand-mirrored; when the real ROCm headers happen to be
  # available, compile the static_assert cross-checks against them. This is
  # never a build requirement -- if the package is absent, the checks are simply
  # skipped. Linux only, matching the supplemental HSA drain.
  if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux")
    find_package(hsa-runtime64 QUIET HINTS ${CMAKE_INSTALL_PREFIX} PATHS /opt/rocm)
    if(hsa-runtime64_FOUND)
      get_target_property(_profile_hsa_inc hsa-runtime64::hsa-runtime64
                          INTERFACE_INCLUDE_DIRECTORIES)
      if(_profile_hsa_inc)
        message(STATUS "clang_rt.profile_rocm: verifying HSA ABI against "
                       "${_profile_hsa_inc}")
        list(APPEND PROFILE_ROCM_FLAGS -DPROFILE_VERIFY_HSA_ABI=1)
        foreach(_inc ${_profile_hsa_inc})
          list(APPEND PROFILE_ROCM_FLAGS "-isystem${_inc}")
        endforeach()
      endif()
    endif()
  endif()

  # The interceptor path needs sanitizer_common symbols; merge the same object
  # libs as clang_rt.cfi so the archive stays self-contained.
  set(PROFILE_ROCM_OBJECT_LIBS
    RTInterception
    RTSanitizerCommon
    RTSanitizerCommonLibc)

  if(MSVC)
    # These merged object libs are built /MD; match it so the archive is
    # CRT-consistent. clang_rt.profile stays /MT.
    set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreadedDLL)
  endif()

  add_compiler_rt_runtime(clang_rt.profile_rocm
    STATIC
    ARCHS ${PROFILE_SUPPORTED_ARCH}
    OBJECT_LIBS ${PROFILE_ROCM_OBJECT_LIBS}
    CFLAGS ${PROFILE_ROCM_FLAGS}
    SOURCES ${PROFILE_ROCM_SOURCES}
    ADDITIONAL_HEADERS ${PROFILE_HEADERS}
    LINK_LIBS ${PROFILE_LINK_LIBS}
    PARENT_TARGET profile)
endif()
