NAME="llvm"
DESC="The Low Level Virtual Machine"
VERSION="16.0.5"
FILES=(
  "https://github.com/llvm/llvm-project/releases/download/llvmorg-$VERSION/llvm-$VERSION.src.tar.xz"
  "https://github.com/llvm/llvm-project/releases/download/llvmorg-$VERSION/clang-$VERSION.src.tar.xz"
  "https://www.linuxfromscratch.org/patches/blfs/12.0/clang-$VERSION-enable_default_ssp-1.patch"
  "https://anduin.linuxfromscratch.org/BLFS/llvm/llvm-cmake.src.tar.xz"
  "https://anduin.linuxfromscratch.org/BLFS/llvm/llvm-third-party.src.tar.xz"
)
HASHES=(
  "d9185fc007c32aea27a6de3c7c1eb90d"
  "cb3e79db62c4c3b78cfcdebe66b00268"
  "301fb492352a6f97e344edeaeb64db89fae737db1f5bfd22faf6c11e64fa4e44"
  "356a1aff675d281d7c76165269d33bd5"
  "8b506e49e5fa4c41186ba8ba7da5af82"
)
DEPENDS=()

PACKAGE() {
  tar xf $NAME-$VERSION.src.tar.xz
  cd $NAME-$VERSION.src

  tar -xf ../llvm-cmake.src.tar.xz                                   
  tar -xf ../llvm-third-party.src.tar.xz                             

  sed '/LLVM_COMMON_CMAKE_UTILS/s@../cmake@llvm-cmake.src@'          \
    -i CMakeLists.txt                                              
  sed '/LLVM_THIRD_PARTY_DIR/s@../third-party@llvm-third-party.src@' \
    -i cmake/modules/HandleLLVMOptions.cmake
  grep -rl '#!.*python' | xargs sed -i '1s/python$/python3/'

  tar -xf ../clang-$VERSION.src.tar.xz -C tools
  mv tools/clang-$VERSION.src tools/clang
  patch -Np2 -d tools/clang <../clang-$VERSION-enable_default_ssp-1.patch

  mkdir -v build
  cd       build

  export CFLAGS="-march=x86-64 -mtune=generic"
  cmake -DCMAKE_INSTALL_PREFIX=/usr                 \
      -DLLVM_ENABLE_FFI=ON                          \
      -DCMAKE_BUILD_TYPE=Release                    \
      -DLLVM_BUILD_LLVM_DYLIB=ON                    \
      -DLLVM_LINK_LLVM_DYLIB=ON                     \
      -DLLVM_ENABLE_RTTI=ON                         \
      -DLLVM_TARGETS_TO_BUILD="host;AMDGPU;BPF"     \
      -DLLVM_ENABLE_PROJECTS=""                     \
      -DLLVM_BINUTILS_INCDIR=/usr/include           \
      -DLLVM_INCLUDE_BENCHMARKS=OFF                 \
      -DCLANG_DEFAULT_PIE_ON_LINUX=ON               \
      -Wno-dev -G Ninja ..                     

  mkdir -pv ${ROOTDIR}/usr/bin
  ninja && DESTDIR=${ROOTDIR} ninja install 
  cp bin/FileCheck ${ROOTDIR}/usr/bin

  cd ../.. && rm -rf $NAME-$VERSION.src
}
