diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9066ebda4..24e303cf4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,7 +3,7 @@ name: Build and test on: push: branches: - - "*" + - "*" pull_request: branches: - "*" @@ -12,78 +12,134 @@ jobs: build: strategy: matrix: - name: [ubuntu-gcc-10, - ubuntu-gcc-11, - ubuntu-gcc-12, - ubuntu-clang-15, - macos-xcode-14-intel, - macos-xcode-14-arm, + name: [ubuntu-gcc-12, + ubuntu-gcc-13, + ubuntu-gcc-14, + ubuntu-gcc-15, + ubuntu-gcc-15-debug, +# ubuntu-gcc-14-arm, + ubuntu-clang-17, + ubuntu-clang-19, + macos-intel, + macos-xcode16-arm, + macos-xcode26-arm, windows ] include: - - name: ubuntu-gcc-10 - os: ubuntu-20.04 + + - name: ubuntu-gcc-12 + os: ubuntu-22.04 compiler: gcc - version: "10" - buildtype: "release" + version: "12" arch: "linux64" - - name: ubuntu-gcc-11 - os: ubuntu-22.04 + - name: ubuntu-gcc-13 + os: ubuntu-24.04 compiler: gcc - version: "11" - buildtype: "release" + version: "13" arch: "linux64" - - name: ubuntu-gcc-12 - os: ubuntu-22.04 + - name: ubuntu-gcc-14 + os: ubuntu-24.04 compiler: gcc - version: "12" - buildtype: "release" + version: "14" arch: "linux64" - - name: ubuntu-clang-15 - os: ubuntu-22.04 - compiler: clang + - name: ubuntu-gcc-15 + os: ubuntu-24.04 + compiler: gcc + version: "14" + buildtype: "Release" + arch: "linux64" + image: ubuntu:25.04 + + - name: ubuntu-gcc-15-debug + os: ubuntu-24.04 + compiler: gcc version: "15" - buildtype: "release" + buildtype: "Debug" + arch: "linux64" + image: ubuntu:25.04 + +# "Failed to obtain BEAGLE instance" on some tests. +# - name: ubuntu-gcc-14-arm +# os: ubuntu-24.04-arm +# compiler: gcc +# version: "14" +# arch: "linux64" + + - name: ubuntu-clang-17 + os: ubuntu-24.04 + compiler: clang + version: "17" + buildtype: "Release" + arch: "linux64" + + - name: ubuntu-clang-19 + os: ubuntu-24.04 + compiler: clang + version: "19" + buildtype: "Release" arch: "linux64" - - name: macos-xcode-14-intel - os: macos-12 + - name: macos-intel + os: macos-15-intel compiler: xcode - version: "14" - buildtype: "release" + version: "16" arch: "mac-intel64" - - name: macos-xcode-14-arm - os: macos-14 + - name: macos-xcode16-arm + os: macos-15 compiler: xcode - version: "14" - buildtype: "release" + version: "16" + arch: "mac-arm64" + + - name: macos-xcode26-arm + os: macos-latest + compiler: xcode + version: "26" arch: "mac-arm64" - name: windows - os: ubuntu-22.04 + os: ubuntu-24.04 compiler: mingw version: "N/A" - buildtype: "release" arch: "win64" runs-on: ${{ matrix.os }} + container: + image: ${{ matrix.image || '' }} steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: - python-version: 3.12.0 + python-version: 3.12 + + # Caches for different branches are isolated, so we don't need to put the branch name into the key. + # The total size for all caches in a repository is 5Gb. + + - name: Set CMake build type + run: | + # Portable binaries: with -march=native, ccache would reuse objects built on one runner's CPU on + # another runner's ("Illegal instruction"). + CMAKE_ARGS="-DBEAGLE_OPTIMIZE_FOR_NATIVE_ARCH=OFF" + if [ -n "${{ matrix.buildtype }}" ] ; then + CMAKE_ARGS="${CMAKE_ARGS} -DCMAKE_BUILD_TYPE=${{ matrix.buildtype }}" + fi + echo "CMAKE_ARGS=${CMAKE_ARGS}" >> $GITHUB_ENV - - name: Install (Linux) + - name: Install utilities (Linux) if: runner.os == 'Linux' && matrix.name != 'windows' run: | + # If we're running in a docker image, we are already root + if [ -n "${{ matrix.image }}" ] ; then + apt-get update && apt-get install -y sudo build-essential git cmake + fi + sudo apt-get update sudo apt-get install -y cmake ninja-build ccache pkg-config - sudo apt-get install -y openjdk-17-jdk libeigen3-dev ocl-icd-opencl-dev + sudo apt-get install -y openjdk-17-jdk libeigen3-dev if [ "${{ matrix.compiler }}" = "gcc" ]; then # For newer GCCs, maybe. @@ -97,21 +153,17 @@ jobs: sudo apt-get install -y clang-${{ matrix.version }} echo "CC=ccache clang-${{ matrix.version }}" >> $GITHUB_ENV echo "CXX=ccache clang++-${{ matrix.version }}" >> $GITHUB_ENV - echo "CMAKE_ARGS=-DBUILD_OPENMP=OFF" >> $GITHUB_ENV + echo "CMAKE_ARGS=${CMAKE_ARGS} -DBUILD_OPENMP=OFF" >> $GITHUB_ENV fi - - name: Install (Linux -> Windows [cross]) + - name: Install utilities (Linux -> Windows [cross]) if: matrix.name == 'windows' run: | - # For mingw/gcc-12. - cat /etc/apt/sources.list - sudo sed -i 's/jammy/lunar/g' /etc/apt/sources.list - sudo apt-get update sudo apt-get install -y cmake ninja-build ccache pkg-config sudo apt-get install -y dos2unix g++-mingw-w64 mingw-w64-tools wine64 zstd - echo "CMAKE_ARGS=-DBUILD_ACTION=OFF -DBUILD_JNI=OFF -DBUILD_OPENMP=OFF -DCMAKE_TOOLCHAIN_FILE=scripts/mingw-w64-x86_64.cmake" >> $GITHUB_ENV + echo "CMAKE_ARGS=${CMAKE_ARGS} -DBUILD_ACTION=OFF -DBUILD_JNI=OFF -DBUILD_OPENMP=OFF -DCMAKE_TOOLCHAIN_FILE=scripts/mingw-w64-x86_64.cmake" >> $GITHUB_ENV - name: Select XCode version (macOS) if: runner.os == 'macOS' @@ -119,44 +171,23 @@ jobs: with: xcode-version: ${{ matrix.version }} - - name: Install (macOS) + - name: Install utilities (macOS) if: runner.os == 'macOS' run: | - brew install cmake ninja pkg-config ccache coreutils eigen openjdk + brew install ninja pkg-config ccache coreutils eigen openjdk echo "CC=ccache clang" >> $GITHUB_ENV echo "CXX=ccache clang++" >> $GITHUB_ENV - echo "CMAKE_ARGS=-DBUILD_OPENMP=OFF" >> $GITHUB_ENV - - # Caches for different branches are isolated, so we don't need to put the branch name into the key. - # The total size for all caches in a repository is 5Gb. + echo "CMAKE_ARGS=${CMAKE_ARGS} -DBUILD_OPENMP=OFF" >> $GITHUB_ENV - - name: Prepare ccache timestamp - id: ccache_cache_timestamp - run: | - ccache --set-config=cache_dir=$HOME/.ccache - - if [ "${{ runner.os }}" = "Linux" ]; then - stamp=$(date '+%s') - else - stamp=$(gdate '+%s') - fi - echo "${stamp}" - echo "timestamp=${stamp}" >> $GITHUB_OUTPUT - - - name: ccache cache files -# uses: actions/cache@v2 - uses: pat-s/always-upload-cache@v3.0.11 + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 with: - path: ~/.ccache - key: ${{ matrix.name }}-ccache-${{ steps.ccache_cache_timestamp.outputs.timestamp }} + key: ${{ matrix.name }}-portable restore-keys: | - ${{ matrix.name }}-ccache- + ${{ matrix.name }}-portable - name: Configure run: | - if [ "${{ matrix.cxxflags }}" != "" ] ; then - CPPARGS="$CPPARGS ${{ matrix.cxxflags }}" - fi mkdir build cd build cmake .. -G Ninja -DCMAKE_INSTALL_PREFIX=$HOME/local ${CMAKE_ARGS} diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 000000000..04f651bca --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,52 @@ +name: CI + +on: + push: + branches: + - "*" + pull_request: + branches: + - "*" + +jobs: + build: + name: Build on Linux x86_64 + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y cmake file pkgconf libeigen3-dev + + - name: Build + run: | + mkdir build + cd build + cmake .. + make -j + file libhmsbeagle/libhmsbeagle.so.* | grep x86-64 + + build-aarch64: + name: Build on Linux aarch64 + runs-on: ubuntu-24.04-arm + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y cmake file pkgconf libeigen3-dev + + - name: Build + run: | + mkdir build + cd build + cmake .. + make -j + file libhmsbeagle/libhmsbeagle.so.* | grep aarch64 diff --git a/CMakeLists.txt b/CMakeLists.txt index ed856e070..cf1efd46a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,32 +1,48 @@ -cmake_minimum_required(VERSION 3.9) +cmake_minimum_required(VERSION 3.18) project(BEAGLE) set(BEAGLE_PACKAGE_NAME "libhmsbeagle") set(BEAGLE_VERSION_MAJOR "4") set(BEAGLE_VERSION_MINOR "0") -set(BEAGLE_VERSION_PATCH "1") +set(BEAGLE_VERSION_PATCH "2") + +set(GENERIC_API_VERSION "1") set(BEAGLE_VERSION "${BEAGLE_VERSION_MAJOR}.${BEAGLE_VERSION_MINOR}.${BEAGLE_VERSION_PATCH}") set(BEAGLE_PLUGIN_VERSION "${BEAGLE_VERSION_MAJOR}${BEAGLE_VERSION_MINOR}") -set(BEAGLE_OPTIMIZE_FOR_NATIVE_ARCH true) +message(STATUS "BEAGLE_VERSION = ${BEAGLE_VERSION}") +message(STATUS "BEAGLE_PLUGIN_VERSION = ${BEAGLE_PLUGIN_VERSION}") + +# -march=native makes the fastest code for the build machine, but the binaries may not run on other CPUs +# (Illegal instruction). Turn it off for binaries that are distributed or cached across machines. +option(BEAGLE_OPTIMIZE_FOR_NATIVE_ARCH "Compile with -march=native (not portable to other CPUs)" ON) option(BUILD_OPENCL "Build beagle with OpenCL library" ON) option(BUILD_CUDA "Build beagle with CUDA library" ON) option(BUILD_JNI "Build beagle with JNI library" ON) option(BUILD_OPENMP "Build beagle with OpenMP library" ON) option(BUILD_ACTION "Build beagle with action-based calculations" ON) +option(BUILD_SSE "Build beagle with SSE library" ON) +option(BUILD_BASTA "Build beagle with mbasta library" OFF) # Old config.h settings OPTION(BEAGLE_BENCHMARK "Print runtimes" OFF) OPTION(BEAGLE_DEBUG_FLOW "Print flow" OFF) OPTION(BEAGLE_DEBUG_VALUES "Print debug values" OFF) +OPTION(BEAGLE_DEBUG_SYNCH "Synchronize threads on GPU for timing" OFF) +OPTION(BEAGLE_BENCHMARK_ENERGY "Print energy consumption" OFF) +OPTION(BEAGLE_BASTA_CPU_ACCUM "Use CPU for final accumulation for reduction" OFF) IF(BEAGLE_BENCHMARK) ADD_DEFINITIONS(-DBEAGLE_BENCHMARK) ENDIF(BEAGLE_BENCHMARK) +IF(BEAGLE_BENCHMARK_ENERGY) + ADD_DEFINITIONS(-DBEAGLE_BENCHMARK_ENERGY) +ENDIF(BEAGLE_BENCHMARK_ENERGY) + IF(BEAGLE_DEBUG_FLOW) ADD_DEFINITIONS(-DBEAGLE_DEBUG_FLOW) ENDIF(BEAGLE_DEBUG_FLOW) @@ -35,6 +51,15 @@ IF(BEAGLE_DEBUG_VALUES) ADD_DEFINITIONS(-DBEAGLE_DEBUG_VALUES) ENDIF(BEAGLE_DEBUG_VALUES) +IF(BEAGLE_DEBUG_SYNCH) + ADD_DEFINITIONS(-DBEAGLE_DEBUG_SYNCH) +ENDIF(BEAGLE_DEBUG_SYNCH) + +IF(BEAGLE_BASTA_CPU_ACCUM) + ADD_DEFINITIONS(-DBEAGLE_BASTA_CPU_ACCUM) +ENDIF(BEAGLE_BASTA_CPU_ACCUM) + + add_definitions( -DPACKAGE_BUGREPORT="beagle-dev@googlegroups.com" -DPACKAGE_NAME="${BEAGLE_PACKAGE_NAME}" @@ -52,6 +77,13 @@ if(NOT DEFINED CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE RelWithDebInfo) endif() +# Make erros and warnings more readable by enabling colors in the compiler output +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + add_compile_options(-fdiagnostics-color=always) +elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") + add_compile_options(-fcolor-diagnostics) +endif() + ## flags for standard library #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libstdc++") SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules") @@ -113,16 +145,30 @@ if(BUILD_ACTION) include(FetchContent) set(EIGEN_VERSION 3.4) find_package(Eigen3 ${EIGEN_VERSION} QUIET) - if(NOT EIGEN3_FOUND) - message(" Eigen3: library not found - downloading.") + if(NOT Eigen3_FOUND) + message(STATUS "Eigen3 not found — downloading.") + set(BUILD_TESTING OFF CACHE INTERNAL "") - FetchContent_Declare(eigen - GIT_REPOSITORY https://gitlab.com/libeigen/eigen.git - GIT_TAG ${EIGEN_VERSION} - GIT_SHALLOW ON) + + FetchContent_Declare( + eigen + GIT_REPOSITORY https://gitlab.com/libeigen/eigen.git + GIT_TAG ${EIGEN_VERSION} + GIT_SHALLOW ON + SOURCE_SUBDIR "NONEXISTANT_DIR" + ) + FetchContent_MakeAvailable(eigen) + message(STATUS " Eigen3: downloaded.") + unset(BUILD_TESTING CACHE) - message(" Eigen3: downloaded.") + + # Create our own Eigen3::Eigen target instead of running the CMakeLists.txt from Eigen, + # which is creates an uninstallable target and so fails to configure. + add_library(Eigen3::Eigen INTERFACE IMPORTED) + target_include_directories(Eigen3::Eigen INTERFACE + ${eigen_SOURCE_DIR} + ) endif() set(CMAKE_CXX_STANDARD 17) @@ -130,6 +176,14 @@ if(BUILD_ACTION) # add_definitions(-DBEAGLE_DEBUG_FLOW) endif(BUILD_ACTION) +if (BUILD_BASTA) + IF(BEAGLE_DEBUG_KERNELS) + add_subdirectory(tests/basta) + ENDIF(BEAGLE_DEBUG_KERNELS) + + add_definitions(-DBEAGLE_BEASTA) +endif(BUILD_BASTA) + link_directories( ${PROJECT_SOURCE_DIR}/libhmsbeagle ${PROJECT_SOURCE_DIR}/libhmsbeagle/CPU @@ -176,7 +230,7 @@ elseif(UNIX) SET(CMAKE_INSTALL_RPATH "\$ORIGIN") # $ORIGIN/{CPU,GPU,JNI} is so that libhmsbeagle.so can find the plugins in their build location. # $ORIGIN/../libhmsbeagle is so that examples/* can find libhmsbeagle.so - SET(CMAKE_BUILD_RPATH "\$ORIGIN:\$ORIGIN/CPU:\$ORIGIN/GPU:\$ORIGIN/JNI:\$ORIGIN/../libhmsbeagle") + SET(CMAKE_BUILD_RPATH "\$ORIGIN:\$ORIGIN/CPU:\$ORIGIN/GPU:\$ORIGIN/GPU/CMake_Action:\$ORIGIN/GPU/CMake_CUDA:\$ORIGIN/GPU/CMake_OpenCL:\$ORIGIN/JNI:\$ORIGIN/../libhmsbeagle") endif(APPLE) if (BEAGLE_OPTIMIZE_FOR_NATIVE_ARCH) diff --git a/README.md b/README.md index 96e020052..cfbebe57a 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,8 @@ The paper describing the algorithms used for calculating likelihoods of sequence ### Current binary installers -* [BEAGLE v4.0.0 for macOS universal](https://github.com/beagle-dev/beagle-lib/releases/download/v4.0.0/BEAGLE.v4.0.0.pkg) -* [BEAGLE v4.0.0 for Windows 64-bit](https://github.com/beagle-dev/beagle-lib/releases/download/v4.0.0/BEAGLE.v4.0.0.msi) +* [BEAGLE v4.0.0 for macOS universal](https://github.com/beagle-dev/beagle-lib/releases/download/v4.0.0/BEAGLE-4.0.0-Darwin-x86-ARM.pkg) +* [BEAGLE v4.0.0 for Windows 64-bit](https://github.com/beagle-dev/beagle-lib/releases/download/v4.0.0/BEAGLE-4.0.0-win64.msi) ### Previous binary installers diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 95363a9a8..b33fa73e0 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -41,24 +41,48 @@ add_executable(synthetictest #add_executable(complextest # complextest/complextest.cpp) +if(BEAGLE_BENCHMARK) +# list(APPEND BENCHMARK_LIBS nvidia-ml) # Needed for nvml.h +endif() target_link_libraries(hmctest hmsbeagle - hmsbeagle-cpu-sse +# hmsbeagle-cpu-sse hmsbeagle-cpu + ${BENCHMARK_LIBS} ${CMAKE_DL_LIBS}) +if(BUILD_SSE) + target_link_libraries(hmctest hmsbeagle-cpu-sse) +endif(BUILD_SSE) + target_link_libraries(hmctest5 hmsbeagle - hmsbeagle-cpu-sse hmsbeagle-cpu + ${BENCHMARK_LIBS} ${CMAKE_DL_LIBS}) +if(BUILD_SSE) + target_link_libraries(hmctest5 hmsbeagle-cpu-sse) +endif(BUILD_SSE) + target_link_libraries(synthetictest hmsbeagle - hmsbeagle-cpu-sse +# hmsbeagle-cpu-sse hmsbeagle-cpu + ${BENCHMARK_LIBS} ${CMAKE_DL_LIBS}) +if(BUILD_SSE) + target_link_libraries(synthetictest hmsbeagle-cpu-sse) +endif(BUILD_SSE) + +if(BUILD_SSE) + target_link_libraries(hmctest + hmsbeagle-cpu-sse) + + target_link_libraries(synthetictest + hmsbeagle-cpu-sse) +endif(BUILD_SSE) add_test(hmctest hmctest) diff --git a/examples/actiontest/actiontest.cpp b/examples/actiontest/actiontest.cpp index 9fcc9b60d..9959ebf6f 100644 --- a/examples/actiontest/actiontest.cpp +++ b/examples/actiontest/actiontest.cpp @@ -1,12 +1,13 @@ -#include -#include -#include +#include +#include +#include #include #include #include #include #include #include +#include typedef Eigen::Matrix MatrixXd; typedef Eigen::Map MapType; @@ -20,9 +21,9 @@ typedef Eigen::Triplet Triplet; #include "libhmsbeagle/beagle.h" -char *human = (char*)"GAGT"; -char *chimp = (char*)"GAGG"; -char *gorilla = (char*)"AAAT"; +char *human = (char*)"GAGTC"; +char *chimp = (char*)"GAGGT"; +char *gorilla = (char*)"AAATC"; //char *human = (char*)"G"; //char *chimp = (char*)"G"; @@ -104,33 +105,66 @@ double* getPartials(char *sequence, int repeats) { return partials; } -void printFlags(long inFlags) { - if (inFlags & BEAGLE_FLAG_PROCESSOR_CPU) fprintf(stdout, " PROCESSOR_CPU"); - if (inFlags & BEAGLE_FLAG_PROCESSOR_GPU) fprintf(stdout, " PROCESSOR_GPU"); - if (inFlags & BEAGLE_FLAG_PROCESSOR_FPGA) fprintf(stdout, " PROCESSOR_FPGA"); - if (inFlags & BEAGLE_FLAG_PROCESSOR_CELL) fprintf(stdout, " PROCESSOR_CELL"); - if (inFlags & BEAGLE_FLAG_PRECISION_DOUBLE) fprintf(stdout, " PRECISION_DOUBLE"); - if (inFlags & BEAGLE_FLAG_PRECISION_SINGLE) fprintf(stdout, " PRECISION_SINGLE"); - if (inFlags & BEAGLE_FLAG_COMPUTATION_ASYNCH) fprintf(stdout, " COMPUTATION_ASYNCH"); - if (inFlags & BEAGLE_FLAG_COMPUTATION_SYNCH) fprintf(stdout, " COMPUTATION_SYNCH"); - if (inFlags & BEAGLE_FLAG_EIGEN_REAL) fprintf(stdout, " EIGEN_REAL"); - if (inFlags & BEAGLE_FLAG_EIGEN_COMPLEX) fprintf(stdout, " EIGEN_COMPLEX"); - if (inFlags & BEAGLE_FLAG_SCALING_MANUAL) fprintf(stdout, " SCALING_MANUAL"); - if (inFlags & BEAGLE_FLAG_SCALING_AUTO) fprintf(stdout, " SCALING_AUTO"); - if (inFlags & BEAGLE_FLAG_SCALING_ALWAYS) fprintf(stdout, " SCALING_ALWAYS"); - if (inFlags & BEAGLE_FLAG_SCALING_DYNAMIC) fprintf(stdout, " SCALING_DYNAMIC"); - if (inFlags & BEAGLE_FLAG_SCALERS_RAW) fprintf(stdout, " SCALERS_RAW"); - if (inFlags & BEAGLE_FLAG_SCALERS_LOG) fprintf(stdout, " SCALERS_LOG"); - if (inFlags & BEAGLE_FLAG_VECTOR_NONE) fprintf(stdout, " VECTOR_NONE"); - if (inFlags & BEAGLE_FLAG_VECTOR_SSE) fprintf(stdout, " VECTOR_SSE"); - if (inFlags & BEAGLE_FLAG_VECTOR_AVX) fprintf(stdout, " VECTOR_AVX"); - if (inFlags & BEAGLE_FLAG_THREADING_NONE) fprintf(stdout, " THREADING_NONE"); - if (inFlags & BEAGLE_FLAG_THREADING_CPP) fprintf(stdout, " THREADING_CPP"); - if (inFlags & BEAGLE_FLAG_THREADING_OPENMP) fprintf(stdout, " THREADING_OPENMP"); - if (inFlags & BEAGLE_FLAG_FRAMEWORK_CPU) fprintf(stdout, " FRAMEWORK_CPU"); - if (inFlags & BEAGLE_FLAG_FRAMEWORK_CUDA) fprintf(stdout, " FRAMEWORK_CUDA"); - if (inFlags & BEAGLE_FLAG_FRAMEWORK_OPENCL) fprintf(stdout, " FRAMEWORK_OPENCL"); - if (inFlags & BEAGLE_FLAG_COMPUTATION_ACTION) fprintf(stdout, " COMPUTATION_ACTION"); + +std::ostream& operator<<(std::ostream& o, BeagleFlags inFlags) +{ + if (inFlags & BEAGLE_FLAG_PRECISION_SINGLE) o<<" PRECISION_SINGLE"; + if (inFlags & BEAGLE_FLAG_PRECISION_DOUBLE) o<<" PRECISION_DOUBLE"; + if (inFlags & BEAGLE_FLAG_COMPUTATION_SYNCH) o<<" COMPUTATION_SYNCH"; + if (inFlags & BEAGLE_FLAG_COMPUTATION_ASYNCH) o<<" COMPUTATION_ASYNCH"; + if (inFlags & BEAGLE_FLAG_EIGEN_REAL) o<<" EIGEN_REAL"; + if (inFlags & BEAGLE_FLAG_EIGEN_COMPLEX) o<<" EIGEN_COMPLEX"; + + if (inFlags & BEAGLE_FLAG_SCALING_MANUAL) o<<" SCALING_MANUAL"; + if (inFlags & BEAGLE_FLAG_SCALING_AUTO) o<<" SCALING_AUTO"; + if (inFlags & BEAGLE_FLAG_SCALING_ALWAYS) o<<" SCALING_ALWAYS"; + if (inFlags & BEAGLE_FLAG_SCALING_DYNAMIC) o<<" SCALING_DYNAMIC"; + if (inFlags & BEAGLE_FLAG_SCALERS_RAW) o<<" SCALERS_RAW"; + if (inFlags & BEAGLE_FLAG_SCALERS_LOG) o<<" SCALERS_LOG"; + + if (inFlags & BEAGLE_FLAG_INVEVEC_STANDARD) o<<" INVENV_STANDARD"; + if (inFlags & BEAGLE_FLAG_INVEVEC_TRANSPOSED) o<<" INVENV_STANDARD"; + + if (inFlags & BEAGLE_FLAG_VECTOR_SSE) o<<" VECTOR_SSE"; + if (inFlags & BEAGLE_FLAG_VECTOR_AVX) o<<" VECTOR_AVX"; + if (inFlags & BEAGLE_FLAG_VECTOR_NONE) o<<" VECTOR_NONE"; + + if (inFlags & BEAGLE_FLAG_THREADING_CPP) o<<" THREADING_CPP"; + if (inFlags & BEAGLE_FLAG_THREADING_OPENMP) o<<" THREADING_OPENMP"; + if (inFlags & BEAGLE_FLAG_THREADING_NONE) o<<" THREADING_NONE"; + + if (inFlags & BEAGLE_FLAG_PROCESSOR_CPU) o<<" PROCESSOR_CPU"; + if (inFlags & BEAGLE_FLAG_PROCESSOR_GPU) o<<" PROCESSOR_GPU"; + if (inFlags & BEAGLE_FLAG_PROCESSOR_FPGA) o<<" PROCESSOR_FPGA"; + if (inFlags & BEAGLE_FLAG_PROCESSOR_CELL) o<<" PROCESSOR_CELL"; + if (inFlags & BEAGLE_FLAG_PROCESSOR_PHI) o<<" PROCESSOR_PHI"; + if (inFlags & BEAGLE_FLAG_PROCESSOR_OTHER) o<<" PROCESSOR_OTHER"; + + if (inFlags & BEAGLE_FLAG_FRAMEWORK_CUDA) o<<" FRAMEWORK_CUDA"; + if (inFlags & BEAGLE_FLAG_FRAMEWORK_OPENCL) o<<" FRAMEWORK_OPENCL"; + if (inFlags & BEAGLE_FLAG_FRAMEWORK_CPU) o<<" FRAMEWORK_CPU"; + + if (inFlags & BEAGLE_FLAG_PARALLELOPS_STREAMS) o<<" PARALLEL_OPS_STREAMS"; + if (inFlags & BEAGLE_FLAG_PARALLELOPS_GRID) o<<" PARALLEL_OPS_GRID"; + + if (inFlags & BEAGLE_FLAG_PREORDER_TRANSPOSE_MANUAL) o<<" PREORDER_TRANSPOSE_MANUAL"; + if (inFlags & BEAGLE_FLAG_PREORDER_TRANSPOSE_AUTO) o<<" PREORDER_TRANSPOSE_MANUAL"; + + if (inFlags & BEAGLE_FLAG_COMPUTATION_ACTION) o<<" COMPUTATION_ACTION"; + + return o; +} + +std::string showFlags(BeagleFlags flags) +{ + std::ostringstream o; + o<length; i++) { - fprintf(stdout, "\tResource %i:\n\t\tName : %s\n", i, rList->list[i].name); - fprintf(stdout, "\t\tDesc : %s\n", rList->list[i].description); - fprintf(stdout, "\t\tFlags:"); - printFlags(rList->list[i].supportFlags); - fprintf(stdout, "\n"); + std::cout<<"\tResource "<list[i].name<<"\n"; + std::cout<<"\t\tDesc : "<list[i].description<<"\n"; + std::cout<<"\t\tFlags:"<list[i].supportFlags )<<"\n"; } - fprintf(stdout, "\n"); - - bool scaling = true; + std::cout<<"\n"; bool doJC = true; @@ -167,9 +197,23 @@ int main( int argc, const char* argv[] ) // int rateCategoryCount = 4; int rateCategoryCount = 2; + bool scaling = true; + for(int i=1;i 1 && strcmp(argv[1] , "--gpu") == 0; + int whichDevice = -1; + bool useGpu = false; + for(int i=1;i\n"; std::cerr<<"Flag: --threading\n"; + std::cerr<<"Flag: --noscaling\n"; std::exit(1); } bool useTipStates = false; - int whichDevice = -1; - if (useGpu) { - if (argc > 2) { - whichDevice = atol(argv[2]); - if (whichDevice < 0) { - whichDevice = -1; - } - } - } + if (useGpu) useSSE = false; BeagleInstanceDetails instDetails; +// long requirementFlags = BEAGLE_FLAG_EIGEN_REAL; + long long requirementFlags = 0; long long preferenceFlags = BEAGLE_FLAG_COMPUTATION_ACTION; if (useGpu) { - preferenceFlags |= BEAGLE_FLAG_PROCESSOR_GPU; + requirementFlags |= BEAGLE_FLAG_PROCESSOR_GPU; } else { - preferenceFlags |= BEAGLE_FLAG_PROCESSOR_CPU; + requirementFlags |= BEAGLE_FLAG_PROCESSOR_CPU; + if (useSSE) { + requirementFlags |= BEAGLE_FLAG_VECTOR_SSE; + } else { + requirementFlags |= BEAGLE_FLAG_VECTOR_NONE; + } } if (singlePrecision) { @@ -212,14 +257,6 @@ int main( int argc, const char* argv[] ) preferenceFlags |= BEAGLE_FLAG_PRECISION_DOUBLE; } -// long requirementFlags = BEAGLE_FLAG_EIGEN_REAL; - long long requirementFlags = BEAGLE_FLAG_FRAMEWORK_CPU; - if (useSSE) { - requirementFlags |= BEAGLE_FLAG_VECTOR_SSE; - } else { - requirementFlags |= BEAGLE_FLAG_VECTOR_NONE; - } - if (useThreading) preferenceFlags |= BEAGLE_FLAG_THREADING_CPP; @@ -240,17 +277,17 @@ int main( int argc, const char* argv[] ) requirementFlags, /**< Bit-flags indicating required implementation characteristics, see BeagleFlags (input) */ &instDetails); if (instance < 0) { - fprintf(stderr, "Failed to obtain BEAGLE instance\n\n"); + std::cerr<<"Failed to obtain BEAGLE instance\n\n"; exit(1); } int rNumber = instDetails.resourceNumber; - fprintf(stdout, "Using resource %i:\n", rNumber); - fprintf(stdout, "\tRsrc Name : %s\n",instDetails.resourceName); - fprintf(stdout, "\tImpl Name : %s\n", instDetails.implName); - fprintf(stdout, "\tImpl Desc : %s\n", instDetails.implDescription); - fprintf(stdout, "\n"); + std::cout<<"Using resource "< firstBuffer(nPatterns * 5 * 2); // Get both numerator and denominator std::vector sumBuffer(5); diff --git a/examples/hmctest/hmcBastaTest.cpp b/examples/hmctest/hmcBastaTest.cpp new file mode 100755 index 000000000..60415ef21 --- /dev/null +++ b/examples/hmctest/hmcBastaTest.cpp @@ -0,0 +1,499 @@ +/* + * tinyTest.c + * BEAGLE + * + * Created by Andrew Rambaut on 20/03/2009. + * Copyright 2009 __MyCompanyName__. All rights reserved. + * + */ +#include +#include +#include +#include +#include +#include +#include + +//#define JC + +#ifdef _WIN32 +#include +#endif + +#include "libhmsbeagle/beagle.h" + +char *human = (char*)"A"; +char *chimp = (char*)"G"; +char *gorilla = (char*)"G"; + +//char *human = (char*)"G"; +//char *chimp = (char*)"G"; +//char *gorilla = (char*)"A"; + + +//char *human = (char*)"GAGAAATATGTCTGATAAAAGAGTTACTTTGATAGAGTAAATAATAGGAGCTTAAACCCCCTTATTTCTACTAGGACTATGAGAATCGAACCCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTATCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTTATACCCTTCCCGTACTAAGAAATTTAGGTTAAATACAGACCAAGAGCCTTCAAAGCCCTCAGTAAGTTG-CAATACTTAATTTCTGTAAGGACTGCAAAACCCCACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGACCAATGGGACTTAAACCCACAAACACTTAGTTAACAGCTAAGCACCCTAATCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAA-TCACCTCGGAGCTTGGTAAAAAGAGGCCTAACCCCTGTCTTTAGATTTACAGTCCAATGCTTCA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCCAAAGCTGGTTTCAAGCCAACCCCATGGCCTCCATGACTTTTTCAAAAGGTATTAGAAAAACCATTTCATAACTTTGTCAAAGTTAAATTATAGGCT-AAATCCTATATATCTTA-CACTGTAAAGCTAACTTAGCATTAACCTTTTAAGTTAAAGATTAAGAGAACCAACACCTCTTTACAGTGA"; +//char *chimp = (char*)"GGGAAATATGTCTGATAAAAGAATTACTTTGATAGAGTAAATAATAGGAGTTCAAATCCCCTTATTTCTACTAGGACTATAAGAATCGAACTCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTATCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTTACACCCTTCCCGTACTAAGAAATTTAGGTTAAGCACAGACCAAGAGCCTTCAAAGCCCTCAGCAAGTTA-CAATACTTAATTTCTGTAAGGACTGCAAAACCCCACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGATTAATGGGACTTAAACCCACAAACATTTAGTTAACAGCTAAACACCCTAATCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAA-TCACCTCAGAGCTTGGTAAAAAGAGGCTTAACCCCTGTCTTTAGATTTACAGTCCAATGCTTCA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCTAAAGCTGGTTTCAAGCCAACCCCATGACCTCCATGACTTTTTCAAAAGATATTAGAAAAACTATTTCATAACTTTGTCAAAGTTAAATTACAGGTT-AACCCCCGTATATCTTA-CACTGTAAAGCTAACCTAGCATTAACCTTTTAAGTTAAAGATTAAGAGGACCGACACCTCTTTACAGTGA"; +//char *gorilla = (char*)"AGAAAATATGTCTGATAAAAGAGTTACTTTGATAGAGTAAATAATAGAGGTTTAAACCCCCTTATTTCTACTAGGACTATGAGAATTGAACCCATCCCTGAGAATCCAAAATTCTCCGTGCCACCTGTCACACCCCATCCTAAGTAAGGTCAGCTAAATAAGCTATCGGGCCCATACCCCGAAAATGTTGGTCACATCCTTCCCGTACTAAGAAATTTAGGTTAAACATAGACCAAGAGCCTTCAAAGCCCTTAGTAAGTTA-CAACACTTAATTTCTGTAAGGACTGCAAAACCCTACTCTGCATCAACTGAACGCAAATCAGCCACTTTAATTAAGCTAAGCCCTTCTAGATCAATGGGACTCAAACCCACAAACATTTAGTTAACAGCTAAACACCCTAGTCAAC-TGGCTTCAATCTAAAGCCCCGGCAGG-TTTGAAGCTGCTTCTTCGAATTTGCAATTCAATATGAAAT-TCACCTCGGAGCTTGGTAAAAAGAGGCCCAGCCTCTGTCTTTAGATTTACAGTCCAATGCCTTA-CTCAGCCATTTTACCACAAAAAAGGAAGGAATCGAACCCCCCAAAGCTGGTTTCAAGCCAACCCCATGACCTTCATGACTTTTTCAAAAGATATTAGAAAAACTATTTCATAACTTTGTCAAGGTTAAATTACGGGTT-AAACCCCGTATATCTTA-CACTGTAAAGCTAACCTAGCGTTAACCTTTTAAGTTAAAGATTAAGAGTATCGGCACCTCTTTGCAGTGA"; + +int* getStates(char *sequence, int repeats) { + int n = strlen(sequence); + int *states = (int*) malloc(sizeof(int) * n * repeats); + + int k = 0; + for (int r = 0; r < repeats; ++r) { + for (int i = 0; i < n; i++) { + switch (sequence[i]) { + case 'A': + states[k++] = 0; + break; + case 'C': + states[k++] = 1; + break; + case 'G': + states[k++] = 2; + break; + case 'T': + states[k++] = 3; + break; + default: + states[k++] = 4; + break; + } + } + } + return states; +} + +double* getPartials(char *sequence, int repeats) { + int n = strlen(sequence); + double *partials = (double*)malloc(sizeof(double) * n * 4); + + int k = 0; + for (int i = 0; i < n; i++) { + switch (sequence[i]) { + case 'A': + partials[k++] = 1; + partials[k++] = 0; + partials[k++] = 0; + partials[k++] = 0; + break; + case 'C': + partials[k++] = 0; + partials[k++] = 1; + partials[k++] = 0; + partials[k++] = 0; + break; + case 'G': + partials[k++] = 0; + partials[k++] = 0; + partials[k++] = 1; + partials[k++] = 0; + break; + case 'T': + partials[k++] = 0; + partials[k++] = 0; + partials[k++] = 0; + partials[k++] = 1; + break; + default: + partials[k++] = 1; + partials[k++] = 1; + partials[k++] = 1; + partials[k++] = 1; + break; + } + } + return partials; +} + +void printFlags(long inFlags) { + if (inFlags & BEAGLE_FLAG_PROCESSOR_CPU) fprintf(stdout, " PROCESSOR_CPU"); + if (inFlags & BEAGLE_FLAG_PROCESSOR_GPU) fprintf(stdout, " PROCESSOR_GPU"); + if (inFlags & BEAGLE_FLAG_PROCESSOR_FPGA) fprintf(stdout, " PROCESSOR_FPGA"); + if (inFlags & BEAGLE_FLAG_PROCESSOR_CELL) fprintf(stdout, " PROCESSOR_CELL"); + if (inFlags & BEAGLE_FLAG_PRECISION_DOUBLE) fprintf(stdout, " PRECISION_DOUBLE"); + if (inFlags & BEAGLE_FLAG_PRECISION_SINGLE) fprintf(stdout, " PRECISION_SINGLE"); + if (inFlags & BEAGLE_FLAG_COMPUTATION_ASYNCH) fprintf(stdout, " COMPUTATION_ASYNCH"); + if (inFlags & BEAGLE_FLAG_COMPUTATION_SYNCH) fprintf(stdout, " COMPUTATION_SYNCH"); + if (inFlags & BEAGLE_FLAG_EIGEN_REAL) fprintf(stdout, " EIGEN_REAL"); + if (inFlags & BEAGLE_FLAG_EIGEN_COMPLEX) fprintf(stdout, " EIGEN_COMPLEX"); + if (inFlags & BEAGLE_FLAG_SCALING_MANUAL) fprintf(stdout, " SCALING_MANUAL"); + if (inFlags & BEAGLE_FLAG_SCALING_AUTO) fprintf(stdout, " SCALING_AUTO"); + if (inFlags & BEAGLE_FLAG_SCALING_ALWAYS) fprintf(stdout, " SCALING_ALWAYS"); + if (inFlags & BEAGLE_FLAG_SCALING_DYNAMIC) fprintf(stdout, " SCALING_DYNAMIC"); + if (inFlags & BEAGLE_FLAG_SCALERS_RAW) fprintf(stdout, " SCALERS_RAW"); + if (inFlags & BEAGLE_FLAG_SCALERS_LOG) fprintf(stdout, " SCALERS_LOG"); + if (inFlags & BEAGLE_FLAG_VECTOR_NONE) fprintf(stdout, " VECTOR_NONE"); + if (inFlags & BEAGLE_FLAG_VECTOR_SSE) fprintf(stdout, " VECTOR_SSE"); + if (inFlags & BEAGLE_FLAG_VECTOR_AVX) fprintf(stdout, " VECTOR_AVX"); + if (inFlags & BEAGLE_FLAG_THREADING_NONE) fprintf(stdout, " THREADING_NONE"); + if (inFlags & BEAGLE_FLAG_THREADING_OPENMP) fprintf(stdout, " THREADING_OPENMP"); + if (inFlags & BEAGLE_FLAG_FRAMEWORK_CPU) fprintf(stdout, " FRAMEWORK_CPU"); + if (inFlags & BEAGLE_FLAG_FRAMEWORK_CUDA) fprintf(stdout, " FRAMEWORK_CUDA"); + if (inFlags & BEAGLE_FLAG_FRAMEWORK_OPENCL) fprintf(stdout, " FRAMEWORK_OPENCL"); +} + +int main( int argc, const char* argv[] ) +{ + // print resource list + BeagleResourceList* rList; + rList = beagleGetResourceList(); + fprintf(stdout, "Available resources:\n"); + for (int i = 0; i < rList->length; i++) { + fprintf(stdout, "\tResource %i:\n\t\tName : %s\n", i, rList->list[i].name); + fprintf(stdout, "\t\tDesc : %s\n", rList->list[i].description); + fprintf(stdout, "\t\tFlags:"); + printFlags(rList->list[i].supportFlags); + fprintf(stdout, "\n"); + } + fprintf(stdout, "\n"); + +// bool scaling = true; + bool scaling = false; // disable scaling for now + + bool doJC = true; + + bool singlePrecision = false; + bool useSSE = true; + + // is nucleotides... + int stateCount = 4; + + int nRepeats = 1; + + // get the number of site patterns + int nPatterns = strlen(human) * nRepeats; + + // change # rate category to 2 +// int rateCategoryCount = 4; + int rateCategoryCount = 1; + + int scaleCount = (scaling ? 7 : 0); + + bool useGpu = argc > 1 && strcmp(argv[1] , "--gpu") == 0; + + bool useTipStates = false; + + int whichDevice = -1; + if (useGpu) { + if (argc > 2) { + whichDevice = atol(argv[2]); + if (whichDevice < 0) { + whichDevice = -1; + } + } + } + + BeagleInstanceDetails instDetails; + + long preferenceFlags = BEAGLE_FLAG_SCALERS_RAW; + + if (useGpu) { + preferenceFlags |= BEAGLE_FLAG_PROCESSOR_GPU; + } else { + preferenceFlags |= BEAGLE_FLAG_PROCESSOR_CPU; + } + + if (singlePrecision) { + preferenceFlags |= BEAGLE_FLAG_PRECISION_SINGLE; + } else { + preferenceFlags |= BEAGLE_FLAG_PRECISION_DOUBLE; + } + + long requirementFlags = BEAGLE_FLAG_EIGEN_REAL; + if (useSSE) { + requirementFlags |= BEAGLE_FLAG_VECTOR_SSE; + } else { + requirementFlags |= BEAGLE_FLAG_VECTOR_NONE; + } + + // create an instance of the BEAGLE library + int instance = beagleCreateInstance( + 0, /**< Number of tip data elements (input) */ + 20, /**< Number of partials buffers to create (input) */ + 0, /**< Number of compact state representation buffers to create (input) */ + stateCount, /**< Number of states in the continuous-time Markov chain (input) */ + 1, /**< Number of site patterns to be handled by the instance (input) */ + 2, /**< Number of rate matrix eigen-decomposition buffers to allocate (input) */ + 4, /**< Number of rate matrix buffers (input) */ + rateCategoryCount,/**< Number of rate categories (input) */ + 1, /**< Number of scaling buffers */ + NULL, /**< List of potential resource on which this instance is allowed (input, NULL implies no restriction */ + whichDevice >= 0 ? 1 : 0, /**< Length of resourceList list (input) */ + 0, + 32, /**< Bit-flags indicating required implementation characteristics, see BeagleFlags (input) */ + &instDetails); + + beagleAllocateBastaBuffers(instance,5,4); + + if (instance < 0) { + fprintf(stderr, "Failed to obtain BEAGLE instance\n\n"); + exit(1); + } + + int rNumber = instDetails.resourceNumber; + fprintf(stdout, "Using resource %i:\n", rNumber); + fprintf(stdout, "\tRsrc Name : %s\n",instDetails.resourceName); + fprintf(stdout, "\tImpl Name : %s\n", instDetails.implName); + fprintf(stdout, "\tImpl Desc : %s\n", instDetails.implDescription); + fprintf(stdout, "\n"); + + if (useTipStates) { + // set the sequences for each tip using state likelihood arrays + int *humanStates = getStates(human, nRepeats); + int *chimpStates = getStates(chimp, nRepeats); + int *gorillaStates = getStates(gorilla, nRepeats); + + beagleSetTipStates(instance, 0, humanStates); + beagleSetTipStates(instance, 1, chimpStates); + beagleSetTipStates(instance, 2, gorillaStates); + + free(humanStates); + free(chimpStates); + free(gorillaStates); + + } else { + // set the sequences for each tip using partial likelihood arrays + double *humanPartials = getPartials(human, nRepeats); + double *chimpPartials = getPartials(chimp, nRepeats); + double *gorillaPartials = getPartials(gorilla, nRepeats); + + beagleSetPartials(instance, 0, humanPartials); + beagleSetPartials(instance, 1, chimpPartials); + beagleSetPartials(instance, 2, gorillaPartials); + + free(humanPartials); + free(chimpPartials); + free(gorillaPartials); + } + +#ifdef _WIN32 + std::vector rates(rateCategoryCount); +#else + double rates[rateCategoryCount]; +#endif + + + + + rates[0] = 1.0; + + beagleSetCategoryRates(instance, &rates[0]); + + double* patternWeights = (double*) malloc(sizeof(double) * nPatterns); + + for (int i = 0; i < nPatterns; i++) { + patternWeights[i] = 1.0; + } + + beagleSetPatternWeights(instance, patternWeights); + + // create base frequency array +// double freqs[4] = { 0.1, 0.3, 0.2, 0.4 }; + double freqs[4] = { 0.25, 0.25, 0.25, 0.25 }; + + beagleSetStateFrequencies(instance, 0, freqs); + + // create an array containing site category weights +#ifdef _WIN32 + std::vector weights(rateCategoryCount); +#else + double weights[rateCategoryCount]; +#endif + for (int i = 0; i < rateCategoryCount; i++) { + weights[i] = 1.0/rateCategoryCount; +// weights[i] = 2.0 * double(i + 1)/ double(rateCategoryCount * (rateCategoryCount + 1)); + } + + beagleSetCategoryWeights(instance, 0, &weights[0]); + + + ///eigen decomposition of the HKY85 model + double evec[4 * 4] = {-0.6532830113402044, 0.4999979842955143, -0.27059808322435847, 0.5000000001499998, 0.2705993899275025, -0.4999994206514062, -0.6532813709797044, 0.4999999998499999, -0.27059644259896054, -0.5000005794441943, 0.65328170474785, 0.5000000000499999, 0.6532800643812152, 0.5000020156000878, 0.2705977493031389, 0.49999999994999994}; + + double ivec[4 * 4] = {-0.6532830113402049, 0.270599389927502, -0.27059644259896076, 0.6532800643812157, 0.49999798429551423, -0.49999942065140635, -0.5000005794441948, 0.500002015600088, -0.2705980832243587, -0.6532813709797037, 0.6532817047478499, 0.2705977493031391, 0.5000000001499999, 0.49999999985000004, 0.5000000000500006, 0.49999999994999994}; + + ///array of real parts + array of imaginary parts + double eval[8] = {-1.0000000001414213, -1.0000000000999998, -0.9999999998585786, 1.0000023031864202E-10, 0.0, 0.0, 0.0, 0.0}; + + ///Q^T matrix +// double QT[4 * 4] = { +// -1.2857138, 0.1428570, 0.1428570, 0.1428570, +// 0.4285712, -0.9999997, 0.4285714, 0.4285713, +// 0.2857142, 0.2857143, -1.1428568, 0.2857142, +// 0.5714284, 0.5714284, 0.5714284, -0.8571426 +// }; + + double Q[4 * 4 * 1] = { + -0.7499999999, 0.2499999999, 0.2500000001, 0.2499999999, + 0.2500000001, -0.7500000001, 0.2500000001, 0.2499999999, + 0.2500000001, 0.2499999999, -0.7499999999, 0.2499999999, + 0.2500000001, 0.2499999999, 0.2500000001, -0.7500000001 + }; + + + std::vector scaledQ(4 * 4 * 1); +// std::vector scaledQT(4 * 4 * 2); + + for (int rate = 0; rate < rateCategoryCount; ++rate) { + for (int entry = 0; entry < stateCount * stateCount; ++entry) { + scaledQ[entry + rate * stateCount * stateCount] = Q[entry + rate * stateCount * stateCount] * rates[rate]; + } + } + + // set the Eigen decomposition + beagleSetEigenDecomposition(instance, 0, evec, ivec, eval); + + // a list of indices and edge lengths + int transitionMatrixIndices[3] = { 0, 1, 2}; + double edgeLengths[3] = {0, 0.6, 0.7}; + //double edgeLengths[4] = { 1.0, 1.0, 1.0, 1.0}; + + // tell BEAGLE to populate the transition matrices for the above edge lengths + beagleUpdateTransitionMatrices(instance, // instance + 0, // eigenIndex + transitionMatrixIndices, // probabilityIndices + NULL, // firstDerivativeIndices + NULL, // secondDervativeIndices + edgeLengths, // edgeLengths + 3); // count + + beagleSetTransitionMatrix(instance, 3, scaledQ.data(), 0.0); + + + double* matrix1 = (double*) malloc(sizeof(double) * stateCount * stateCount * rateCategoryCount); + double* matrix2 = (double*) malloc(sizeof(double) * stateCount * stateCount * rateCategoryCount); + double* matrix3 = (double*) malloc(sizeof(double) * stateCount * stateCount * rateCategoryCount); + + beagleGetTransitionMatrix(instance, 0, matrix1); + beagleGetTransitionMatrix(instance, 1, matrix2); + beagleGetTransitionMatrix(instance, 2, matrix3); + + int nodeId = 0; + std::cout << "Matrix for node " << nodeId << std::endl; + double* mat = matrix1; + { + int offset = 0; + for (int r = 0; r < rateCategoryCount; r++) { + std::cout << " rate category" << r + 1 << ": \n"; + for (int i = 0; i < stateCount; i++) { + for (int j = 0; j < stateCount; j++) { + std::cout << mat[offset++] << ", "; + } + std::cout << std::endl; + } + std::cout << std::endl; + } + } + + std::cout << "Matrix for node " << nodeId << std::endl; + double* mat2 = matrix2; + { + int offset = 0; + for (int r = 0; r < rateCategoryCount; r++) { + std::cout << " rate category" << r + 1 << ": \n"; + for (int i = 0; i < stateCount; i++) { + for (int j = 0; j < stateCount; j++) { + std::cout << mat2[offset++] << ", "; + } + std::cout << std::endl; + } + std::cout << std::endl; + } + } + + std::cout << "Matrix for node " << nodeId << std::endl; + double* mat3 = matrix3; + { + int offset = 0; + for (int r = 0; r < rateCategoryCount; r++) { + std::cout << " rate category" << r + 1 << ": \n"; + for (int i = 0; i < stateCount; i++) { + for (int j = 0; j < stateCount; j++) { + std::cout << mat3[offset++] << ", "; + } + std::cout << std::endl; + } + std::cout << std::endl; + } + } + + // create a list of partial likelihood update operations + // the order is [dest, destScaling, source1, matrix1, source2, matrix2] + BastaOperation operations[4] = {3, 2, 0, -1, -1, 3, -1, 0, 4, 0, 1, 1, 1, 5, 6, 1, 7, 3, 1, -1, -1, 7, -1, 1, 8, 4, 2, 7, 2, 9, 10, 2}; + + int rootIndex = 4; + int intervals[4] = {0,1,3,4}; + int intervalSize = 4; + // update the partials + beagleUpdateBastaPartials(instance, + operations, + 4, + intervals, + intervalSize, + 0, + 0); + + + double * nodePartials = (double*) malloc(sizeof(double) * stateCount * nPatterns * rateCategoryCount); + + for(int i = 0; i < 5; i++){ + beagleGetPartials(instance, 3+i, BEAGLE_OP_NONE, nodePartials); + + std::cout<<"node Partial for node "<< 4-i << ": \n"; + + int l = 0; + for(int s = 0; s < rateCategoryCount; s++){ + std::cout<<" rate category"<< s+1<< ": \n"; + for(int j=0; j < stateCount; j++){ + std::cout< - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/examples/standalone/epochtest/LICENSE b/examples/standalone/epochtest/LICENSE new file mode 100644 index 000000000..12741b8cd --- /dev/null +++ b/examples/standalone/epochtest/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Phylogenetic Likelihood Working Group + +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. diff --git a/java/beagle-lib.iml b/java/beagle-lib.iml new file mode 100644 index 000000000..b107a2dd8 --- /dev/null +++ b/java/beagle-lib.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/java/beagle/Beagle.java b/java/beagle/Beagle.java index 9bfb765c0..eaa2ce57a 100644 --- a/java/beagle/Beagle.java +++ b/java/beagle/Beagle.java @@ -5,19 +5,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @brief This file documents the API as well as header for the * Broad-platform Evolutionary Analysis General Likelihood Evaluator @@ -287,6 +277,42 @@ void setEigenDecomposition( final double[] inInverseEigenVectors, final double[] inEigenValues); + /** + * Set a sparse matrix + * + * This function copies a sparse matrix into a instance buffer. + * + * @param matrixIndex Index of sparse matrix buffer (input) + * @param inRowIndices Row indices of non-zero entries (input) + * @param inColIndices Column indices of non-zero entries (input) + * @param inValues Vector of non-zero values (input) + * @param numNonZeros Number of non-zero entries (input) + */ + void setSparseMatrix( + int matrixIndex, + final int[] inRowIndices, + final int[] inColIndices, + final double[] inValues, + int numNonZeros); + + /** + * Set a sparse differential matrix + * + * This function copies a sparse matrix into a instance buffer. + * + * @param matrixIndex Index of sparse matrix buffer (input) + * @param inRowIndices Row indices of non-zero entries (input) + * @param inColIndices Column indices of non-zero entries (input) + * @param inValues Vector of non-zero values (input) + * @param numNonZeros Number of non-zero entries (input) + */ + void setSparseDifferentialMatrix( + int matrixIndex, + final int[] inRowIndices, + final int[] inColIndices, + final double[] inValues, + int numNonZeros); + /** * Set a set of state frequences. These will probably correspond to an * eigen-system. diff --git a/java/beagle/BeagleFactory.java b/java/beagle/BeagleFactory.java index b44e4bc28..1cc733f60 100644 --- a/java/beagle/BeagleFactory.java +++ b/java/beagle/BeagleFactory.java @@ -162,7 +162,7 @@ public static Beagle loadBeagleInstance( ); } - private static BeagleJNIWrapper getBeagleJNIWrapper() { + protected static BeagleJNIWrapper getBeagleJNIWrapper() { if (BeagleJNIWrapper.INSTANCE == null) { try { BeagleJNIWrapper.loadBeagleLibrary(); diff --git a/java/beagle/BeagleFlag.java b/java/beagle/BeagleFlag.java index 449b31acc..f8e9bd9ba 100644 --- a/java/beagle/BeagleFlag.java +++ b/java/beagle/BeagleFlag.java @@ -44,6 +44,7 @@ public enum BeagleFlag { PREORDER_TRANSPOSE_MANUAL((long) 1 << 30, "Pre-order transition matrices passed to BEAGLE have been transposed"), PREORDER_TRANSPOSE_AUTO((long) 1 << 31, "Automatically transpose pre-order transition matrices"), + PREORDER_TRANSPOSE_LOW_MEMORY(1L << 32, "Use low-memory automatic transposition of pre-order transition matrices"), BEAGLE_FLAG_COMPUTATION_ACTION((long) 1 << 40, "Action computation"); diff --git a/java/beagle/BeagleJNIImpl.java b/java/beagle/BeagleJNIImpl.java index 7575fbac6..a0b72f032 100644 --- a/java/beagle/BeagleJNIImpl.java +++ b/java/beagle/BeagleJNIImpl.java @@ -15,7 +15,7 @@ public class BeagleJNIImpl implements Beagle { - private int instance = -1; + protected int instance = -1; private InstanceDetails details = new InstanceDetails(); public BeagleJNIImpl(int tipCount, @@ -141,6 +141,22 @@ public void setEigenDecomposition(int eigenIndex, } } + @Override + public void setSparseMatrix(int matrixIndex, int[] inRowIndices, int[] inColIndices, double[] inValues, int numNonZeros) { + int errCode = BeagleJNIWrapper.INSTANCE.setSparseMatrix(instance, matrixIndex, inRowIndices, inColIndices, inValues, numNonZeros); + if (errCode != 0) { + throw new BeagleException("setSparseMatrix", errCode); + } + } + + @Override + public void setSparseDifferentialMatrix(int matrixIndex, int[] inRowIndices, int[] inColIndices, double[] inValues, int numNonZeros) { + int errCode = BeagleJNIWrapper.INSTANCE.setSparseDifferentialMatrix(instance, matrixIndex, inRowIndices, inColIndices, inValues, numNonZeros); + if (errCode != 0) { + throw new BeagleException("setSparseDifferentialMatrix", errCode); + } + } + public void setStateFrequencies(int stateFrequenciesIndex, final double[] stateFrequencies) { int errCode = BeagleJNIWrapper.INSTANCE.setStateFrequencies(instance, diff --git a/java/beagle/BeagleJNIWrapper.java b/java/beagle/BeagleJNIWrapper.java index b77c09208..6286336ef 100644 --- a/java/beagle/BeagleJNIWrapper.java +++ b/java/beagle/BeagleJNIWrapper.java @@ -90,6 +90,20 @@ public native int setEigenDecomposition(int instance, final double[] inverseEigenValues, final double[] eigenValues); + public native int setSparseMatrix(int instance, + int matrixIndex, + final int[] rowIndices, + final int[] colIndices, + final double[] values, + int numNonZeros); + + public native int setSparseDifferentialMatrix(int instance, + int matrixIndex, + final int[] rowIndices, + final int[] colIndices, + final double[] values, + int numNonZeros); + public native int setStateFrequencies(int instance, int stateFrequenciesIndex, final double[] stateFrequencies); diff --git a/java/beagle/GeneralBeagleImpl.java b/java/beagle/GeneralBeagleImpl.java index ae63b98b3..844d839a2 100644 --- a/java/beagle/GeneralBeagleImpl.java +++ b/java/beagle/GeneralBeagleImpl.java @@ -229,6 +229,12 @@ public void setStateFrequencies(final int stateFrequenciesIndex, final double[] System.arraycopy(stateFrequencies, 0, this.stateFrequencies[stateFrequenciesIndex], 0, stateCount); } + public void setSparseMatrix(int maatrixIndex, final int[] inRowIndices, final int[] inColIndices, final double[] inValues, int numNonZeros) { + }; + + public void setSparseDifferentialMatrix(int maatrixIndex, final int[] inRowIndices, final int[] inColIndices, final double[] inValues, int numNonZeros) { + }; + public void setCategoryWeights(final int categoryWeightsIndex, final double[] categoryWeights) { System.arraycopy(categoryWeights, 0, this.categoryWeights[categoryWeightsIndex], 0, categoryCount); } diff --git a/java/beagle_BeagleJNIWrapper.h b/java/beagle_BeagleJNIWrapper.h new file mode 100644 index 000000000..78897b7ea --- /dev/null +++ b/java/beagle_BeagleJNIWrapper.h @@ -0,0 +1,405 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class beagle_BeagleJNIWrapper */ + +#ifndef _Included_beagle_BeagleJNIWrapper +#define _Included_beagle_BeagleJNIWrapper +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: beagle_BeagleJNIWrapper + * Method: getVersion + * Signature: ()Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_beagle_BeagleJNIWrapper_getVersion + (JNIEnv *, jobject); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getCitation + * Signature: ()Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_beagle_BeagleJNIWrapper_getCitation + (JNIEnv *, jobject); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getResourceList + * Signature: ()[Lbeagle/ResourceDetails; + */ +JNIEXPORT jobjectArray JNICALL Java_beagle_BeagleJNIWrapper_getResourceList + (JNIEnv *, jobject); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getBenchmarkedResourceList + * Signature: (IIIII[IIJJIIIJ)[Lbeagle/BenchmarkedResourceDetails; + */ +JNIEXPORT jobjectArray JNICALL Java_beagle_BeagleJNIWrapper_getBenchmarkedResourceList + (JNIEnv *, jobject, jint, jint, jint, jint, jint, jintArray, jint, jlong, jlong, jint, jint, jint, jlong); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: createInstance + * Signature: (IIIIIIIII[IIJJLbeagle/InstanceDetails;)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_createInstance + (JNIEnv *, jobject, jint, jint, jint, jint, jint, jint, jint, jint, jint, jintArray, jint, jlong, jlong, jobject); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: finalize + * Signature: (I)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_finalize + (JNIEnv *, jobject, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setCPUThreadCount + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCPUThreadCount + (JNIEnv *, jobject, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setPatternWeights + * Signature: (I[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPatternWeights + (JNIEnv *, jobject, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setPatternPartitions + * Signature: (II[I)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPatternPartitions + (JNIEnv *, jobject, jint, jint, jintArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setTipStates + * Signature: (II[I)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTipStates + (JNIEnv *, jobject, jint, jint, jintArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getTipStates + * Signature: (II[I)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getTipStates + (JNIEnv *, jobject, jint, jint, jintArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setTipPartials + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTipPartials + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setRootPrePartials + * Signature: (I[I[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setRootPrePartials + (JNIEnv *, jobject, jint, jintArray, jintArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setPartials + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPartials + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getPartials + * Signature: (III[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getPartials + (JNIEnv *, jobject, jint, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getLogScaleFactors + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getLogScaleFactors + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setEigenDecomposition + * Signature: (II[D[D[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setEigenDecomposition + (JNIEnv *, jobject, jint, jint, jdoubleArray, jdoubleArray, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setSparseMatrix + * Signature: (II[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setSparseMatrix + (JNIEnv *, jobject, jint, jint, jintArray, jintArray, jdoubleArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setSparseDifferentialMatrix + * Signature: (II[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setSparseDifferentialMatrix + (JNIEnv *, jobject, jint, jint, jintArray, jintArray, jdoubleArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setStateFrequencies + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setStateFrequencies + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setCategoryWeights + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryWeights + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setCategoryRates + * Signature: (I[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryRates + (JNIEnv *, jobject, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setCategoryRatesWithIndex + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryRatesWithIndex + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setTransitionMatrix + * Signature: (II[DD)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTransitionMatrix + (JNIEnv *, jobject, jint, jint, jdoubleArray, jdouble); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setDifferentialMatrix + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setDifferentialMatrix + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getTransitionMatrix + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getTransitionMatrix + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: convolveTransitionMatrices + * Signature: (I[I[I[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_convolveTransitionMatrices + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: addTransitionMatrices + * Signature: (I[I[I[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_addTransitionMatrices + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: transposeTransitionMatrices + * Signature: (I[I[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_transposeTransitionMatrices + (JNIEnv *, jobject, jint, jintArray, jintArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: updateTransitionMatrices + * Signature: (II[I[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updateTransitionMatrices + (JNIEnv *, jobject, jint, jint, jintArray, jintArray, jintArray, jdoubleArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: updateTransitionMatricesWithMultipleModels + * Signature: (I[I[I[I[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updateTransitionMatricesWithMultipleModels + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jintArray, jdoubleArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: updatePrePartials + * Signature: (I[III)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePrePartials + (JNIEnv *, jobject, jint, jintArray, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: updatePrePartialsByPartition + * Signature: (I[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePrePartialsByPartition + (JNIEnv *, jobject, jint, jintArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: updatePartials + * Signature: (I[III)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePartials + (JNIEnv *, jobject, jint, jintArray, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: updatePartialsByPartition + * Signature: (I[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePartialsByPartition + (JNIEnv *, jobject, jint, jintArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: waitForPartials + * Signature: (I[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_waitForPartials + (JNIEnv *, jobject, jint, jintArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: accumulateScaleFactors + * Signature: (I[III)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_accumulateScaleFactors + (JNIEnv *, jobject, jint, jintArray, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: accumulateScaleFactorsByPartition + * Signature: (I[IIII)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_accumulateScaleFactorsByPartition + (JNIEnv *, jobject, jint, jintArray, jint, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: removeScaleFactors + * Signature: (I[III)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_removeScaleFactors + (JNIEnv *, jobject, jint, jintArray, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: removeScaleFactorsByPartition + * Signature: (I[IIII)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_removeScaleFactorsByPartition + (JNIEnv *, jobject, jint, jintArray, jint, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: resetScaleFactors + * Signature: (II)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_resetScaleFactors + (JNIEnv *, jobject, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: resetScaleFactorsByPartition + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_resetScaleFactorsByPartition + (JNIEnv *, jobject, jint, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: copyScaleFactors + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_copyScaleFactors + (JNIEnv *, jobject, jint, jint, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: calculateRootLogLikelihoods + * Signature: (I[I[I[I[II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateRootLogLikelihoods + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: calculateRootLogLikelihoodsByPartition + * Signature: (I[I[I[I[I[III[D[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateRootLogLikelihoodsByPartition + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jintArray, jint, jint, jdoubleArray, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: getSiteLogLikelihoods + * Signature: (I[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getSiteLogLikelihoods + (JNIEnv *, jobject, jint, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: calculateEdgeDifferentials + * Signature: (I[I[I[I[II[D[D[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateEdgeDifferentials + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jint, jdoubleArray, jdoubleArray, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: calculateCrossProductDifferentials + * Signature: (I[I[I[I[I[DI[D[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateCrossProductDifferentials + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jdoubleArray, jint, jdoubleArray, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: calculateEdgeDerivative + * Signature: (I[I[II[I[IIII[II[D[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateEdgeDerivative + (JNIEnv *, jobject, jint, jintArray, jintArray, jint, jintArray, jintArray, jint, jint, jint, jintArray, jint, jdoubleArray, jdoubleArray); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libhmsbeagle/BeagleImpl.h b/libhmsbeagle/BeagleImpl.h old mode 100644 new mode 100755 index 0b29bc0f5..104cd0256 --- a/libhmsbeagle/BeagleImpl.h +++ b/libhmsbeagle/BeagleImpl.h @@ -6,20 +6,10 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . - * * @author Andrew Rambaut * @author Marc Suchard * @author Daniel Ayres @@ -42,23 +32,23 @@ class BeagleImpl { public: virtual ~BeagleImpl(){} - + virtual int createInstance(int tipCount, int partialsBufferCount, int compactBufferCount, int stateCount, int patternCount, int eigenBufferCount, - int matrixBufferCount, + int matrixBufferCount, int categoryCount, int scaleBufferCount, int resourceNumber, int pluginResourceNumber, long long preferenceFlags, long long requirementFlags) = 0; - + virtual int getInstanceDetails(BeagleInstanceDetails* returnInfo) = 0; - + virtual int setCPUThreadCount(int threadCount) = 0; virtual int setTipStates(int tipIndex, @@ -66,7 +56,7 @@ class BeagleImpl virtual int setTipPartials(int tipIndex, const double* inPartials) = 0; - + virtual int setPartials(int bufferIndex, const double* inPartials) = 0; @@ -77,28 +67,40 @@ class BeagleImpl virtual int getPartials(int bufferIndex, int scaleIndex, double* outPartials) = 0; - + virtual int setEigenDecomposition(int eigenIndex, const double* inEigenVectors, const double* inInverseEigenVectors, const double* inEigenValues) = 0; - + + virtual int setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros) = 0; + + virtual int setSparseDifferentialMatrix(int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros) = 0; + virtual int setStateFrequencies(int stateFrequenciesIndex, - const double* inStateFrequencies) = 0; - + const double* inStateFrequencies) = 0; + virtual int setCategoryWeights(int categoryWeightsIndex, const double* inCategoryWeights) = 0; - + virtual int setPatternWeights(const double* inPatternWeights) = 0; virtual int setPatternPartitions(int partitionCount, const int* inPatternPartitions) = 0; - + virtual int setCategoryRates(const double* inCategoryRates) = 0; virtual int setCategoryRatesWithIndex(int categoryRatesIndex, const double* inCategoryRates) = 0; - + virtual int setTransitionMatrix(int matrixIndex, const double* inMatrix, double paddedValue) = 0; @@ -109,8 +111,8 @@ class BeagleImpl virtual int setTransitionMatrices(const int* matrixIndices, const double* inMatrices, const double* paddedValues, - int count) = 0; - + int count) = 0; + virtual int getTransitionMatrix(int matrixIndex, double* outMatrix) = 0; @@ -134,6 +136,10 @@ class BeagleImpl const int* secondDerivativeIndices, const double* edgeLengths, int count) = 0; + + virtual int updateTransitionMatricesGrad(const int* probabilityIndices, + const double* edgeLengths, + int count) = 0; virtual int updateTransitionMatricesWithModelCategories(int* eigenIndices, const int* probabilityIndices, @@ -149,7 +155,7 @@ class BeagleImpl const int* secondDerivativeIndices, const double* edgeLengths, int count) = 0; - + virtual int updatePartials(const int* operations, int operationCount, int cumulativeScalingIndex) = 0; @@ -166,7 +172,7 @@ class BeagleImpl virtual int waitForPartials(const int* destinationPartials, int destinationPartialsCount) = 0; - + virtual int accumulateScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex) = 0; @@ -175,7 +181,7 @@ class BeagleImpl int count, int cumulativeScaleIndex, int partitionIndex) = 0; - + virtual int removeScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex) = 0; @@ -184,18 +190,18 @@ class BeagleImpl int count, int cumulativeScaleIndex, int partitionIndex) = 0; - - virtual int resetScaleFactors(int cumulativeScalingIndex) = 0; + + virtual int resetScaleFactors(int cumulativeScalingIndex) = 0; virtual int resetScaleFactorsByPartition(int cumulativeScaleIndex, - int partitionIndex) = 0; - + int partitionIndex) = 0; + virtual int copyScaleFactors(int destScalingIndex, - int srcScalingIndex) = 0; - + int srcScalingIndex) = 0; + virtual int getScaleFactors(int srcScalingIndex, - double* scaleFactors) = 0; - + double* scaleFactors) = 0; + virtual int calculateRootLogLikelihoods(const int* bufferIndices, const int* categoryWeightsIndices, const int* stateFrequenciesIndices, @@ -263,16 +269,54 @@ class BeagleImpl double* outSumFirstDerivative, double* outSumSecondDerivativeByPartition, double* outSumSecondDerivative) = 0; - + virtual int getLogLikelihood(double* outSumLogLikelihood) = 0; virtual int getDerivatives(double* outSumFirstDerivative, double* outSumSecondDerivative) = 0; virtual int getSiteLogLikelihoods(double* outLogLikelihoods) = 0; - + virtual int getSiteDerivatives(double* outFirstDerivatives, double* outSecondDerivatives) = 0; + + virtual int updateBastaPartials(const int* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex) = 0; + + virtual int updateBastaPartialsGrad(const int* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex) = 0; + + virtual int accumulateBastaPartials(const int* operations, + int operationCount, + const int* segments, + int segmentCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out) = 0; + virtual int accumulateBastaPartialsGrad(const int* operations, + int operationCount, + const int* segments, + int segmentCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out) = 0; + + virtual int allocateBastaBuffers(int bufferCount, + int bufferLength) = 0; + + virtual int getBastaBuffer(int bufferIndex, + double* out) = 0; + //protected: int resourceNumber; }; @@ -293,7 +337,7 @@ class BeagleImplFactory { long long preferenceFlags, long long requirementFlags, int* errorCode) = 0; // pure virtual - + virtual const char* getName() = 0; // pure virtual virtual long long getFlags() = 0; // pure virtual diff --git a/libhmsbeagle/CMakeLists.txt b/libhmsbeagle/CMakeLists.txt index 5711dfda7..2c9fabca0 100644 --- a/libhmsbeagle/CMakeLists.txt +++ b/libhmsbeagle/CMakeLists.txt @@ -86,7 +86,35 @@ if (BUILD_ACTION) target_link_libraries(hmsbeagle Eigen3::Eigen) endif(BUILD_ACTION) -set_target_properties(hmsbeagle PROPERTIES PUBLIC_HEADER "beagle.h;platform.h") +if(BEAGLE_BENCHMARK_ENERGY) + find_library(NVIDIA_ML_LIBRARY + NAMES nvidia-ml + PATHS /usr/lib/x86_64-linux-gnu + ) + target_link_libraries(hmsbeagle nvidia-ml) + + if(NOT NVIDIA_ML_LIBRARY) + message(FATAL_ERROR "Nvidia ML library not found") + else() + message(STATUS "Nvidia ML library found at ${NVIDIA_ML_LIBRARY}") + endif() + + + find_package(CUDA) + if(CUDA_FOUND AND BUILD_CUDA) + message(STATUS "CUDA Includes: ${CUDA_INCLUDE_DIRS}") + target_include_directories(hmsbeagle PRIVATE ${CUDA_INCLUDE_DIRS}) + endif(CUDA_FOUND AND BUILD_CUDA) + +endif() + +set_target_properties(hmsbeagle PROPERTIES + PUBLIC_HEADER "beagle.h;platform.h" + VERSION ${GENERIC_API_VERSION}) + +if(NOT WIN32 AND NOT APPLE) + target_link_libraries(hmsbeagle ${CMAKE_DL_LIBS}) +endif(NOT WIN32 AND NOT APPLE) add_subdirectory(CPU) add_subdirectory(GPU) @@ -94,12 +122,43 @@ if(BUILD_JNI) add_subdirectory(JNI) endif(BUILD_JNI) +set(PKG "hmsbeagle-${GENERIC_API_VERSION}") + install(TARGETS hmsbeagle + EXPORT ${PKG} LIBRARY DESTINATION ${BEAGLE_INSTALL_DIR} PUBLIC_HEADER DESTINATION ${BEAGLE_HEADER_DIR} COMPONENT main + ) + +include(CMakePackageConfigHelpers) + +write_basic_package_version_file( + ${PKG}ConfigVersion.cmake + VERSION ${BEAGLE_VERSION} + COMPATIBILITY AnyNewerVersion ) +install(EXPORT ${PKG} + FILE ${PKG}Config.cmake + NAMESPACE ${PKG}-${BEAGLE_VERSION}:: + DESTINATION lib/cmake/${PKG} + ) + +install(FILES "${CMAKE_CURRENT_BINARY_DIR}/hmsbeagle-1ConfigVersion.cmake" + DESTINATION lib/cmake/${PKG} + ) + +configure_file( + ${PKG}.pc.in + ${PKG}.pc + @ONLY +) + +install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PKG}.pc" + DESTINATION lib/pkg-config +) + if(WIN32) SET_TARGET_PROPERTIES(hmsbeagle PROPERTIES diff --git a/libhmsbeagle/CPU/AVXDefinitions.h b/libhmsbeagle/CPU/AVXDefinitions.h index 92e070bfe..1a72b61c7 100644 --- a/libhmsbeagle/CPU/AVXDefinitions.h +++ b/libhmsbeagle/CPU/AVXDefinitions.h @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ diff --git a/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.h b/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.h index 15391bcd7..d5702094a 100644 --- a/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.h +++ b/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.h @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -48,11 +38,11 @@ namespace cpu { BEAGLE_CPU_TEMPLATE class BeagleCPU4StateAVXImpl : public BeagleCPU4StateImpl {}; - + BEAGLE_CPU_4_AVX_TEMPLATE class BeagleCPU4StateAVXImpl : public BeagleCPU4StateImpl { - + protected: using BeagleCPUImpl::kTipCount; using BeagleCPUImpl::gPartials; @@ -70,56 +60,56 @@ class BeagleCPU4StateAVXImpl : public BeagleCPU4StateImp using BeagleCPUImpl::realtypeMin; using BeagleCPUImpl::outLogLikelihoodsTmp; using BeagleCPUImpl::gPatternWeights; - -public: + +public: virtual const char* getName(); virtual long long getFlags(); - + protected: - virtual int getPaddedPatternsModulus(); - + virtual int getPaddedPatternsModulus(); + private: - + virtual void calcStatesStates(float* destP, const int* states1, const float* matrices1, const int* states2, const float* matrices2); - + virtual void calcStatesPartials(float* destP, const int* states1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2); - + virtual void calcStatesPartialsFixedScaling(float* destP, const int* states1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2, const float* __restrict scaleFactors); - + virtual void calcPartialsPartials(float* __restrict destP, const float* __restrict partials1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2); - + virtual void calcPartialsPartialsFixedScaling(float* __restrict destP, const float* __restrict child0Partials, const float* __restrict child0TransMat, const float* __restrict child1Partials, const float* __restrict child1TransMat, const float* __restrict scaleFactors); - + virtual void calcPartialsPartialsAutoScaling(float* __restrict destP, const float* __restrict partials1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2, int* activateScaling); - + virtual int calcEdgeLogLikelihoods(const int parentBufferIndex, const int childBufferIndex, const int probabilityIndex, @@ -127,13 +117,13 @@ class BeagleCPU4StateAVXImpl : public BeagleCPU4StateImp const int stateFrequenciesIndex, const int scalingFactorsIndex, double* outSumLogLikelihood); - + }; - + BEAGLE_CPU_4_AVX_TEMPLATE class BeagleCPU4StateAVXImpl : public BeagleCPU4StateImpl { - + protected: using BeagleCPUImpl::kTipCount; using BeagleCPUImpl::gPartials; @@ -151,7 +141,7 @@ class BeagleCPU4StateAVXImpl : public BeagleCPU4StateIm using BeagleCPUImpl::realtypeMin; using BeagleCPUImpl::outLogLikelihoodsTmp; using BeagleCPUImpl::gPatternWeights; - + public: virtual const char* getName(); @@ -159,48 +149,48 @@ class BeagleCPU4StateAVXImpl : public BeagleCPU4StateIm protected: virtual int getPaddedPatternsModulus(); - + private: - + virtual void calcStatesStates(double* destP, const int* states1, const double* matrices1, const int* states2, const double* matrices2); - + virtual void calcStatesPartials(double* destP, const int* states1, const double* __restrict matrices1, const double* __restrict partials2, const double* __restrict matrices2); - + virtual void calcStatesPartialsFixedScaling(double* destP, const int* states1, const double* __restrict matrices1, const double* __restrict partials2, const double* __restrict matrices2, const double* __restrict scaleFactors); - + virtual void calcPartialsPartials(double* __restrict destP, const double* __restrict partials1, const double* __restrict matrices1, const double* __restrict partials2, const double* __restrict matrices2); - + virtual void calcPartialsPartialsFixedScaling(double* __restrict destP, const double* __restrict child0Partials, const double* __restrict child0TransMat, const double* __restrict child1Partials, const double* __restrict child1TransMat, const double* __restrict scaleFactors); - + virtual void calcPartialsPartialsAutoScaling(double* __restrict destP, const double* __restrict partials1, const double* __restrict matrices1, const double* __restrict partials2, const double* __restrict matrices2, int* activateScaling); - + virtual int calcEdgeLogLikelihoods(const int parentBufferIndex, const int childBufferIndex, const int probabilityIndex, @@ -208,10 +198,10 @@ class BeagleCPU4StateAVXImpl : public BeagleCPU4StateIm const int stateFrequenciesIndex, const int scalingFactorsIndex, double* outSumLogLikelihood); - + }; - - + + BEAGLE_CPU_FACTORY_TEMPLATE class BeagleCPU4StateAVXImplFactory : public BeagleImplFactory { public: diff --git a/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.hpp b/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.hpp index 75a1ff710..0db2a2663 100644 --- a/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.hpp +++ b/libhmsbeagle/CPU/BeagleCPU4StateAVXImpl.hpp @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -109,7 +99,7 @@ inline const char* getBeagleCPU4StateAVXName(){ return "CPU-4State-AVX-D template<> inline const char* getBeagleCPU4StateAVXName(){ return "CPU-4State-AVX-Single"; }; - + /* * Calculates partial likelihoods at a node when both children have states. */ @@ -349,7 +339,7 @@ void BeagleCPU4StateAVXImpl::calcPartialsPartials(doubl // fprintf(stderr,"APM\n"); for (int k = 0; k < kPatternCount; k++) { - + # if 1 && !defined(_WIN32) __builtin_prefetch (&partials_q[v+64]); __builtin_prefetch (&partials_r[v+64]); @@ -462,7 +452,7 @@ void BeagleCPU4StateAVXImpl::calcPartialsPartialsFixedS __builtin_prefetch (&partials_r[v+64]); // __builtin_prefetch (destPvec+32,1,0); # endif - + // Prefetch scale factor // const V_Real scaleFactor = VEC_LOAD_SCALAR(scaleFactors + k); // Option below appears faster, why? @@ -507,7 +497,7 @@ void BeagleCPU4StateAVXImpl::calcPartialsPartialsFixedS } } - + BEAGLE_CPU_4_AVX_TEMPLATE void BeagleCPU4StateAVXImpl::calcPartialsPartialsAutoScaling(float* destP, const float* partials_q, @@ -538,7 +528,7 @@ void BeagleCPU4StateAVXImpl::calcPartialsPartialsAutoSc matrices_r, activateScaling); } - + BEAGLE_CPU_4_AVX_TEMPLATE int BeagleCPU4StateAVXImpl::calcEdgeLogLikelihoods(const int parIndex, const int childIndex, @@ -677,7 +667,7 @@ int BeagleCPU4StateAVXImpl::calcEdgeLogLikelihoods(cons if (*outSumLogLikelihood != *outSumLogLikelihood) returnCode = BEAGLE_ERROR_FLOATING_POINT; - + return returnCode; } @@ -688,7 +678,7 @@ int BeagleCPU4StateAVXImpl::getPaddedPatternsModulus() { // return 4; // For single-precision, can operate on 4 patterns at a time // TODO Vectorize final log operations over patterns } - + BEAGLE_CPU_4_AVX_TEMPLATE int BeagleCPU4StateAVXImpl::getPaddedPatternsModulus() { // return 2; // For double-precision, can operate on 2 patterns at a time @@ -705,7 +695,7 @@ const char* BeagleCPU4StateAVXImpl::getName() { return getBeagleCPU4StateAVXName(); } - + BEAGLE_CPU_4_AVX_TEMPLATE long BeagleCPU4StateAVXImpl::getFlags() { return BEAGLE_FLAG_COMPUTATION_SYNCH | @@ -791,7 +781,7 @@ long BeagleCPU4StateAVXImplFactory::getFlags() { BEAGLE_FLAG_SCALERS_LOG | BEAGLE_FLAG_SCALERS_RAW | BEAGLE_FLAG_EIGEN_COMPLEX | BEAGLE_FLAG_EIGEN_REAL| BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED | - BEAGLE_FLAG_FRAMEWORK_CPU; + BEAGLE_FLAG_FRAMEWORK_CPU; } template <> @@ -805,7 +795,7 @@ long BeagleCPU4StateAVXImplFactory::getFlags() { BEAGLE_FLAG_SCALERS_LOG | BEAGLE_FLAG_SCALERS_RAW | BEAGLE_FLAG_EIGEN_COMPLEX | BEAGLE_FLAG_EIGEN_REAL | BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED | - BEAGLE_FLAG_FRAMEWORK_CPU; + BEAGLE_FLAG_FRAMEWORK_CPU; } diff --git a/libhmsbeagle/CPU/BeagleCPU4StateImpl.h b/libhmsbeagle/CPU/BeagleCPU4StateImpl.h index 8b22f4a21..d3e3c4fcb 100644 --- a/libhmsbeagle/CPU/BeagleCPU4StateImpl.h +++ b/libhmsbeagle/CPU/BeagleCPU4StateImpl.h @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Andrew Rambaut * @author Marc Suchard @@ -87,7 +77,7 @@ class BeagleCPU4StateImpl : public BeagleCPUImpl { const REALTYPE* matrices2, int startPattern, int endPattern); - + virtual void calcStatesPartials(REALTYPE* destP, const int* states1, const REALTYPE* matrices1, @@ -95,7 +85,7 @@ class BeagleCPU4StateImpl : public BeagleCPUImpl { const REALTYPE* matrices2, int startPattern, int endPattern); - + virtual void calcPartialsPartials(REALTYPE* destP, const REALTYPE* partials1, const REALTYPE* matrices1, @@ -121,25 +111,27 @@ class BeagleCPU4StateImpl : public BeagleCPUImpl { int endPattern); virtual void calcEdgeLogDerivativesStates(const int *tipStates, - const REALTYPE *preOrderPartial, - const int firstDerivativeIndex, - const int secondDerivativeIndex, - const double *categoryRates, - const REALTYPE *categoryWeights, - double *outDerivatives, - double *outSumDerivatives, - double *outSumSquaredDerivatives); + const REALTYPE *preOrderPartial, + const int firstDerivativeIndex, + const int secondDerivativeIndex, + const double *categoryRates, + const REALTYPE *categoryWeights, + double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int cacheOffset); virtual void calcEdgeLogDerivativesPartials(const REALTYPE *postOrderPartial, - const REALTYPE *preOrderPartial, - const int firstDerivativeIndex, - const int secondDerivativeIndex, - const double *categoryRates, - const REALTYPE *categoryWeights, - const int scalingFactorsIndex, - double *outDerivatives, - double *outSumDerivatives, - double *outSumSquaredDerivatives); + const REALTYPE *preOrderPartial, + const int firstDerivativeIndex, + const int secondDerivativeIndex, + const double *categoryRates, + const REALTYPE *categoryWeights, + const int scalingFactorsIndex, + double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int cacheOffset); virtual void calcCrossProductsStates(const int *tipStates, const REALTYPE *preOrderPartial, @@ -170,14 +162,14 @@ class BeagleCPU4StateImpl : public BeagleCPUImpl { const int* partitionIndices, int partitionCount, double* outSumLogLikelihoodByPartition); - + virtual int calcRootLogLikelihoodsMulti(const int* bufferIndices, const int* categoryWeightsIndices, const int* stateFrequenciesIndices, const int* scaleBufferIndices, int count, - double* outSumLogLikelihood); - + double* outSumLogLikelihood); + virtual int calcEdgeLogLikelihoods(const int parentBufferIndex, const int childBufferIndex, const int probabilityIndex, @@ -195,7 +187,7 @@ class BeagleCPU4StateImpl : public BeagleCPUImpl { const int* partitionIndices, int partitionCount, double* outSumLogLikelihoodByPartition); - + virtual void calcStatesStatesFixedScaling(REALTYPE *destP, const int *child0States, const REALTYPE *child0TransMat, @@ -222,15 +214,15 @@ class BeagleCPU4StateImpl : public BeagleCPUImpl { const REALTYPE *scaleFactors, int startPattern, int endPattern); - + virtual void calcPartialsPartialsAutoScaling(REALTYPE *destP, const REALTYPE *child0Partials, const REALTYPE *child0TransMat, const REALTYPE *child1Partials, const REALTYPE *child1TransMat, int *activateScaling); - - + + inline int integrateOutStatesAndScale(const REALTYPE* integrationTmp, const int stateFrequenciesIndex, const int scalingFactorsIndex, diff --git a/libhmsbeagle/CPU/BeagleCPU4StateImpl.hpp b/libhmsbeagle/CPU/BeagleCPU4StateImpl.hpp index e286a3ace..f4d4c756e 100644 --- a/libhmsbeagle/CPU/BeagleCPU4StateImpl.hpp +++ b/libhmsbeagle/CPU/BeagleCPU4StateImpl.hpp @@ -7,19 +7,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Andrew Rambaut * @author Marc Suchard @@ -215,13 +205,13 @@ void BeagleCPU4StateImpl::calcStatesStates(REALTYPE* destP, const int state1 = states1[k]; const int state2 = states2[k]; - destP[v ] = matrices1[w + state1] * + destP[v ] = matrices1[w + state1] * matrices2[w + state2]; - destP[v + 1] = matrices1[w + OFFSET*1 + state1] * + destP[v + 1] = matrices1[w + OFFSET*1 + state1] * matrices2[w + OFFSET*1 + state2]; - destP[v + 2] = matrices1[w + OFFSET*2 + state1] * + destP[v + 2] = matrices1[w + OFFSET*2 + state1] * matrices2[w + OFFSET*2 + state2]; - destP[v + 3] = matrices1[w + OFFSET*3 + state1] * + destP[v + 3] = matrices1[w + OFFSET*3 + state1] * matrices2[w + OFFSET*3 + state2]; v += 4; } @@ -246,20 +236,20 @@ void BeagleCPU4StateImpl::calcStatesStatesFixedScaling(REALT } int w = l*4*OFFSET; - + for (int k = startPattern; k < endPattern; k++) { - + const int state1 = states1[k]; const int state2 = states2[k]; const REALTYPE scaleFactor = scaleFactors[k]; - - destP[v ] = matrices1[w + state1] * + + destP[v ] = matrices1[w + state1] * matrices2[w + state2] / scaleFactor; - destP[v + 1] = matrices1[w + OFFSET*1 + state1] * + destP[v + 1] = matrices1[w + OFFSET*1 + state1] * matrices2[w + OFFSET*1 + state2] / scaleFactor; - destP[v + 2] = matrices1[w + OFFSET*2 + state1] * + destP[v + 2] = matrices1[w + OFFSET*2 + state1] * matrices2[w + OFFSET*2 + state2] / scaleFactor; - destP[v + 3] = matrices1[w + OFFSET*3 + state1] * + destP[v + 3] = matrices1[w + OFFSET*3 + state1] * matrices2[w + OFFSET*3 + state2] / scaleFactor; v += 4; } @@ -286,22 +276,22 @@ void BeagleCPU4StateImpl::calcStatesPartials(REALTYPE* destP } int w = l*4*OFFSET; - + PREFETCH_MATRIX(2,matrices2,w); - + for (int k = startPattern; k < endPattern; k++) { - + const int state1 = states1[k]; - + PREFETCH_PARTIALS(2,partials2,u); - + DO_INTEGRATION(2); // defines sum20, sum21, sum22, sum23; - + destP[u ] = matrices1[w + state1] * sum20; destP[u + 1] = matrices1[w + OFFSET*1 + state1] * sum21; destP[u + 2] = matrices1[w + OFFSET*2 + state1] * sum22; destP[u + 3] = matrices1[w + OFFSET*3 + state1] * sum23; - + u += 4; } } @@ -325,26 +315,26 @@ void BeagleCPU4StateImpl::calcStatesPartialsFixedScaling(REA } int w = l*4*OFFSET; - + PREFETCH_MATRIX(2,matrices2,w); - + for (int k = startPattern; k < endPattern; k++) { - + const int state1 = states1[k]; const REALTYPE scaleFactor = scaleFactors[k]; - + PREFETCH_PARTIALS(2,partials2,u); - + DO_INTEGRATION(2); // defines sum20, sum21, sum22, sum23 - + destP[u ] = matrices1[w + state1] * sum20 / scaleFactor; destP[u + 1] = matrices1[w + OFFSET*1 + state1] * sum21 / scaleFactor; destP[u + 2] = matrices1[w + OFFSET*2 + state1] * sum22 / scaleFactor; destP[u + 3] = matrices1[w + OFFSET*3 + state1] * sum23 / scaleFactor; - - u += 4; + + u += 4; } - } + } } BEAGLE_CPU_TEMPLATE @@ -355,8 +345,8 @@ void BeagleCPU4StateImpl::calcPartialsPartials(REALTYPE* des const REALTYPE* matrices2, int startPattern, int endPattern) { - - + + #pragma omp parallel for num_threads(kCategoryCount) for (int l = 0; l < kCategoryCount; l++) { int u = l*4*kPaddedPatternCount; @@ -364,16 +354,16 @@ void BeagleCPU4StateImpl::calcPartialsPartials(REALTYPE* des u += 4*startPattern; } int w = l*4*OFFSET; - - PREFETCH_MATRIX(1,matrices1,w); + + PREFETCH_MATRIX(1,matrices1,w); PREFETCH_MATRIX(2,matrices2,w); - for (int k = startPattern; k < endPattern; k++) { + for (int k = startPattern; k < endPattern; k++) { PREFETCH_PARTIALS(1,partials1,u); PREFETCH_PARTIALS(2,partials2,u); - + DO_INTEGRATION(1); // defines sum10, sum11, sum12, sum13 DO_INTEGRATION(2); // defines sum20, sum21, sum22, sum23 - + // Final results destP[u ] = sum10 * sum20; destP[u + 1] = sum11 * sum21; @@ -477,28 +467,28 @@ void BeagleCPU4StateImpl::calcPartialsPartialsAutoScaling(RE const REALTYPE* partials2, const REALTYPE* matrices2, int* activateScaling) { - - + + #pragma omp parallel for num_threads(kCategoryCount) for (int l = 0; l < kCategoryCount; l++) { int u = l*4*kPaddedPatternCount; int w = l*4*OFFSET; - - PREFETCH_MATRIX(1,matrices1,w); + + PREFETCH_MATRIX(1,matrices1,w); PREFETCH_MATRIX(2,matrices2,w); - for (int k = 0; k < kPatternCount; k++) { + for (int k = 0; k < kPatternCount; k++) { PREFETCH_PARTIALS(1,partials1,u); PREFETCH_PARTIALS(2,partials2,u); - + DO_INTEGRATION(1); // defines sum10, sum11, sum12, sum13 DO_INTEGRATION(2); // defines sum20, sum21, sum22, sum23 - + // Final results destP[u ] = sum10 * sum20; destP[u + 1] = sum11 * sum21; destP[u + 2] = sum12 * sum22; destP[u + 3] = sum13 * sum23; - + if (*activateScaling == 0) { int expTmp; int expMax; @@ -517,13 +507,13 @@ void BeagleCPU4StateImpl::calcPartialsPartialsAutoScaling(RE *activateScaling = 1; } } - + u += 4; - + } } } - + BEAGLE_CPU_TEMPLATE void BeagleCPU4StateImpl::calcPartialsPartialsFixedScaling(REALTYPE* destP, @@ -543,30 +533,30 @@ void BeagleCPU4StateImpl::calcPartialsPartialsFixedScaling(R } int w = l*4*OFFSET; - + PREFETCH_MATRIX(1,matrices1,w); PREFETCH_MATRIX(2,matrices2,w); - + for (int k = startPattern; k < endPattern; k++) { - + // Prefetch scale factor const REALTYPE scaleFactor = scaleFactors[k]; - + PREFETCH_PARTIALS(1,partials1,u); PREFETCH_PARTIALS(2,partials2,u); - + DO_INTEGRATION(1); // defines sum10, sum11, sum12, sum13 DO_INTEGRATION(2); // defines sum20, sum21, sum22, sum23 - + // Final results destP[u ] = sum10 * sum20 / scaleFactor; destP[u + 1] = sum11 * sum21 / scaleFactor; destP[u + 2] = sum12 * sum22 / scaleFactor; destP[u + 3] = sum13 * sum23 / scaleFactor; - + u += 4; } - } + } } BEAGLE_CPU_TEMPLATE @@ -574,15 +564,15 @@ int inline BeagleCPU4StateImpl::integrateOutStatesAndScale(c const int stateFrequenciesIndex, const int scalingFactorsIndex, double* outSumLogLikelihood) { - + int returnCode = BEAGLE_SUCCESS; - + REALTYPE freq0, freq1, freq2, freq3; - freq0 = gStateFrequencies[stateFrequenciesIndex][0]; + freq0 = gStateFrequencies[stateFrequenciesIndex][0]; freq1 = gStateFrequencies[stateFrequenciesIndex][1]; freq2 = gStateFrequencies[stateFrequenciesIndex][2]; freq3 = gStateFrequencies[stateFrequenciesIndex][3]; - + int u = 0; for(int k = 0; k < kPatternCount; k++) { REALTYPE sumOverI = @@ -590,11 +580,11 @@ int inline BeagleCPU4StateImpl::integrateOutStatesAndScale(c freq1 * integrationTmp[u + 1] + freq2 * integrationTmp[u + 2] + freq3 * integrationTmp[u + 3]; - + u += 4; - + outLogLikelihoodsTmp[k] = log(sumOverI); - } + } if (scalingFactorsIndex != BEAGLE_OP_NONE) { const REALTYPE* scalingFactors = gScaleBuffers[scalingFactorsIndex]; @@ -602,15 +592,15 @@ int inline BeagleCPU4StateImpl::integrateOutStatesAndScale(c outLogLikelihoodsTmp[k] += scalingFactors[k]; } } - - *outSumLogLikelihood = 0.0; + + *outSumLogLikelihood = 0.0; for(int k=0; k < kPatternCount; k++) { *outSumLogLikelihood += outLogLikelihoodsTmp[k] * gPatternWeights[k]; - } - + } + if (*outSumLogLikelihood != *outSumLogLikelihood) returnCode = BEAGLE_ERROR_FLOATING_POINT; - + return returnCode; } @@ -622,7 +612,7 @@ void inline BeagleCPU4StateImpl::integrateOutStatesAndScaleB const int* partitionIndices, int partitionCount, double* outSumLogLikelihoodByPartition) { - + for (int p = 0; p < partitionCount; p++) { int pIndex = partitionIndices[p]; @@ -633,7 +623,7 @@ void inline BeagleCPU4StateImpl::integrateOutStatesAndScaleB const int scalingFactorsIndex = cumulativeScaleIndices[p]; REALTYPE freq0, freq1, freq2, freq3; - freq0 = gStateFrequencies[stateFrequenciesIndex][0]; + freq0 = gStateFrequencies[stateFrequenciesIndex][0]; freq1 = gStateFrequencies[stateFrequenciesIndex][1]; freq2 = gStateFrequencies[stateFrequenciesIndex][2]; freq3 = gStateFrequencies[stateFrequenciesIndex][3]; @@ -645,11 +635,11 @@ void inline BeagleCPU4StateImpl::integrateOutStatesAndScaleB freq1 * integrationTmp[u + 1] + freq2 * integrationTmp[u + 2] + freq3 * integrationTmp[u + 3]; - + u += 4; - + outLogLikelihoodsTmp[k] = log(sumOverI); - } + } if (scalingFactorsIndex != BEAGLE_OP_NONE) { const REALTYPE* scalingFactors = gScaleBuffers[scalingFactorsIndex]; @@ -657,13 +647,13 @@ void inline BeagleCPU4StateImpl::integrateOutStatesAndScaleB outLogLikelihoodsTmp[k] += scalingFactors[k]; } } - + outSumLogLikelihoodByPartition[p] = 0.0; for(int k=startPattern; k < endPattern; k++) { outSumLogLikelihoodByPartition[p] += outLogLikelihoodsTmp[k] * gPatternWeights[k]; } } - + } #define FAST_MAX(x,y) (x > y ? x : y) @@ -680,7 +670,7 @@ void BeagleCPU4StateImpl::rescalePartials(REALTYPE* destP, bool useLogScalars = kFlags & BEAGLE_FLAG_SCALERS_LOG; for (int k = 0; k < kPatternCount; k++) { - REALTYPE max = 0; + REALTYPE max = 0; const int patternOffset = k * 4; for (int l = 0; l < kCategoryCount; l++) { int offset = l * kPaddedPatternCount * 4 + patternOffset; @@ -738,7 +728,7 @@ void BeagleCPU4StateImpl::rescalePartialsByPartition( int endPattern = gPatternPartitionsStartPatterns[partitionIndex + 1]; for (int k = startPattern; k < endPattern; k++) { - REALTYPE max = 0; + REALTYPE max = 0; const int patternOffset = k * 4; for (int l = 0; l < kCategoryCount; l++) { int offset = l * kPaddedPatternCount * 4 + patternOffset; @@ -792,73 +782,73 @@ int BeagleCPU4StateImpl::calcEdgeLogLikelihoods(const int pa const int scalingFactorsIndex, double* outSumLogLikelihood) { // TODO: implement derivatives for calculateEdgeLnL - + assert(parIndex >= kTipCount); - + const REALTYPE* partialsParent = gPartials[parIndex]; const REALTYPE* transMatrix = gTransitionMatrices[probIndex]; const REALTYPE* wt = gCategoryWeights[categoryWeightsIndex]; - + memset(integrationTmp, 0, (kPatternCount * kStateCount)*sizeof(REALTYPE)); - + if (childIndex < kTipCount && gTipStates[childIndex]) { // Integrate against a state at the child - - const int* statesChild = gTipStates[childIndex]; + + const int* statesChild = gTipStates[childIndex]; int v = 0; // Index for parent partials int w = 0; for(int l = 0; l < kCategoryCount; l++) { int u = 0; // Index in resulting product-partials (summed over categories) const REALTYPE weight = wt[l]; for(int k = 0; k < kPatternCount; k++) { - - const int stateChild = statesChild[k]; - - integrationTmp[u ] += transMatrix[w + stateChild] * partialsParent[v ] * weight; + + const int stateChild = statesChild[k]; + + integrationTmp[u ] += transMatrix[w + stateChild] * partialsParent[v ] * weight; integrationTmp[u + 1] += transMatrix[w + OFFSET*1 + stateChild] * partialsParent[v + 1] * weight; integrationTmp[u + 2] += transMatrix[w + OFFSET*2 + stateChild] * partialsParent[v + 2] * weight; integrationTmp[u + 3] += transMatrix[w + OFFSET*3 + stateChild] * partialsParent[v + 3] * weight; - + u += 4; - v += 4; + v += 4; } w += OFFSET*4; if (kExtraPatterns) v += 4 * kExtraPatterns; } - + } else { // Integrate against a partial at the child - + const REALTYPE* partialsChild = gPartials[childIndex]; #if 0// int v = 0; #endif int w = 0; - for(int l = 0; l < kCategoryCount; l++) { + for(int l = 0; l < kCategoryCount; l++) { int u = 0; #if 1// int v = l*kPaddedPatternCount*4; #endif const REALTYPE weight = wt[l]; - + PREFETCH_MATRIX(1,transMatrix,w); - - for(int k = 0; k < kPatternCount; k++) { - + + for(int k = 0; k < kPatternCount; k++) { + const REALTYPE* partials1 = partialsChild; - + PREFETCH_PARTIALS(1,partials1,v); - + DO_INTEGRATION(1); - + integrationTmp[u ] += sum10 * partialsParent[v ] * weight; integrationTmp[u + 1] += sum11 * partialsParent[v + 1] * weight; integrationTmp[u + 2] += sum12 * partialsParent[v + 2] * weight; integrationTmp[u + 3] += sum13 * partialsParent[v + 3] * weight; - + u += 4; v += 4; - } + } w += OFFSET*4; #if 0// if (kExtraPatterns) @@ -884,7 +874,7 @@ void BeagleCPU4StateImpl::calcEdgeLogLikelihoodsByPartition( for (int p = 0; p < partitionCount; p++) { int pIndex = partitionIndices[p]; - + int startPattern = gPatternPartitionsStartPatterns[pIndex]; int endPattern = gPatternPartitionsStartPatterns[pIndex + 1]; @@ -896,30 +886,30 @@ void BeagleCPU4StateImpl::calcEdgeLogLikelihoodsByPartition( const int categoryWeightsIndex = categoryWeightsIndices[p]; assert(parIndex >= kTipCount); - + const REALTYPE* partialsParent = gPartials[parIndex]; const REALTYPE* transMatrix = gTransitionMatrices[probIndex]; const REALTYPE* wt = gCategoryWeights[categoryWeightsIndex]; - + if (childIndex < kTipCount && gTipStates[childIndex]) { // Integrate against a state at the child - - const int* statesChild = gTipStates[childIndex]; + + const int* statesChild = gTipStates[childIndex]; int v = startPattern * 4; // Index for parent partials int w = 0; for(int l = 0; l < kCategoryCount; l++) { int u = startPattern * 4; // Index in resulting product-partials (summed over categories) const REALTYPE weight = wt[l]; for(int k = startPattern; k < endPattern; k++) { - - const int stateChild = statesChild[k]; - - integrationTmp[u ] += transMatrix[w + stateChild] * partialsParent[v ] * weight; + + const int stateChild = statesChild[k]; + + integrationTmp[u ] += transMatrix[w + stateChild] * partialsParent[v ] * weight; integrationTmp[u + 1] += transMatrix[w + OFFSET*1 + stateChild] * partialsParent[v + 1] * weight; integrationTmp[u + 2] += transMatrix[w + OFFSET*2 + stateChild] * partialsParent[v + 2] * weight; integrationTmp[u + 3] += transMatrix[w + OFFSET*3 + stateChild] * partialsParent[v + 3] * weight; - + u += 4; - v += 4; + v += 4; } w += OFFSET*4; if (kExtraPatterns) @@ -932,31 +922,31 @@ void BeagleCPU4StateImpl::calcEdgeLogLikelihoodsByPartition( int v = 0; #endif int w = 0; - for(int l = 0; l < kCategoryCount; l++) { + for(int l = 0; l < kCategoryCount; l++) { int u = startPattern * 4; #if 1// int v = l*kPaddedPatternCount*4 + startPattern * 4; #endif const REALTYPE weight = wt[l]; - + PREFETCH_MATRIX(1,transMatrix,w); - - for(int k = startPattern; k < endPattern; k++) { - + + for(int k = startPattern; k < endPattern; k++) { + const REALTYPE* partials1 = partialsChild; - + PREFETCH_PARTIALS(1,partials1,v); - + DO_INTEGRATION(1); - + integrationTmp[u ] += sum10 * partialsParent[v ] * weight; integrationTmp[u + 1] += sum11 * partialsParent[v + 1] * weight; integrationTmp[u + 2] += sum12 * partialsParent[v + 2] * weight; integrationTmp[u + 3] += sum13 * partialsParent[v + 3] * weight; - + u += 4; v += 4; - } + } w += OFFSET*4; #if 0// if (kExtraPatterns) @@ -999,13 +989,13 @@ int BeagleCPU4StateImpl::calcRootLogLikelihoods(const int bu integrationTmp[u + 1] += rootPartials[v + 1] * wtl; integrationTmp[u + 2] += rootPartials[v + 2] * wtl; integrationTmp[u + 3] += rootPartials[v + 3] * wtl; - + u += 4; v += 4; } v += 4 * kExtraPatterns; } - + return integrateOutStatesAndScale(integrationTmp, stateFrequenciesIndex, scalingFactorsIndex, outSumLogLikelihood); } @@ -1018,7 +1008,8 @@ void BeagleCPU4StateImpl::calcEdgeLogDerivativesStates(const const REALTYPE *categoryWeights, double *outDerivatives, double *outSumDerivatives, - double *outSumSquaredDerivatives) { + double *outSumSquaredDerivatives, + int cacheOffset) { for (int category = 0; category < kCategoryCount; category++) { @@ -1057,7 +1048,8 @@ void BeagleCPU4StateImpl::calcEdgeLogDerivativesPartials(con const int scalingFactorsIndex, double *outDerivatives, double *outSumDerivatives, - double *outSumSquaredDerivatives) { + double *outSumSquaredDerivatives, + int cacheOffset) { const REALTYPE* transMatrix = gTransitionMatrices[firstDerivativeIndex]; @@ -1276,14 +1268,14 @@ void BeagleCPU4StateImpl::calcRootLogLikelihoodsByPartition( for (int p = 0; p < partitionCount; p++) { int pIndex = partitionIndices[p]; - + int startPattern = gPatternPartitionsStartPatterns[pIndex]; int endPattern = gPatternPartitionsStartPatterns[pIndex + 1]; const REALTYPE* rootPartials = gPartials[bufferIndices[p]]; assert(rootPartials); const REALTYPE* wt = gCategoryWeights[categoryWeightsIndices[p]]; - + int v = startPattern * 4; const REALTYPE wt0 = wt[0]; for (int k = startPattern; k < endPattern; k++) { @@ -1302,7 +1294,7 @@ void BeagleCPU4StateImpl::calcRootLogLikelihoodsByPartition( integrationTmp[u + 1] += rootPartials[v + 1] * wtl; integrationTmp[u + 2] += rootPartials[v + 2] * wtl; integrationTmp[u + 3] += rootPartials[v + 3] * wtl; - + u += 4; v += 4; } @@ -1319,12 +1311,12 @@ int BeagleCPU4StateImpl::calcRootLogLikelihoodsMulti(const i const int* scaleBufferIndices, int count, double* outSumLogLikelihood) { - + int returnCode = BEAGLE_SUCCESS; - + std::vector indexMaxScale(kPatternCount); std::vector maxScaleFactor(kPatternCount); - + for (int subsetIndex = 0 ; subsetIndex < count; ++subsetIndex ) { const int rootPartialIndex = bufferIndices[subsetIndex]; const REALTYPE* rootPartials = gPartials[rootPartialIndex]; @@ -1332,7 +1324,7 @@ int BeagleCPU4StateImpl::calcRootLogLikelihoodsMulti(const i const REALTYPE* wt = gCategoryWeights[categoryWeightsIndices[subsetIndex]]; int u = 0; int v = 0; - + const REALTYPE wt0 = wt[0]; for (int k = 0; k < kPatternCount; k++) { integrationTmp[v ] = rootPartials[v ] * wt0; @@ -1349,88 +1341,88 @@ int BeagleCPU4StateImpl::calcRootLogLikelihoodsMulti(const i integrationTmp[u + 1] += rootPartials[v + 1] * wtl; integrationTmp[u + 2] += rootPartials[v + 2] * wtl; integrationTmp[u + 3] += rootPartials[v + 3] * wtl; - + u += 4; v += 4; } v += 4 * kExtraPatterns; } - + REALTYPE freq0, freq1, freq2, freq3; - freq0 = frequencies[0]; + freq0 = frequencies[0]; freq1 = frequencies[1]; freq2 = frequencies[2]; freq3 = frequencies[3]; - + u = 0; for (int k = 0; k < kPatternCount; k++) { - REALTYPE sum = + REALTYPE sum = freq0 * integrationTmp[u ] + freq1 * integrationTmp[u + 1] + freq2 * integrationTmp[u + 2] + freq3 * integrationTmp[u + 3]; - - u += 4; - + + u += 4; + // TODO: allow only some subsets to have scale indices if (scaleBufferIndices[0] != BEAGLE_OP_NONE || (kFlags & BEAGLE_FLAG_SCALING_ALWAYS)) { int cumulativeScalingFactorIndex; if (kFlags & BEAGLE_FLAG_SCALING_ALWAYS) - cumulativeScalingFactorIndex = rootPartialIndex - kTipCount; + cumulativeScalingFactorIndex = rootPartialIndex - kTipCount; else cumulativeScalingFactorIndex = scaleBufferIndices[subsetIndex]; - + const REALTYPE* cumulativeScaleFactors = gScaleBuffers[cumulativeScalingFactorIndex]; - + if (subsetIndex == 0) { indexMaxScale[k] = 0; maxScaleFactor[k] = cumulativeScaleFactors[k]; for (int j = 1; j < count; j++) { REALTYPE tmpScaleFactor; if (kFlags & BEAGLE_FLAG_SCALING_ALWAYS) - tmpScaleFactor = gScaleBuffers[bufferIndices[j] - kTipCount][k]; + tmpScaleFactor = gScaleBuffers[bufferIndices[j] - kTipCount][k]; else tmpScaleFactor = gScaleBuffers[scaleBufferIndices[j]][k]; - + if (tmpScaleFactor > maxScaleFactor[k]) { indexMaxScale[k] = j; maxScaleFactor[k] = tmpScaleFactor; } } } - + if (subsetIndex != indexMaxScale[k]) sum *= exp((REALTYPE)(cumulativeScaleFactors[k] - maxScaleFactor[k])); } - + if (subsetIndex == 0) { outLogLikelihoodsTmp[k] = sum; } else if (subsetIndex == count - 1) { REALTYPE tmpSum = outLogLikelihoodsTmp[k] + sum; - + outLogLikelihoodsTmp[k] = log(tmpSum); } else { outLogLikelihoodsTmp[k] += sum; } } } - + if (scaleBufferIndices[0] != BEAGLE_OP_NONE || (kFlags & BEAGLE_FLAG_SCALING_ALWAYS)) { for(int i=0; i::getName() { @@ -1511,7 +1503,7 @@ long long BeagleCPU4StateImplFactory::getFlags() { BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED | BEAGLE_FLAG_PREORDER_TRANSPOSE_MANUAL | BEAGLE_FLAG_PREORDER_TRANSPOSE_AUTO | BEAGLE_FLAG_FRAMEWORK_CPU; - + if (DOUBLE_PRECISION) flags |= BEAGLE_FLAG_PRECISION_DOUBLE; else diff --git a/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.h b/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.h index 1fa882a62..2dc5a2c9a 100644 --- a/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.h +++ b/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.h @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -48,11 +38,11 @@ namespace cpu { BEAGLE_CPU_TEMPLATE class BeagleCPU4StateSSEImpl : public BeagleCPU4StateImpl {}; - + BEAGLE_CPU_4_SSE_TEMPLATE class BeagleCPU4StateSSEImpl : public BeagleCPU4StateImpl { - + protected: using BeagleCPUImpl::kTipCount; using BeagleCPUImpl::gPartials; @@ -71,56 +61,56 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateImp using BeagleCPUImpl::outLogLikelihoodsTmp; using BeagleCPUImpl::gPatternWeights; using BeagleCPUImpl::gPatternPartitionsStartPatterns; - -public: + +public: virtual const char* getName(); virtual long long getFlags(); - + protected: - virtual int getPaddedPatternsModulus(); - + virtual int getPaddedPatternsModulus(); + private: - + virtual void calcStatesStates(float* destP, const int* states1, const float* matrices1, const int* states2, const float* matrices2); - + virtual void calcStatesPartials(float* destP, const int* states1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2); - + virtual void calcStatesPartialsFixedScaling(float* destP, const int* states1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2, const float* __restrict scaleFactors); - + virtual void calcPartialsPartials(float* __restrict destP, const float* __restrict partials1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2); - + virtual void calcPartialsPartialsFixedScaling(float* __restrict destP, const float* __restrict child0Partials, const float* __restrict child0TransMat, const float* __restrict child1Partials, const float* __restrict child1TransMat, const float* __restrict scaleFactors); - + virtual void calcPartialsPartialsAutoScaling(float* __restrict destP, const float* __restrict partials1, const float* __restrict matrices1, const float* __restrict partials2, const float* __restrict matrices2, int* activateScaling); - + virtual int calcEdgeLogLikelihoods(const int parentBufferIndex, const int childBufferIndex, const int probabilityIndex, @@ -140,11 +130,11 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateImp double* outSumLogLikelihoodByPartition); }; - + BEAGLE_CPU_4_SSE_TEMPLATE class BeagleCPU4StateSSEImpl : public BeagleCPU4StateImpl { - + protected: using BeagleCPUImpl::kTipCount; using BeagleCPUImpl::gPartials; @@ -175,27 +165,28 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateIm protected: virtual int getPaddedPatternsModulus(); - virtual void accumulateDerivatives(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); + virtual void accumulateDerivatives(double *outDerivatives, double *outSumDerivatives, + double *outSumSquaredDerivatives, int offset); private: template - void accumulateDerivativesDispatch1(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); + void + accumulateDerivativesDispatch1(double *outDerivatives, double *outSumDerivatives, double *outSumSquaredDerivatives, + int offset); template - void accumulateDerivativesDispatch2(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); + void accumulateDerivativesDispatch2(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset); template - void accumulateDerivativesImpl(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); - + void accumulateDerivativesImpl(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset); + virtual void calcStatesStates(double* destP, const int* states1, const double* matrices1, @@ -203,7 +194,7 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateIm const double* matrices2, int startPattern, int endPattern); - + virtual void calcStatesPartials(double* destP, const int* states1, const double* __restrict matrices1, @@ -211,7 +202,7 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateIm const double* __restrict matrices2, int startPattern, int endPattern); - + virtual void calcStatesPartialsFixedScaling(double* destP, const int* states1, const double* __restrict matrices1, @@ -220,7 +211,7 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateIm const double* __restrict scaleFactors, int startPattern, int endPattern); - + virtual void calcPartialsPartials(double* __restrict destP, const double* __restrict partials1, const double* __restrict matrices1, @@ -281,7 +272,7 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateIm double *outDerivatives, double *outSumDerivatives, double *outSumSquaredDerivatives); - + virtual void calcPartialsPartialsFixedScaling(double* __restrict destP, const double* __restrict child0Partials, const double* __restrict child0TransMat, @@ -290,14 +281,14 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateIm const double* __restrict scaleFactors, int startPattern, int endPattern); - + virtual void calcPartialsPartialsAutoScaling(double* __restrict destP, const double* __restrict partials1, const double* __restrict matrices1, const double* __restrict partials2, const double* __restrict matrices2, int* activateScaling); - + virtual int calcEdgeLogLikelihoods(const int parentBufferIndex, const int childBufferIndex, const int probabilityIndex, @@ -315,10 +306,10 @@ class BeagleCPU4StateSSEImpl : public BeagleCPU4StateIm const int* partitionIndices, int partitionCount, double* outSumLogLikelihoodByPartition); - + }; - - + + BEAGLE_CPU_FACTORY_TEMPLATE class BeagleCPU4StateSSEImplFactory : public BeagleImplFactory { public: diff --git a/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.hpp b/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.hpp index 69ce5060a..34d4a86f7 100644 --- a/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.hpp +++ b/libhmsbeagle/CPU/BeagleCPU4StateSSEImpl.hpp @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author David Swofford @@ -104,7 +94,7 @@ #define SSE_PREFETCH_PRE_MATRICES(src_m1, src_m2, dest_vu_m1, dest_vu_m2) \ const double *m1 = (src_m1); \ const double *m2 = (src_m2); \ - for (int i = 0; i < OFFSET; i++, m1+=OFFSET, m2++) { \ + for (int i = 0; i < 4; i++, m1+=OFFSET, m2++) { \ dest_vu_m1[i][0].x[0] = m1[0]; \ dest_vu_m1[i][0].x[1] = m1[1]; \ dest_vu_m2[i][0].x[0] = m2[0*OFFSET]; \ @@ -113,6 +103,12 @@ dest_vu_m1[i][1].x[1] = m1[3]; \ dest_vu_m2[i][1].x[0] = m2[2*OFFSET]; \ dest_vu_m2[i][1].x[1] = m2[3*OFFSET]; \ + } \ + for (int i = 4; i < OFFSET; i++, m2++) { \ + dest_vu_m2[i][0].x[0] = m2[0*OFFSET]; \ + dest_vu_m2[i][0].x[1] = m2[1*OFFSET]; \ + dest_vu_m2[i][1].x[0] = m2[2*OFFSET]; \ + dest_vu_m2[i][1].x[1] = m2[3*OFFSET]; \ } #define SSE_PREFETCH_MATRIX(src_m1, dest_vu_m1) \ @@ -643,10 +639,10 @@ void BeagleCPU4StateSSEImpl::calcCrossProductsStates(co } BEAGLE_CPU_4_SSE_TEMPLATE template -void BeagleCPU4StateSSEImpl::accumulateDerivativesImpl( - double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void BeagleCPU4StateSSEImpl::accumulateDerivativesImpl(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { V_Real vSum = VEC_SETZERO(); V_Real vSumSquared = VEC_SETZERO(); @@ -707,46 +703,47 @@ void BeagleCPU4StateSSEImpl::accumulateDerivativesImpl( } BEAGLE_CPU_4_SSE_TEMPLATE template -void BeagleCPU4StateSSEImpl::accumulateDerivativesDispatch2( - double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void BeagleCPU4StateSSEImpl::accumulateDerivativesDispatch2(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { if (outSumSquaredDerivatives == NULL) { accumulateDerivativesImpl( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } else { accumulateDerivativesImpl( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } } BEAGLE_CPU_4_SSE_TEMPLATE template -void BeagleCPU4StateSSEImpl::accumulateDerivativesDispatch1( - double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void BeagleCPU4StateSSEImpl::accumulateDerivativesDispatch1(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { if (outSumDerivatives == NULL) { accumulateDerivativesDispatch2( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } else { accumulateDerivativesDispatch2( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } } BEAGLE_CPU_4_SSE_TEMPLATE -void BeagleCPU4StateSSEImpl::accumulateDerivatives(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void BeagleCPU4StateSSEImpl::accumulateDerivatives(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { if (outDerivatives == NULL) { accumulateDerivativesDispatch1( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } else { accumulateDerivativesDispatch1( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } } diff --git a/libhmsbeagle/CPU/BeagleCPUAVXImpl.h b/libhmsbeagle/CPU/BeagleCPUAVXImpl.h index 58fc92a01..cc3259857 100644 --- a/libhmsbeagle/CPU/BeagleCPUAVXImpl.h +++ b/libhmsbeagle/CPU/BeagleCPUAVXImpl.h @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -103,7 +93,7 @@ class BeagleCPUAVXImpl : public BeagleCPUImpl : public BeagleCPUImpl : public BeagleCPUImpl { @@ -177,7 +167,7 @@ class BeagleCPUAVXImpl : public BeagleCPUImpl : public BeagleCPUImpl. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -344,7 +334,7 @@ void BeagleCPUAVXImpl::calcPartialsPartialsFixedScaling( // } } - + BEAGLE_CPU_AVX_TEMPLATE void BeagleCPUAVXImpl::calcPartialsPartialsAutoScaling(double* destP, const double* partials_q, @@ -375,7 +365,7 @@ void BeagleCPUAVXImpl::calcPartialsPartialsAutoScaling(do // matrices_r, // activateScaling); //} - + BEAGLE_CPU_AVX_TEMPLATE int BeagleCPUAVXImpl::calcEdgeLogLikelihoods(const int parIndex, const int childIndex, @@ -511,7 +501,7 @@ return BeagleCPUImpl::calcEdgeLogLikelihoods( // for (int i = 0; i < kPatternCount; i++) { // *outSumLogLikelihood += outLogLikelihoodsTmp[i] * gPatternWeights[i]; // } -// +// // if (!(*outSumLogLikelihood - *outSumLogLikelihood == 0.0)) // returnCode = BEAGLE_ERROR_FLOATING_POINT; // @@ -522,7 +512,7 @@ BEAGLE_CPU_AVX_TEMPLATE int BeagleCPUAVXImpl::getPaddedPatternsModulus() { return 1; // We currently do not vectorize across patterns } - + BEAGLE_CPU_AVX_TEMPLATE const char* BeagleCPUAVXImpl::getName() { return getBeagleCPUAVXName(); @@ -532,7 +522,7 @@ BEAGLE_CPU_AVX_TEMPLATE const char* BeagleCPUAVXImpl::getName() { return getBeagleCPUAVXName(); } - + BEAGLE_CPU_AVX_TEMPLATE long BeagleCPUAVXImpl::getFlags() { return BEAGLE_FLAG_COMPUTATION_SYNCH | @@ -573,12 +563,12 @@ BeagleImpl* BeagleCPUAVXImplFactory::createImpl(int if (!CPUSupportsAVX()) return NULL; - + if (stateCount & 1) { // is odd BeagleCPUAVXImpl* impl = new BeagleCPUAVXImpl(); - - + + try { if (impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount, patternCount, eigenBufferCount, matrixBufferCount, @@ -591,8 +581,8 @@ BeagleImpl* BeagleCPUAVXImplFactory::createImpl(int delete impl; throw; } - - delete impl; + + delete impl; } else { BeagleCPUAVXImpl* impl = new BeagleCPUAVXImpl(); @@ -613,7 +603,7 @@ BeagleImpl* BeagleCPUAVXImplFactory::createImpl(int delete impl; } - + return NULL; } @@ -634,7 +624,7 @@ long BeagleCPUAVXImplFactory::getFlags() { BEAGLE_FLAG_EIGEN_COMPLEX | BEAGLE_FLAG_EIGEN_REAL | BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED | BEAGLE_FLAG_PREORDER_TRANSPOSE_MANUAL | BEAGLE_FLAG_PREORDER_TRANSPOSE_AUTO | - BEAGLE_FLAG_FRAMEWORK_CPU; + BEAGLE_FLAG_FRAMEWORK_CPU; } template <> @@ -649,7 +639,7 @@ long BeagleCPUAVXImplFactory::getFlags() { BEAGLE_FLAG_EIGEN_COMPLEX | BEAGLE_FLAG_EIGEN_REAL | BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED | BEAGLE_FLAG_PREORDER_TRANSPOSE_MANUAL | BEAGLE_FLAG_PREORDER_TRANSPOSE_AUTO | - BEAGLE_FLAG_FRAMEWORK_CPU; + BEAGLE_FLAG_FRAMEWORK_CPU; } // Code to save: diff --git a/libhmsbeagle/CPU/BeagleCPUActionImpl.h b/libhmsbeagle/CPU/BeagleCPUActionImpl.h index eca3e00c9..2958f2c0f 100644 --- a/libhmsbeagle/CPU/BeagleCPUActionImpl.h +++ b/libhmsbeagle/CPU/BeagleCPUActionImpl.h @@ -35,6 +35,7 @@ #include #include #include +#include #define T_PAD_DEFAULT 1 // Pad transition matrix rows with an extra 1.0 for ambiguous characters #define P_PAD_DEFAULT 0 // No partials padding necessary for non-SSE implementations @@ -46,7 +47,7 @@ typedef Eigen::Matrix MatrixXd; typedef Eigen::Map MapType; -typedef Eigen::SparseMatrix SpMatrix; +typedef Eigen::SparseMatrix SpMatrix; typedef Eigen::Triplet Triplet; @@ -63,9 +64,10 @@ namespace beagle { protected: using BeagleCPUImpl::kTipCount; -// using BeagleCPUImpl::integrationTmp; -// using BeagleCPUImpl::firstDerivTmp; -// using BeagleCPUImpl::secondDerivTmp; + using BeagleCPUImpl::kNumThreads; + using BeagleCPUImpl::integrationTmp; + using BeagleCPUImpl::firstDerivTmp; + using BeagleCPUImpl::secondDerivTmp; using BeagleCPUImpl::kPatternCount; using BeagleCPUImpl::kPaddedPatternCount; using BeagleCPUImpl::kExtraPatterns; @@ -78,9 +80,16 @@ namespace beagle { using BeagleCPUImpl::kEigenDecompCount; using BeagleCPUImpl::gPartials; using BeagleCPUImpl::gCategoryRates; + using BeagleCPUImpl::gCategoryWeights; using BeagleCPUImpl::gScaleBuffers; using BeagleCPUImpl::kFlags; -// SpMatrix** gScaledQs; + using BeagleCPUImpl::grandNumeratorDerivTmp; + using BeagleCPUImpl::grandDenominatorDerivTmp; + using BeagleCPUImpl::accumulateDerivatives; + using BeagleCPUImpl::resetDerivativeTemporaries; +// using BeagleCPUImpl::gTransitionMatrices; + + // SpMatrix** gScaledQs; int kPartialsCacheOffset; // using BeagleCPUImpl::gStateFrequencies; // using BeagleCPUImpl::gTipStates; @@ -94,7 +103,8 @@ namespace beagle { std::vector gB1Norms; std::vector gEigenMaps; std::vector gEdgeMultipliers; - std::vector> ds; + mutable std::vector> ds; + mutable std::shared_mutex ds_mutex; SpMatrix identity; MapType* gMappedIntegrationTmp; // MapType* gMappedLeftPartialTmp; @@ -178,6 +188,18 @@ namespace beagle { int operationCount, int cumulativeScalingIndex); + virtual int calcEdgeLogDerivatives(const int *postBufferIndices, + const int *preBufferIndices, + const int *firstDerivativeIndices, + const int *secondDerivativeIndices, + const int *categoryWeightsIndices, + const int *categoryRatesIndices, + const int *cumulativeScaleIndices, + int count, + double *siteLogLikelihoods, + double *outLogFirstDerivatives, + double *outLogDiagonalSecondDerivatives); + inline MapType partialsMap(int index, int category, int startPattern, int endPattern); inline MapType partialsMap(int index, int category); @@ -189,11 +211,44 @@ namespace beagle { // virtual int getPaddedPatternsModulus(); private: + // Divide the patterns [startPattern, endPattern) of a partials buffer by existing scale factors. + void applyFixedScaling(int destinationPartialIndex, const double* scalingFactors, int startPattern, int endPattern); + + void calcEdgeLogDerivativesPartials(const int postOrderPartialIndex, + const int preOrderPartialIndex, + const int firstDerivativeIndex, + const int secondDerivativeIndex, + const double *categoryRates, + const double *categoryWeights, + const int scalingFactorsIndex, + double *siteLogLikelihoods, + double *outLogFirstDerivatives, + double *outLogDiagonalSecondDerivatives, + int offset); + + int calcEdgeLogDerivativesByAutoPartitionAsync(const int *operations, + int count, + double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives); + virtual int setEigenDecomposition(int eigenIndex, const double *inEigenVectors, const double *inInverseEigenVectors, const double *inEigenValues); + virtual int setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros); + + virtual int setSparseDifferentialMatrix(int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros); + virtual int updateTransitionMatrices(int eigenIndex, const int* probabilityIndices, const int* firstDerivativeIndices, @@ -223,12 +278,15 @@ namespace beagle { int startPattern, int endPattern); + // Return (m,s) std::tuple getStatistics2(double t, int nCol, double edgeMultiplier, int eigenIndex) const; double getDValue(int p, int eigenIndex) const; + bool hasDValue(int p, int eigenIndex) const; + double getPMax() const; }; diff --git a/libhmsbeagle/CPU/BeagleCPUActionImpl.hpp b/libhmsbeagle/CPU/BeagleCPUActionImpl.hpp index 4b65886c0..80eb25d40 100644 --- a/libhmsbeagle/CPU/BeagleCPUActionImpl.hpp +++ b/libhmsbeagle/CPU/BeagleCPUActionImpl.hpp @@ -38,6 +38,7 @@ #include #include #include +#include #include "libhmsbeagle/beagle.h" #include "libhmsbeagle/CPU/BeagleCPUImpl.h" @@ -62,6 +63,10 @@ tuple ArgNormP1(const T& matrix) template double normPInf(const T& matrix) { +//#ifdef BEAGLE_DEBUG_FLOW +// std::cerr<<"matrix =\n" << matrix<().maxCoeff() << std::endl; +//#endif return matrix.template lpNorm(); } @@ -80,6 +85,29 @@ double random_plus_minus_1_func(double x) return -1; } +std::vector true_norm_merged(const SpMatrix& A, int pMax) +{ + assert(pMax >= 0); + + std::vector norms(pMax+1, 0); + norms[0] = 1.0; + + // A is (n,n); + assert(A.rows() == A.cols()); + int n = A.cols(); + + MatrixXd Y = MatrixXd::Identity(n,n); + + for(int p=1;p<=pMax;p++) + { + Y = A*Y; + auto [est, j] = ArgNormP1(Y); + norms[p] = est; + } + + return norms; +} + // Algorithm 2.4 from Higham and Tisseur (2000), A BLOCK ALGORITHM FOR MATRIX 1-NORM ESTIMATION, // WITH AN APPLICATION TO 1-NORM PSEUDOSPECTRA. // See OneNormEst in https://eprints.maths.manchester.ac.uk/2195/1/thesis-main.pdf @@ -198,9 +226,10 @@ double normest1(const SpMatrix& A, int p, int t=2, int itmax=5) } // (3) of Algorithm 2.4 - Z = A.transpose() * S; // (t,n) * (n,t) -> (t,t) + Z = A.transpose() * S; // (n,n) * (n,t) -> (n,t) - h = Z.cwiseAbs().rowwise().maxCoeff(); + // Maximize across each the t entries in each row of Z. + h = Z.cwiseAbs().rowwise().maxCoeff(); // (n,t) -> (n,1) // (4) of Algorithm 2.4 if (k >= 2 and h.maxCoeff() == h[ind_best]) @@ -263,6 +292,142 @@ double normest1(const SpMatrix& A, int p, int t=2, int itmax=5) return est_old; } +std::vector normest1_all(const SpMatrix& A, int pMax, int t=2, int itmax=5) +{ + std::vector norms(pMax+1, 1.0); + + for(int p=0; p<=pMax; p++) + { + norms[p] = normest1(A, p, t, itmax); + } + + return norms; +} + +std::vector normest1_merged(const SpMatrix& A, int pMax, int t=2, int itmax=2) +{ + // nstd::cerr<<"--BEGIN--\n"; + // auto sep_norms = normest1_all(A,pMax,t,itmax); + + assert(pMax >= 0); + assert(t != 0); // negative means t = n + assert(itmax >= 1); + + // A is (n,n); + assert(A.rows() == A.cols()); + int n = A.cols(); + + // Handle t too large + t = std::min(n,t); + + // Interpret negative t as t == n + if (t < 0) t = n; + + std::vector norms(pMax+1, 0); + norms[0] = 1.0; + + MatrixXd S(n,t); + MatrixXd Z(n,t); + Eigen::VectorXd h(n); + + MatrixXd X(n,t); + MatrixXd Y(n,t); + std::vector ind_best(pMax+1, -1); + std::vector est_old(pMax+1,0); + vector new_indices(pMax+1); + + // (0) Choose starting matrix X that is (n,t) with columns of unit 1-norm. + // We choose the first column to be all 1s. + X.col(0).setOnes(); + // The other columns have randomly chosen {-1,+1} entries. + X = X.unaryExpr( &random_plus_minus_1_func ); + // Divide by n so that the norm of each column is 1. + X /= n; + + std::vector all_indices; + all_indices.resize(n); + std::vector all_ind_hist(n,false); + + for(int k=1; k<=itmax and X.cols() > 0; k++) + { + for(int p=1; p<=pMax; p++) + { + // std::cerr<<"iter "< est_old[p] or k == 2) + { + // Note that j is in [0,t-1], but indices[j] is in [0,n-1]. + ind_best[p] = all_indices[j]; + // w = Y[p].col(ind_best); + } + // std::cerr<<" est = "<= est_old[p]); + + // S = sign(Y[p]), 0.0 -> 1.0 + S = Y.unaryExpr([](const double& x) {return (x>=0) ? 1.0 : -1.0 ;}); + + // (3) of Algorithm 2.4 + Z = A.transpose() * S; // (n,n) * (n,t) -> (n,t) + + // Maximize across each the t entries in each row of Z. + h = Z.cwiseAbs().rowwise().maxCoeff(); // (n,t) -> (n,1) + + // reorder idx so that the highest values of h[indices[i]] come first. + std::optional i; + for(int l=0;l h[i.value()])) + i = l; + + new_indices[p] = i.value(); + } + + // Combine indices from different values of p + all_indices.clear(); + for(int p=1;p<=pMax;p++) + { + int i = new_indices[p]; + if (not all_ind_hist[i]) + { + all_indices.push_back(i); + all_ind_hist[i] = true; + } + } + + // std::cerr<<"k = "< 0) + { + X = MatrixXd::Zero(n, tmax); + for(int j=0; j < tmax; j++) + X(all_indices[j], j) = 1; // X(:,j) = e(indices[j]) + } + } + +// for(int p=1;p(){ return "CPU-Action-Single"; }; - BEAGLE_CPU_ACTION_TEMPLATE + BEAGLE_CPU_ACTION_TEMPLATE int BeagleCPUActionImpl::upPartials(bool byPartition, - const int *operations, - int operationCount, - int cumulativeScaleIndex) { - double* cumulativeScaleBuffer = NULL; + const int *operations, + int operationCount, + int cumulativeScaleIndex) { + double *cumulativeScaleBuffer = NULL; if (cumulativeScaleIndex != BEAGLE_OP_NONE) cumulativeScaleBuffer = gScaleBuffers[cumulativeScaleIndex]; for (int op = 0; op < operationCount; op++) { int numOps = BEAGLE_OP_COUNT; - if (byPartition) - numOps = BEAGLE_PARTITION_OP_COUNT; + if (byPartition) + numOps = BEAGLE_PARTITION_OP_COUNT; - if (DEBUGGING_OUTPUT) { - fprintf(stderr, "op[%d] = ", op); - for (int j = 0; j < numOps; j++) { - std::cerr << operations[op*numOps+j] << " "; - } - fprintf(stderr, "\n"); - } + if (DEBUGGING_OUTPUT) { + fprintf(stderr, "op[%d] = ", op); + for (int j = 0; j < numOps; j++) { + std::cerr << operations[op * numOps + j] << " "; + } + fprintf(stderr, "\n"); + } - const int destinationPartialIndex = operations[op * numOps]; + const int destinationPartialIndex = operations[op * numOps]; const int writeScalingIndex = operations[op * numOps + 1]; const int readScalingIndex = operations[op * numOps + 2]; const int firstChildPartialIndex = operations[op * numOps + 3]; const int firstChildSubstitutionMatrixIndex = operations[op * numOps + 4]; const int secondChildPartialIndex = operations[op * numOps + 5]; const int secondChildSubstitutionMatrixIndex = operations[op * numOps + 6]; - int currentPartition = 0; - if (byPartition) { - currentPartition = operations[op * numOps + 7]; - cumulativeScaleIndex = operations[op * numOps + 8]; - if (cumulativeScaleIndex != BEAGLE_OP_NONE) - cumulativeScaleBuffer = gScaleBuffers[cumulativeScaleIndex]; - else - cumulativeScaleBuffer = NULL; - } + int currentPartition = 0; + if (byPartition) { + currentPartition = operations[op * numOps + 7]; + cumulativeScaleIndex = operations[op * numOps + 8]; + if (cumulativeScaleIndex != BEAGLE_OP_NONE) + cumulativeScaleBuffer = gScaleBuffers[cumulativeScaleIndex]; + else + cumulativeScaleBuffer = NULL; + } - int startPattern = 0; - int endPattern = kPatternCount; - if (byPartition) { - startPattern = this->gPatternPartitionsStartPatterns[currentPartition]; - endPattern = this->gPatternPartitionsStartPatterns[currentPartition + 1]; + int startPattern = 0; + int endPattern = kPatternCount; + if (byPartition) { + startPattern = this->gPatternPartitionsStartPatterns[currentPartition]; + endPattern = this->gPatternPartitionsStartPatterns[currentPartition + 1]; - assert(startPattern >= 0 and startPattern <= kPatternCount); - assert(endPattern >= 0 and endPattern <= kPatternCount); - assert(startPattern <= endPattern); - } + assert(startPattern >= 0 and startPattern <= kPatternCount); + assert(endPattern >= 0 and endPattern <= kPatternCount); + assert(startPattern <= endPattern); + } int rescale = BEAGLE_OP_NONE; - double* scalingFactors = NULL; + double *scalingFactors = NULL; if (writeScalingIndex >= 0) { rescale = 1; scalingFactors = gScaleBuffers[writeScalingIndex]; @@ -435,25 +600,29 @@ namespace beagle { #ifdef BEAGLE_DEBUG_FLOW - std::cerr<<"Updating partials for index: "<rescalePartialsByPartition(destPartials,scalingFactors,cumulativeScaleBuffer,0, currentPartition); - } else { - this->rescalePartials(destPartials,scalingFactors,cumulativeScaleBuffer,0); - } + double *destPartials = gPartials[destinationPartialIndex]; + if (byPartition) { + this->rescalePartialsByPartition(destPartials, scalingFactors, cumulativeScaleBuffer, 0, + currentPartition); + } else { + this->rescalePartials(destPartials, scalingFactors, cumulativeScaleBuffer, 0); + } + } else if (scalingFactors != NULL) { + // Reuse the existing scale factors (e.g. dynamic rescaling between recomputations). + applyFixedScaling(destinationPartialIndex, scalingFactors, startPattern, endPattern); } } @@ -462,15 +631,19 @@ namespace beagle { BEAGLE_CPU_ACTION_TEMPLATE int BeagleCPUActionImpl::upPrePartials(bool byPartition, - const int *operations, - int operationCount, - int cumulativeScaleIndex) { - double* cumulativeScaleBuffer = NULL; + const int *operations, + int operationCount, + int cumulativeScaleIndex) { + double *cumulativeScaleBuffer = NULL; if (cumulativeScaleIndex != BEAGLE_OP_NONE) cumulativeScaleBuffer = gScaleBuffers[cumulativeScaleIndex]; + int numOps = BEAGLE_OP_COUNT; + if (byPartition) + numOps = BEAGLE_PARTITION_OP_COUNT; + + for (int op = 0; op < operationCount; op++) { - int numOps = BEAGLE_OP_COUNT; // create a list of partial likelihood update operations // the order is [dest, destScaling, source1, matrix1, source2, matrix2] @@ -486,31 +659,31 @@ namespace beagle { const int substitutionMatrixIndex = operations[op * numOps + 4]; const int siblingIndex = operations[op * numOps + 5]; const int siblingSubstitutionMatrixIndex = operations[op * numOps + 6]; - int currentPartition = 0; - if (byPartition) { - currentPartition = operations[op * numOps + 7]; - cumulativeScaleIndex = operations[op * numOps + 8]; + int currentPartition = 0; + if (byPartition) { + currentPartition = operations[op * numOps + 7]; + cumulativeScaleIndex = operations[op * numOps + 8]; // if (cumulativeScaleIndex != BEAGLE_OP_NONE) // cumulativeScaleBuffer = gScaleBuffers[cumulativeScaleIndex]; // else // cumulativeScaleBuffer = NULL; - } + } - double *destPartials = gPartials[destinationPartialIndex]; + double *destPartials = gPartials[destinationPartialIndex]; - int startPattern = 0; - int endPattern = kPatternCount; - if (byPartition) { - startPattern = this->gPatternPartitionsStartPatterns[currentPartition]; - endPattern = this->gPatternPartitionsStartPatterns[currentPartition + 1]; + int startPattern = 0; + int endPattern = kPatternCount; + if (byPartition) { + startPattern = this->gPatternPartitionsStartPatterns[currentPartition]; + endPattern = this->gPatternPartitionsStartPatterns[currentPartition + 1]; - assert(startPattern >= 0 and startPattern <= kPatternCount); - assert(endPattern >= 0 and endPattern <= kPatternCount); - assert(startPattern <= endPattern); - } + assert(startPattern >= 0 and startPattern <= kPatternCount); + assert(endPattern >= 0 and endPattern <= kPatternCount); + assert(startPattern <= endPattern); + } int rescale = BEAGLE_OP_NONE; - double* scalingFactors = NULL; + double *scalingFactors = NULL; if (writeScalingIndex >= 0) { rescale = 1; scalingFactors = gScaleBuffers[writeScalingIndex]; @@ -523,41 +696,262 @@ namespace beagle { #ifdef BEAGLE_DEBUG_FLOW - std::cerr<<"Updating preorder partials for index: "<rescalePartialsByPartition(destPartials,scalingFactors,cumulativeScaleBuffer,0, currentPartition); - } else { - this->rescalePartials(destPartials,scalingFactors,cumulativeScaleBuffer,0); - } + double *destPartials = gPartials[destinationPartialIndex]; + if (byPartition) { + this->rescalePartialsByPartition(destPartials, scalingFactors, cumulativeScaleBuffer, 0, + currentPartition); + } else { + this->rescalePartials(destPartials, scalingFactors, cumulativeScaleBuffer, 0); + } + } else if (scalingFactors != NULL) { + // Reuse the existing scale factors (e.g. dynamic rescaling between recomputations). + applyFixedScaling(destinationPartialIndex, scalingFactors, startPattern, endPattern); } - if (DEBUGGING_OUTPUT) { - if (scalingFactors != NULL && rescale == 0) { - for (int i = 0; i < kPatternCount; i++) - fprintf(stderr, "old scaleFactor[%d] = %.5f\n", i, scalingFactors[i]); - } - fprintf(stderr, "Result partials:\n"); - for (int i = 0; i < this->kPartialsSize; i++) - fprintf(stderr, "destP[%d] = %.5f\n", i, destPartials[i]); - } + if (DEBUGGING_OUTPUT) { + if (scalingFactors != NULL && rescale == 0) { + for (int i = 0; i < kPatternCount; i++) + fprintf(stderr, "old scaleFactor[%d] = %.5f\n", i, scalingFactors[i]); + } + fprintf(stderr, "Result partials:\n"); + for (int i = 0; i < this->kPartialsSize; i++) + fprintf(stderr, "destP[%d] = %.5f\n", i, destPartials[i]); + } } return BEAGLE_SUCCESS; } + BEAGLE_CPU_ACTION_TEMPLATE + void BeagleCPUActionImpl::applyFixedScaling(int destinationPartialIndex, + const double* scalingFactors, + int startPattern, + int endPattern) { + // As BeagleCPUImpl's *FixedScaling functions: divide each pattern by its stored scale factor. + const bool scalersLog = (this->kFlags & BEAGLE_FLAG_SCALERS_LOG) != 0; + for (int category = 0; category < kCategoryCount; category++) { + auto destP = partialsMap(destinationPartialIndex, category, startPattern, endPattern); + for (int j = 0; j < endPattern - startPattern; j++) { + const double factor = scalingFactors[startPattern + j]; + destP.col(j) *= 1.0 / (scalersLog ? exp(factor) : factor); + } + } + } + + BEAGLE_CPU_ACTION_TEMPLATE + void BeagleCPUActionImpl::calcEdgeLogDerivativesPartials(const int postOrderPartialIndex, + const int preOrderPartialIndex, + const int firstDerivativeIndex, + const int secondDerivativeIndex, + const double *categoryRates, + const double *categoryWeights, + const int scalingFactorsIndex, + double *outDerivativesForNode, + double *outSumDerivativesForNode, + double *outSumSquaredDerivativesForNode, + int offset) + { + + auto destNumeratorDrivTmp = MapType(grandNumeratorDerivTmp + offset * kPatternCount , 1, kPatternCount); + auto destDenominatorDrivTmp = MapType(grandDenominatorDerivTmp + offset * kPatternCount, 1, kPatternCount); + auto destFirstDerivTmp = MapType(firstDerivTmp + offset * kPatternCount * kStateCount, kStateCount, kPatternCount); + auto destSecondDerivTmp = MapType(secondDerivTmp + offset * kPatternCount * kStateCount, kStateCount, kPatternCount); + SpMatrix differentialMatrix = gInstantaneousMatrices[firstDerivativeIndex]; + +// std::cerr<<"dQ = " << differentialMatrix << ", offset = "<< offset << std::endl; +// std::cerr<< "offset = "<< offset << std::endl; + + + for (int category = 0; category < kCategoryCount; category++) { + const double weight = categoryWeights[category]; + +// std::cerr<<"Category = " << category << " ; multiplier = " << weight << " * " << categoryRates[category] << std::endl; + + MapType postOrderPartial = partialsMap(postOrderPartialIndex, category, 0, kPatternCount); + MapType preOrderPartial = partialsMap(preOrderPartialIndex, category, 0, kPatternCount); + + const double categoryMultiplier = weight * categoryRates[category]; + +// std::cerr<< " = " << categoryMultiplier << std::endl; + + destFirstDerivTmp = differentialMatrix * postOrderPartial; + +// std::cerr<<"Post-order partial = " << std::endl << postOrderPartial << std::endl << "Pre-order partial = " << std::endl << preOrderPartial << std::endl; +// std::cerr<<"Differential matrix = " << differentialMatrix << std::endl; +// std::cerr<<"Qp = " << std::endl << destFirstDerivTmp << std::endl; + + destFirstDerivTmp = destFirstDerivTmp.cwiseProduct(preOrderPartial); + +// std::cerr<<"q'Qp = " << std::endl << destFirstDerivTmp << std::endl; + + destSecondDerivTmp = postOrderPartial.cwiseProduct(preOrderPartial); + +// std::cerr<<"q'p = " << std::endl << destSecondDerivTmp << std::endl; + + destNumeratorDrivTmp += destFirstDerivTmp.colwise().sum() * categoryMultiplier; + +// std::cerr<<"colSum(q'Qp)rw = " << std::endl << destNumeratorDrivTmp << std::endl; + destDenominatorDrivTmp += destSecondDerivTmp.colwise().sum() * weight; +// std::cerr<<"colSum(q'p)rw = " << std::endl << destDenominatorDrivTmp << std::endl; + } +// std::cerr<< "reduction finished"<< std::endl; + } + + BEAGLE_CPU_ACTION_TEMPLATE + int BeagleCPUActionImpl::calcEdgeLogDerivativesByAutoPartitionAsync(const int *operations, + int count, + double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives) { + + int returnCode = BEAGLE_SUCCESS; + + int numOps = BEAGLE_OP_COUNT; + int numOpsP = BEAGLE_PARTITION_OP_COUNT; + + const int secondDerivativeIndex = BEAGLE_OP_NONE; + const double *categoryRates = gCategoryRates[0]; // TODO Generalize + const double *categoryWeights = gCategoryWeights[operations[3]]; // TODO Generalize + + + + for (int nodeNum = 0; nodeNum < count; nodeNum++) { + + const int preOrderPartialIndex = operations[nodeNum * numOpsP + 1]; + const int postOrderPartialindex = operations[nodeNum * numOpsP]; + + + const int firstDerivativeIndex = operations[nodeNum * numOpsP + 2]; + const int scalingFactorsIndex = -1; // cumulativeScaleIndices[nodeNum]; + + const int patternOffset = operations[nodeNum * numOpsP + 4] * kPatternCount; + const int threadOffset = operations[nodeNum * numOpsP + 5] * kPatternCount; + +#ifdef BEAGLE_DEBUG_FLOW + std::cerr<<"Job = " << operations[nodeNum * numOpsP + 4] <::calcEdgeLogDerivatives(const int *postBufferIndices, + const int *preBufferIndices, + const int *firstDerivativeIndices, + const int *secondDerivativeIndices, + const int *categoryWeightsIndices, + const int *categoryRatesIndices, + const int *cumulativeScaleIndices, + int count, + double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives) { + + int returnCode = BEAGLE_SUCCESS; + + const int secondDerivativeIndex = BEAGLE_OP_NONE; + const double *categoryRates = gCategoryRates[0]; // TODO Generalize + const double *categoryWeights = gCategoryWeights[categoryWeightsIndices[0]]; // TODO Generalize + + for (int nodeNum = 0; nodeNum < count; nodeNum++) { + + const int preOrderPartialIndex = preBufferIndices[nodeNum]; + const int postOrderPartialindex = postBufferIndices[nodeNum]; + + + const int firstDerivativeIndex = firstDerivativeIndices[nodeNum]; + const int scalingFactorsIndex = -1; // cumulativeScaleIndices[nodeNum]; + + const int patternOffset = nodeNum * kPatternCount; + double* outDerivativesForNode = (outDerivatives == NULL) ? + NULL : outDerivatives + patternOffset; + double* outSumDerivativesForNode = (outSumDerivatives == NULL) ? + NULL : outSumDerivatives + nodeNum; + double* outSumSquaredDerivativesForNode = (outSumSquaredDerivatives == NULL) ? + NULL : outSumSquaredDerivatives + nodeNum; + + resetDerivativeTemporaries(0); + +// std::cerr<<"Node = " << nodeNum << std::endl; + + calcEdgeLogDerivativesPartials(postOrderPartialindex, preOrderPartialIndex, firstDerivativeIndex, + secondDerivativeIndex, categoryRates, categoryWeights, + scalingFactorsIndex, + outDerivativesForNode, + outSumDerivativesForNode, + outSumSquaredDerivativesForNode, + 0); + + accumulateDerivatives(outDerivativesForNode, + outSumDerivativesForNode, + outSumSquaredDerivativesForNode, 0); + + } + + return returnCode; + + } + BEAGLE_CPU_ACTION_TEMPLATE int BeagleCPUActionImpl::setTipStates(int tipIndex, const int* inStates) { @@ -598,16 +992,6 @@ namespace beagle { ds[eigenIndex].clear(); - int pMax = getPMax(); - for(int p=0;p <= pMax+1; p++) - { - int t = 5; - double approx_norm = normest1( gBs[eigenIndex], p, t); - - // equation 3.7 in Al-Mohy and Higham - ds[eigenIndex].push_back( pow( approx_norm, 1.0/double(p) ) ); - } - // gSimpleActions[eigenIndex]->setInstantaneousMatrix(tripletList); // gSimpleActions[eigenIndex]->fireMatrixChanged(); #ifdef BEAGLE_DEBUG_FLOW @@ -620,6 +1004,54 @@ namespace beagle { return BEAGLE_SUCCESS; } + BEAGLE_CPU_ACTION_TEMPLATE + int BeagleCPUActionImpl::setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros) { + + + std::vector tripletList; + for (int i = 0; i < numNonZeros; i++) { + tripletList.push_back(Triplet(rowIndices[i], colIndices[i], values[i])); + } + gInstantaneousMatrices[matrixIndex].setFromTriplets(tripletList.begin(), tripletList.end()); + + double mu_B = 0.0; + for (int i = 0; i < kStateCount; i++) { + mu_B += gInstantaneousMatrices[matrixIndex].coeff(i, i); + } + mu_B /= (double) kStateCount; + gMuBs[matrixIndex] = mu_B; + gBs[matrixIndex] = gInstantaneousMatrices[matrixIndex] - mu_B * identity; + gB1Norms[matrixIndex] = normP1(gBs[matrixIndex]); + + ds[matrixIndex].clear(); + + return BEAGLE_SUCCESS; + } + + BEAGLE_CPU_ACTION_TEMPLATE + int BeagleCPUActionImpl::setSparseDifferentialMatrix(int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros) { + + + std::vector tripletList; + for (int i = 0; i < numNonZeros; i++) { + tripletList.push_back(Triplet(rowIndices[i], colIndices[i], values[i])); + } + + gInstantaneousMatrices[matrixIndex].setFromTriplets(tripletList.begin(), tripletList.end()); + +// std::cout<<"Checking matrix: "<::updateTransitionMatrices(int eigenIndex, const int* probabilityIndices, @@ -648,7 +1080,7 @@ namespace beagle { << " edge length multiplier: " << edgeLengths[i] << " edgeMultiplier: "<< gEdgeMultipliers[nodeIndex * kCategoryCount + category] << " nodeIndex: "<< nodeIndex - << std::endl << gScaledQs[nodeIndex][category]<::simpleAction2(MapType& destP, MapType& partials, int edgeIndex, + BeagleCPUActionImpl::simpleAction2(MapType &destP, MapType &partials, int edgeIndex, int category, bool transpose) const { #ifdef BEAGLE_DEBUG_FLOW - std::cerr<<"New impl 2\nRate category "<(bestS, INT_MAX), 1.0); assert( bestS >= 1 ); assert( bestS <= INT_MAX ); @@ -922,11 +1403,37 @@ namespace beagle { BEAGLE_CPU_ACTION_TEMPLATE double BeagleCPUActionImpl::getDValue(int p, int eigenIndex) const { - assert(p >= 0 and p < ds[eigenIndex].size()); + // 1. Try to read with a SHARED lock (multiple readers allowed) + { + std::shared_lock read_lock(ds_mutex); + if (p < ds[eigenIndex].size()) { + return ds[eigenIndex][p]; + } + } + + // 2. If not found, upgrade to an EXCLUSIVE lock (only one writer) + std::unique_lock write_lock(ds_mutex); + + // Double-check: another thread might have finished the work + // while we were waiting for the write_lock. + if (p >= ds[eigenIndex].size()) { + for(int i = ds[eigenIndex].size(); i <= p; i++) { + double approx_norm = normest1(gBs[eigenIndex], i); + ds[eigenIndex].push_back(pow(approx_norm, 1.0/double(i))); + } + } return ds[eigenIndex][p]; } + BEAGLE_CPU_ACTION_TEMPLATE + bool BeagleCPUActionImpl::hasDValue(int p, int eigenIndex) const + { + // 1. Try to read with a SHARED lock (multiple readers allowed) + std::shared_lock read_lock(ds_mutex); + return (p < ds[eigenIndex].size()); + } + BEAGLE_CPU_ACTION_TEMPLATE const char* BeagleCPUActionImpl::getName() { return getBeagleCPUActionName(); @@ -976,9 +1483,14 @@ namespace beagle { delete impl; return NULL; } + catch(const std::exception& e) + { + std::cerr<<"BEAGLE: exception in createInstance: "<. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Andrew Rambaut * @author Marc Suchard @@ -44,6 +34,8 @@ #include #include +//#define BEAGLE_CACHE_FRIENDLY + #define BEAGLE_CPU_GENERIC REALTYPE, T_PAD, P_PAD #define BEAGLE_CPU_TEMPLATE template @@ -113,9 +105,17 @@ class BeagleCPUImpl : public BeagleImpl { // tipStates field should be switched to vectors of vectors (to make // memory management less error prone REALTYPE** gPartials; + REALTYPE**** gPartialsGrad; + REALTYPE*** coalescentGrad; + // REALTYPE**** efghGrad; + REALTYPE** tempGrad; int** gTipStates; REALTYPE** gScaleBuffers; +#ifdef BEAGLE_CACHE_FRIENDLY + REALTYPE* gPartialsCache; +#endif + signed short** gAutoScaleBuffers; int* gActiveScalingFactors; @@ -124,6 +124,7 @@ class BeagleCPUImpl : public BeagleImpl { // Each kStateCount x (kStateCount+1) matrix that is flattened // into a single array REALTYPE** gTransitionMatrices; + REALTYPE**** gTransitionMatricesGrad; REALTYPE* integrationTmp; REALTYPE* firstDerivTmp; @@ -143,6 +144,12 @@ class BeagleCPUImpl : public BeagleImpl { REALTYPE* ones; REALTYPE* zeros; + std::vector gBastaBuffers; + std::vector gBastaGradBuffers; + std::vector gCoalescentBuffers; + int kCoalescentBufferLength; + int kCoalescentBufferCount; + struct threadData { std::thread t; // The thread object @@ -204,7 +211,7 @@ class BeagleCPUImpl : public BeagleImpl { // set the pre-order partials for root node // - // bufferIndices the indices of root nodes (may countain multiple) + // bufferIndices the indices of root nodes (may contain multiple) // stateFrequenciesIndices the indices of state frequencies at root // count number of root nodes int setRootPrePartials(const int* bufferIndices, @@ -229,6 +236,18 @@ class BeagleCPUImpl : public BeagleImpl { const double* inInverseEigenVectors, const double* inEigenValues); + int setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros); + + int setSparseDifferentialMatrix(int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros); + int setStateFrequencies(int stateFrequenciesIndex, const double* inStateFrequencies); @@ -290,6 +309,10 @@ class BeagleCPUImpl : public BeagleImpl { const double* edgeLengths, int count); + int updateTransitionMatricesGrad(const int* probabilityIndices, + const double* edgeLengths, + int count); + int updateTransitionMatricesWithModelCategories(int* eigenIndices, const int* probabilityIndices, const int* firstDerivativeIndices, @@ -297,7 +320,6 @@ class BeagleCPUImpl : public BeagleImpl { const double* edgeLengths, int count); - int updateTransitionMatricesWithMultipleModels(const int* eigenIndices, const int* categoryRateIndices, const int* probabilityIndices, @@ -454,6 +476,71 @@ class BeagleCPUImpl : public BeagleImpl { int getSiteDerivatives(double* outFirstDerivatives, double* outSecondDerivatives); + + int updateBastaPartials(const int* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex); + + int updateBastaPartialsGrad(const int* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex); + + int accumulateBastaPartials(const int* operations, + int operationCount, + const int* segments, + int segmentCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out); + + int accumulateBastaPartialsGrad(const int *operations, + const int operationCount, + const int *intervalStarts, + const int intervalStartsCount, + const double *intervalLengths, + const int populationSizesIndex, + const int coalescentIndex, + double *out); + + int allocateBastaBuffers(int bufferCount, + int bufferLength); + + int getBastaBuffer(int bufferIndex, + double* out); + + void reduceWithinInterval(REALTYPE* e, REALTYPE* f, // TODO move to protected + REALTYPE* g, REALTYPE* h, + int startBuffer1, int startBuffer2, + int endBuffer1, int endBuffer2, + int interval); + + void reduceWithinIntervalGrad(REALTYPE*** eGrad, REALTYPE*** fGrad, + REALTYPE*** gGrad, REALTYPE*** hGrad, + int startBuffer1, int startBuffer2, + int endBuffer1, int endBuffer2, + int interval); + + REALTYPE reduceAcrossIntervals(REALTYPE* e, REALTYPE* f, // TODO move to protected + REALTYPE* g, REALTYPE* h, + int interval, REALTYPE length, + const REALTYPE* sizes, + const REALTYPE* coalescent); + + void reduceAcrossIntervalsGrad(REALTYPE *e, REALTYPE *f, + REALTYPE *g, REALTYPE *h, + REALTYPE ***eGrad, REALTYPE ***fGrad, + REALTYPE ***gGrad, REALTYPE ***hGrad, + REALTYPE **resultGrad, + int interval, REALTYPE length, + const REALTYPE *sizes, + const REALTYPE *coalescent); int block(void); @@ -472,6 +559,13 @@ class BeagleCPUImpl : public BeagleImpl { int count, int cumulativeScaleIndex); + + virtual int calcEdgeLogDerivativesByAutoPartitionAsync(const int *operations, + int count, + double *siteLogLikelihoods, + double *outLogFirstDerivatives, + double *outLogDiagonalSecondDerivatives); + virtual int calcEdgeLogDerivatives(const int *postBufferIndices, const int *preBufferIndices, const int *firstDerivativeIndices, @@ -484,16 +578,15 @@ class BeagleCPUImpl : public BeagleImpl { double *outLogFirstDerivatives, double *outLogDiagonalSecondDerivatives); - virtual void calcEdgeLogDerivativesStates(const int *tipStates, - const REALTYPE *preOrderPartial, + virtual void calcEdgeLogDerivativesStates(const int *tipStates, const REALTYPE *preOrderPartial, const int firstDerivativeIndex, const int secondDerivativeIndex, const double *categoryRates, const REALTYPE *categoryWeights, -// const REALTYPE *cumulativeScaleBuffer, double *siteLogLikelihoods, double *outLogFirstDerivatives, - double *outLogDiagonalSecondDerivatives); + double *outLogDiagonalSecondDerivatives, + int cacheOffset); virtual void calcEdgeLogDerivativesPartials(const REALTYPE *postOrderPartial, const REALTYPE *preOrderPartial, @@ -502,10 +595,10 @@ class BeagleCPUImpl : public BeagleImpl { const double *categoryRates, const REALTYPE *categoryWeights, const int scalingFactorsIndex, -// const REALTYPE *cumulativeScaleBuffer, double *siteLogLikelihoods, double *outLogFirstDerivatives, - double *outLogDiagonalSecondDerivatives); + double *outLogDiagonalSecondDerivatives, + int cacheOffset); virtual int calcCrossProducts(const int *postBufferIndices, const int *preBufferIndices, @@ -532,11 +625,10 @@ class BeagleCPUImpl : public BeagleImpl { double *outCrossProducts, double *outSumSquaredDerivatives); - virtual void resetDerivativeTemporaries(); + virtual void resetDerivativeTemporaries(int offset); - virtual void accumulateDerivatives(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); + virtual void accumulateDerivatives(double *outDerivatives, double *outSumDerivatives, + double *outSumSquaredDerivatives, int offset); virtual void autoPartitionPartialsOperations(const int* operations, int* partitionOperations, @@ -546,6 +638,9 @@ class BeagleCPUImpl : public BeagleImpl { virtual int upPartialsByPartitionAsync(const int* operations, int operationCount); + virtual int upPrePartialsByPartitionAsync(const int* operations, + int operationCount); + virtual int reorderPatternsByPartition(); virtual void calcStatesStates(REALTYPE* destP, @@ -776,22 +871,42 @@ class BeagleCPUImpl : public BeagleImpl { void threadWaiting(threadData* tData); + void updateInnerBastaPartials(const int* operations, // TODO make protected + const int begin, + const int end, + const REALTYPE* sizes, + REALTYPE* coalescent); + + void updateInnerBastaPartials2(const int* operations, // TODO make protected + const int op, + const REALTYPE* sizes, + REALTYPE* coalescent); + + void updateInnerBastaPartialsGrad(const int* operations, + const int begin, + const int end, + const REALTYPE* sizes, + const REALTYPE* coalescent); + + void matrixMultiply(const REALTYPE* matrices1, + const REALTYPE* matrices2, + REALTYPE* output, + int n); + private: template - void accumulateDerivativesDispatch1(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); + void + accumulateDerivativesDispatch1(double *outDerivatives, double *outSumDerivatives, double *outSumSquaredDerivatives, + int offset); template - void accumulateDerivativesDispatch2(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); + void accumulateDerivativesDispatch2(double *outDerivatives, double *outSumDerivatives, + double *outSumSquaredDerivatives, int offset); template - void accumulateDerivativesImpl(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives); + void accumulateDerivativesImpl(double *outDerivatives, double *outSumDerivatives, + double *outSumSquaredDerivatives, int offset); }; BEAGLE_CPU_FACTORY_TEMPLATE diff --git a/libhmsbeagle/CPU/BeagleCPUImpl.hpp b/libhmsbeagle/CPU/BeagleCPUImpl.hpp old mode 100644 new mode 100755 index 261f5abcf..4cb95c6ef --- a/libhmsbeagle/CPU/BeagleCPUImpl.hpp +++ b/libhmsbeagle/CPU/BeagleCPUImpl.hpp @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Andrew Rambaut * @author Marc Suchard @@ -131,24 +121,75 @@ BeagleCPUImpl::~BeagleCPUImpl() { // which is TEMP_SCRATCH_PARTIAL twice. for(unsigned int i=0; i::~BeagleCPUImpl() { free(gScaleBuffers[0]); } else { for(unsigned int i=0; i::createInstance(int tipCount, if (preferenceFlags & BEAGLE_FLAG_COMPUTATION_ACTION) gEigenDecomposition = nullptr; - else if (kFlags & BEAGLE_FLAG_EIGEN_COMPLEX) + else if (bool(kFlags & BEAGLE_FLAG_EIGEN_COMPLEX) || kStateCount > 256) gEigenDecomposition = new EigenDecompositionSquare(kEigenDecompCount, kStateCount,kCategoryCount,kFlags); else @@ -359,6 +400,64 @@ int BeagleCPUImpl::createInstance(int tipCount, if (gPartials == NULL) throw std::bad_alloc(); +#ifdef BEAGLE_BASTA + // TODO: deconstrucor should free all of these + gPartialsGrad = (REALTYPE****) malloc(sizeof(REALTYPE***) * kStateCount); + for (int i = 0; i < kStateCount; i++) { + gPartialsGrad[i] = (REALTYPE***) malloc(sizeof(REALTYPE**) * kStateCount); + if (gPartialsGrad[i] == NULL) + throw std::bad_alloc(); + for (int j = 0; j < kStateCount; j++) { + gPartialsGrad[i][j] = (REALTYPE**) malloc(sizeof(REALTYPE*) * kBufferCount); + if (gPartialsGrad[i][j] == NULL) + throw std::bad_alloc(); + for (int k = 0; k < kBufferCount; k++) { + gPartialsGrad[i][j][k] = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPartialsSize); + if (gPartialsGrad[i][j][k] == NULL) + throw std::bad_alloc(); + } + } + } + // TODO: figure out the exact number of coalescent intervals + int MAX_NUM_COALESCENT_INTERVALS = 5000; + + coalescentGrad = (REALTYPE***) malloc(sizeof(REALTYPE***) * kStateCount); + for (int i = 0; i < kStateCount; i++) { + coalescentGrad[i] = (REALTYPE**) malloc(sizeof(REALTYPE**) * kStateCount); + if (coalescentGrad[i] == NULL) + throw std::bad_alloc(); + for (int j = 0; j < kStateCount; j++) { + coalescentGrad[i][j] = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * MAX_NUM_COALESCENT_INTERVALS); + if (coalescentGrad[i][j] == NULL) + throw std::bad_alloc(); + } + } + +// efghGrad = (REALTYPE****) malloc(sizeof(REALTYPE***) * 4); +// for (int i = 0; i < 4; i++) { +// efghGrad[i] = (REALTYPE***) malloc(sizeof(REALTYPE**) * kStateCount); +// if (efghGrad[i] == NULL) +// throw std::bad_alloc(); +// for (int j = 0; j < kStateCount; j++) { +// efghGrad[i][j] = (REALTYPE**) malloc(sizeof(REALTYPE*) * kStateCount); +// if (efghGrad[i][j] == NULL) +// throw std::bad_alloc(); +// for (int k = 0; k < kStateCount; k++) { +// efghGrad[i][j][k] = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPartialsPaddedStateCount * kCoalescentBufferLength); +// if (efghGrad[i][j][k] == NULL) +// throw std::bad_alloc(); +// } +// } +// } + + tempGrad = (REALTYPE**) malloc(sizeof(REALTYPE*) * kStateCount); + for (int i = 0; i < kStateCount; i++) { + tempGrad[i] = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kStateCount); + if (tempGrad[i] == NULL) + throw std::bad_alloc(); + } +#endif /* BEAGLE_BASTA */ + gStateFrequencies = (REALTYPE**) calloc(sizeof(REALTYPE*), kEigenDecompCount); if (gStateFrequencies == NULL) throw std::bad_alloc(); @@ -378,8 +477,16 @@ int BeagleCPUImpl::createInstance(int tipCount, gTipStates[i] = NULL; } +#ifdef BEAGLE_CACHE_FRIENDLY + gPartialsCache = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPartialsSize * (kBufferCount - kTipCount)); +#endif + for (int i = kTipCount; i < kBufferCount; i++) { +#ifdef BEAGLE_CACHE_FRIENDLY + gPartials[i] = gPartialsCache + (i - kTipCount) * kPartialsSize; +#else gPartials[i] = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPartialsSize); +#endif if (gPartials[i] == NULL) throw std::bad_alloc(); } @@ -430,6 +537,26 @@ int BeagleCPUImpl::createInstance(int tipCount, throw std::bad_alloc(); } +#ifdef BEAGLE_BASTA + // TODO: deconstrucor should free all of these + gTransitionMatricesGrad = (REALTYPE****) malloc(sizeof(REALTYPE***) * kStateCount); + for (int i = 0; i < kStateCount; i++) { + gTransitionMatricesGrad[i] = (REALTYPE***) malloc(sizeof(REALTYPE**) * kStateCount); + if (gTransitionMatricesGrad[i] == NULL) + throw std::bad_alloc(); + for (int j = 0; j < kStateCount; j++) { + gTransitionMatricesGrad[i][j] = (REALTYPE**) malloc(sizeof(REALTYPE*) * kMatrixCount); + if (gTransitionMatricesGrad[i][j] == NULL) + throw std::bad_alloc(); + for (int k = 0; k < kMatrixCount; k++) { + gTransitionMatricesGrad[i][j][k] = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kMatrixSize * kCategoryCount); + if (gTransitionMatricesGrad[i][j][k] == NULL) + throw std::bad_alloc(); + } + } + } +#endif + integrationTmp = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPatternCount * kStateCount); firstDerivTmp = (REALTYPE*) malloc(sizeof(REALTYPE) * kPatternCount * kStateCount); secondDerivTmp = (REALTYPE*) malloc(sizeof(REALTYPE) * kPatternCount * kStateCount); @@ -473,15 +600,12 @@ int BeagleCPUImpl::createInstance(int tipCount, if (partitionCount > hardwareThreads/2) { partitionCount = hardwareThreads/2; } - int* patternPartitions = (int*) malloc(sizeof(int) * kPatternCount); - int partitionSize = kPatternCount/partitionCount; - for (int i=0; i partitionCount - 1) - sitePartition = partitionCount - 1; - patternPartitions[i] = sitePartition; + + std::vector partitionForPattern(kPatternCount); + for (int p=0; p::setCPUThreadCount(int threadCount) { partitionCount = threadCount; } - int* patternPartitions = (int*) malloc(sizeof(int) * kPatternCount); - int partitionSize = kPatternCount/partitionCount; - for (int i=0; i partitionCount - 1) - sitePartition = partitionCount - 1; - patternPartitions[i] = sitePartition; + std::vector partitionForPattern(kPatternCount); + for (int p=0; p::setEigenDecomposition(int eigenIndex, return BEAGLE_SUCCESS; } +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros) { + + return BEAGLE_ERROR_NO_IMPLEMENTATION; +} + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::setSparseDifferentialMatrix(int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros) { + + return BEAGLE_ERROR_NO_IMPLEMENTATION; +} + BEAGLE_CPU_TEMPLATE int BeagleCPUImpl::setCategoryRates(const double* inCategoryRates) { int categoryRatesIndex=0; @@ -821,6 +961,11 @@ int BeagleCPUImpl::setPatternPartitions(int partitionCount, assert(inPatternPartitions != 0L); kPartitionCount = partitionCount; + grandDenominatorDerivTmp = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPaddedPatternCount * kPartitionCount); + grandNumeratorDerivTmp = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPaddedPatternCount * kPartitionCount); + firstDerivTmp = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPaddedPatternCount * kStateCount * kPartitionCount); + secondDerivTmp = (REALTYPE*) mallocAligned(sizeof(REALTYPE) * kPaddedPatternCount * kStateCount * kPartitionCount); + if (!kPartitionsInitialised) { gPatternPartitions = (int*) malloc(sizeof(int) * kPatternCount); @@ -1249,6 +1394,33 @@ int BeagleCPUImpl::updateTransitionMatrices(int eigenIndex, return BEAGLE_SUCCESS; } +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::updateTransitionMatricesGrad(const int* probabilityIndices, + const double* edgeLengths, + int count) { + const int matrixIncr = kStateCount + T_PAD; + + for (int u = 0; u < count; u++) { + REALTYPE* transitionMat = gTransitionMatrices[probabilityIndices[u]]; + const double edgeLength = edgeLengths[u]; + for (int a = 0; a < kStateCount; a++) { + for (int b = 0; b < kStateCount; b++) { + REALTYPE* transitionMatGrad = gTransitionMatricesGrad[a][b][probabilityIndices[u]]; + for (int c = 0; c < kStateCount; c++) { + for (int d = 0; d < kStateCount; d++) { + if (d == b) { + transitionMatGrad[c*matrixIncr + b] = edgeLength * transitionMat[c*matrixIncr + a]; + } else { + transitionMatGrad[c*matrixIncr + d] = 0.0; + } + } + } + } + } + } + return BEAGLE_SUCCESS; +} + BEAGLE_CPU_TEMPLATE int BeagleCPUImpl::updateTransitionMatricesWithModelCategories(int* eigenIndices, @@ -1265,79 +1437,980 @@ int BeagleCPUImpl::updateTransitionMatricesWithModelCategori BEAGLE_CPU_TEMPLATE -int BeagleCPUImpl::updateTransitionMatricesWithMultipleModels(const int* eigenIndices, - const int* categoryRateIndices, - const int* probabilityIndices, - const int* firstDerivativeIndices, - const int* secondDerivativeIndices, - const double* edgeLengths, - int count) { +int BeagleCPUImpl::updateTransitionMatricesWithMultipleModels(const int* eigenIndices, + const int* categoryRateIndices, + const int* probabilityIndices, + const int* firstDerivativeIndices, + const int* secondDerivativeIndices, + const double* edgeLengths, + int count) { + + // TODO: move loop to within gEigenDecomposition + + for (int i = 0; i < count; i++) { + // printf("uTMWMM %d %d %f %d\n", eigenIndices[i], probabilityIndices[i], edgeLengths[i], categoryRateIndices[i]); + + const int* firstDeriv = NULL; + const int* secondDeriv = NULL; + if (firstDerivativeIndices != NULL && secondDerivativeIndices == NULL) { + firstDeriv = &firstDerivativeIndices[i]; + } else if (firstDerivativeIndices != NULL && secondDerivativeIndices != NULL) { + firstDeriv = &firstDerivativeIndices[i]; + secondDeriv = &secondDerivativeIndices[i]; + } + + gEigenDecomposition->updateTransitionMatrices(eigenIndices[i], + &probabilityIndices[i], + firstDeriv, + secondDeriv, + &edgeLengths[i], + gCategoryRates[categoryRateIndices[i]], + gTransitionMatrices, + 1); + } + + return BEAGLE_SUCCESS; +} + + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::updatePartials(const int* operations, + int count, + int cumulativeScaleIndex) { + + int returnCode = BEAGLE_ERROR_GENERAL; + + if (kAutoPartitioningEnabled) { + autoPartitionPartialsOperations(operations, + gAutoPartitionOperations, + count, + cumulativeScaleIndex); + count *= kPartitionCount; + returnCode = upPartialsByPartitionAsync((const int*) gAutoPartitionOperations, + count); + } else { + bool byPartition = false; + returnCode = upPartials(byPartition, + operations, + count, + cumulativeScaleIndex); + } + + return returnCode; +} + + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::updatePrePartials(const int *operations, + int count, + int cumulativeScaleIndex) { + int returnCode = BEAGLE_ERROR_GENERAL; + + if (kAutoPartitioningEnabled) { + autoPartitionPartialsOperations(operations, + gAutoPartitionOperations, + count, + cumulativeScaleIndex); + count *= kPartitionCount; + returnCode = upPrePartialsByPartitionAsync((const int*) gAutoPartitionOperations, + count); + } else { + bool byPartition = false; + returnCode = upPrePartials(byPartition, + operations, + count, + cumulativeScaleIndex); + } + + return returnCode; +} + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::allocateBastaBuffers(int bufferCount, + int bufferLength) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleCPUImpl::allocateBastaBuffers\n"); +#endif + + kCoalescentBufferLength = bufferLength; + kCoalescentBufferCount = bufferCount; + + gCoalescentBuffers.resize(kCoalescentBufferCount * kCoalescentBufferLength); + gBastaBuffers.resize(kPartialsPaddedStateCount * kCoalescentBufferLength * 4); + gBastaGradBuffers.resize(4 * kStateCount * kStateCount * kPartialsPaddedStateCount * kCoalescentBufferLength); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleCPUImpl::allocateBastaBuffers\n"); +#endif + + return BEAGLE_SUCCESS; +} + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::getBastaBuffer(int bufferIndex, + double* out) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleCPUImpl::getBastaBuffer\n"); +#endif + + if (bufferIndex >= 0 && bufferIndex < kCoalescentBufferCount) { + beagleMemCpy(out, gCoalescentBuffers.data() + bufferIndex * kCoalescentBufferLength, + kCoalescentBufferLength); + } else if (bufferIndex >= kCoalescentBufferCount && bufferIndex < kCoalescentBufferCount + 4) { + bufferIndex -= kCoalescentBufferCount; + beagleMemCpy(out, gBastaBuffers.data() + bufferIndex * kPartialsPaddedStateCount, kStateCount); + } else if (bufferIndex == -1) { + for (int i = 0; i < 4; ++i) { + beagleMemCpy(out + i * kStateCount, + gBastaBuffers.data() + i * kPartialsPaddedStateCount, + kStateCount); + } + } + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleCPUImpl::getBastaBuffer\n"); +#endif + + return BEAGLE_SUCCESS; +} + +BEAGLE_CPU_TEMPLATE +void BeagleCPUImpl::updateInnerBastaPartials(const int* operations, + const int begin, + const int end, + const REALTYPE* sizes, + REALTYPE* coalescent) { + for (int op = begin; op < end; ++op) { + const int numOps = BEAGLE_BASTA_OP_COUNT; + + const int destinationPartialIndex = operations[op * numOps]; + const int child1PartialIndex = operations[op * numOps + 1]; + const int child1TransMatIndex = operations[op * numOps + 2]; + const int child2PartialIndex = operations[op * numOps + 3]; + const int child2TransMatIndex = operations[op * numOps + 4]; + const int accumulation1PartialIndex = operations[op * numOps + 5]; + const int accumulation2PartialIndex = operations[op * numOps + 6]; + const int intervalNumber = operations[op * numOps + 7]; + + const int matrixIncr = kStateCount + T_PAD; + const int stateCountModFour = (kStateCount / 4) * 4; + + REALTYPE *destPartial = gPartials[destinationPartialIndex]; + // child 1 + const REALTYPE *partial1 = gPartials[child1PartialIndex]; + const REALTYPE *matrix1 = gTransitionMatrices[child1TransMatIndex]; + + for (int i = 0; i < kStateCount; i++) { + const REALTYPE *matrices1Ptr = matrix1 + i * matrixIncr; + REALTYPE sum1A = 0.0; + REALTYPE sum1B = 0.0; + + int j = 0; + for (; j < stateCountModFour; j += 4) { + sum1A += matrices1Ptr[j + 0] * partial1[j + 0]; + sum1B += matrices1Ptr[j + 1] * partial1[j + 1]; + sum1A += matrices1Ptr[j + 2] * partial1[j + 2]; + sum1B += matrices1Ptr[j + 3] * partial1[j + 3]; + + } + + for (; j < kStateCount; j++) { + sum1A += matrices1Ptr[j] * partial1[j]; + } + + destPartial[i] = sum1A + sum1B; + } + + if (child2PartialIndex >= 0) { + + // child 2 + const REALTYPE *partial2 = gPartials[child2PartialIndex]; + const REALTYPE *matrix2 = gTransitionMatrices[child2TransMatIndex]; + + REALTYPE *accumulation1 = gPartials[accumulation1PartialIndex]; + REALTYPE *accumulation2 = gPartials[accumulation2PartialIndex]; + + REALTYPE prob = REALTYPE(0); + + for (int i = 0; i < kStateCount; i++) { + const REALTYPE *matrices2Ptr = matrix2 + i * matrixIncr; + REALTYPE sum2A = 0.0; + REALTYPE sum2B = 0.0; + + int j = 0; + for (; j < stateCountModFour; j += 4) { + sum2A += matrices2Ptr[j + 0] * partial2[j + 0]; + sum2B += matrices2Ptr[j + 1] * partial2[j + 1]; + sum2A += matrices2Ptr[j + 2] * partial2[j + 2]; + sum2B += matrices2Ptr[j + 3] * partial2[j + 3]; + } + + for (; j < kStateCount; j++) { + sum2A += matrices2Ptr[j] * partial2[j]; + } + + REALTYPE child1 = destPartial[i]; + REALTYPE child2 = sum2A + sum2B; + REALTYPE parent = child1 * child2 / sizes[i]; + + accumulation1[i] = child1; + accumulation2[i] = child2; + destPartial[i] = parent; + + prob += parent; + } + + for (int i = 0; i < kStateCount; i++) { + destPartial[i] /= prob; + } + + coalescent[intervalNumber] = prob; + } + } +} + +BEAGLE_CPU_TEMPLATE +void BeagleCPUImpl::updateInnerBastaPartials2(const int* operations, + const int op, + const REALTYPE* sizes, + REALTYPE* coalescent) { + const int numOps = BEAGLE_BASTA_OP_COUNT; + + const int destinationPartialIndex = operations[op * numOps]; + const int child1PartialIndex = operations[op * numOps + 1]; + const int child1TransMatIndex = operations[op * numOps + 2]; + const int child2PartialIndex = operations[op * numOps + 3]; + const int child2TransMatIndex = operations[op * numOps + 4]; + const int accumulation1PartialIndex = operations[op * numOps + 5]; + const int accumulation2PartialIndex = operations[op * numOps + 6]; + const int intervalNumber = operations[op * numOps + 7]; + + const int matrixIncr = kStateCount + T_PAD; + const int stateCountModFour = (kStateCount / 4) * 4; + + REALTYPE *destPartial = gPartials[destinationPartialIndex]; + + // child 1 + const REALTYPE *partial1 = gPartials[child1PartialIndex]; + const REALTYPE *matrix1 = gTransitionMatrices[child1TransMatIndex]; + + for (int i = 0; i < kStateCount; i++) { + const REALTYPE *matrices1Ptr = matrix1 + i * matrixIncr; + REALTYPE sum1A = 0.0; + REALTYPE sum1B = 0.0; + + int j = 0; + for (; j < stateCountModFour; j += 4) { + sum1A += matrices1Ptr[j + 0] * partial1[j + 0]; + sum1B += matrices1Ptr[j + 1] * partial1[j + 1]; + sum1A += matrices1Ptr[j + 2] * partial1[j + 2]; + sum1B += matrices1Ptr[j + 3] * partial1[j + 3]; + } + + for (; j < kStateCount; j++) { + sum1A += matrices1Ptr[j] * partial1[j]; + } + + destPartial[i] = sum1A + sum1B; + } + + if (child2PartialIndex >= 0) { + + // child 2 + const REALTYPE *partial2 = gPartials[child2PartialIndex]; + const REALTYPE *matrix2 = gTransitionMatrices[child2TransMatIndex]; + + REALTYPE *accumulation1 = gPartials[accumulation1PartialIndex]; + REALTYPE *accumulation2 = gPartials[accumulation2PartialIndex]; + + REALTYPE prob = REALTYPE(0); + + for (int i = 0; i < kStateCount; i++) { + const REALTYPE *matrices2Ptr = matrix2 + i * matrixIncr; + REALTYPE sum2A = 0.0; + REALTYPE sum2B = 0.0; + + int j = 0; + for (; j < stateCountModFour; j += 4) { + sum2A += matrices2Ptr[j + 0] * partial2[j + 0]; + sum2B += matrices2Ptr[j + 1] * partial2[j + 1]; + sum2A += matrices2Ptr[j + 2] * partial2[j + 2]; + sum2B += matrices2Ptr[j + 3] * partial2[j + 3]; + } + + for (; j < kStateCount; j++) { + sum2A += matrices2Ptr[j] * partial2[j]; + } + + REALTYPE child1 = destPartial[i]; + REALTYPE child2 = sum2A + sum2B; + REALTYPE parent = child1 * child2 / sizes[i]; + + accumulation1[i] = child1; + accumulation2[i] = child2; + destPartial[i] = parent; + + prob += parent; + } + + for (int i = 0; i < kStateCount; i++) { + destPartial[i] /= prob; + } + + coalescent[intervalNumber] = prob; + } +} + +BEAGLE_CPU_TEMPLATE +void BeagleCPUImpl::updateInnerBastaPartialsGrad(const int* operations, + const int begin, + const int end, + const REALTYPE* sizes, + const REALTYPE* coalescent) { + for (int op = begin; op < end; ++op) { + + const int numOps = BEAGLE_BASTA_OP_COUNT; + + const int destinationPartialIndex = operations[op * numOps]; + const int child1PartialIndex = operations[op * numOps + 1]; + const int child1TransMatIndex = operations[op * numOps + 2]; + const int child2PartialIndex = operations[op * numOps + 3]; + const int child2TransMatIndex = operations[op * numOps + 4]; + const int accumulation1PartialIndex = operations[op * numOps + 5]; + const int accumulation2PartialIndex = operations[op * numOps + 6]; + const int intervalNumber = operations[op * numOps + 7]; + + const int matrixIncr = kStateCount + T_PAD; + const int stateCountModFour = (kStateCount / 4) * 4; + + REALTYPE *destPartial = gPartials[destinationPartialIndex]; + + // child 1 + const REALTYPE *partial1 = gPartials[child1PartialIndex]; + const REALTYPE *matrix1 = gTransitionMatrices[child1TransMatIndex]; + for (int a = 0; a < kStateCount; a++) { + for (int b = 0; b < kStateCount; b++) { + const REALTYPE *partialGrad1 = gPartialsGrad[a][b][child1PartialIndex]; +// for (int i = 0; i < 4; i++) { +// std::cout << "partialGrad1:" << partialGrad1[i] << std::endl; +// } +// for (int i = 0; i < 4; i++) { +// std::cout << "partial1:" << partial1[i] << std::endl; +// } + const REALTYPE *matrixGrad1 = gTransitionMatricesGrad[a][b][child1TransMatIndex]; + +// for (int i = 0; i < kMatrixSize; ++i) { +// std::cout << "matrix grad:" << matrixGrad1[i] << std::endl; +// } + for (int i = 0; i < kStateCount; i++) { + REALTYPE sum = 0.0; + const REALTYPE *matrices1Ptr = matrix1 + i * matrixIncr; + const REALTYPE *matricesGrad1Ptr = matrixGrad1 + i * matrixIncr; + REALTYPE *destPartialGrad = gPartialsGrad[a][b][destinationPartialIndex]; + for (int j = 0; j < kStateCount; j++) { + sum += matrices1Ptr[j] * partialGrad1[j] + matricesGrad1Ptr[j] * partial1[j]; + } + destPartialGrad[i] = sum; + } + } + } + +// for (int a = 0; a < kStateCount; ++a) { +// for (int b = 0; b < kStateCount; ++b) { +// std::cout << "a:" << a << std::endl; +// std::cout << "b:" << b << std::endl; +// for (int i = 0; i < 4; i++) { +// std::cout << " result:" << "\n"; +// std::cout << gPartialsGrad[a][b][destinationPartialIndex][i] << ' '; +// } +// std::cout << " " << "\n"; +// } +// } + + if (child2PartialIndex >= 0) { + // child 2 + const REALTYPE *partial2 = gPartials[child2PartialIndex]; + const REALTYPE *matrix2 = gTransitionMatrices[child2TransMatIndex]; + + REALTYPE *accumulation1 = gPartials[accumulation1PartialIndex]; + REALTYPE *accumulation2 = gPartials[accumulation2PartialIndex]; + + for (int a = 0; a < kStateCount; a++) { + for (int b = 0; b < kStateCount; b++) { + REALTYPE J = coalescent[intervalNumber]; + + // first half + const REALTYPE *partialGrad2 = gPartialsGrad[a][b][child2PartialIndex]; + const REALTYPE *matrixGrad2 = gTransitionMatricesGrad[a][b][child2TransMatIndex]; + + REALTYPE *destPartialGrad = gPartialsGrad[a][b][destinationPartialIndex]; + REALTYPE *accumulationGrad1 = gPartialsGrad[a][b][accumulation1PartialIndex]; + REALTYPE *accumulationGrad2 = gPartialsGrad[a][b][accumulation2PartialIndex]; + + REALTYPE partial_J_ab = REALTYPE(0); + for (int i = 0; i < kStateCount; i++) { + // sum is child2Grad + REALTYPE sum = 0.0; + const REALTYPE *matrices2Ptr = matrix2 + i * matrixIncr; + const REALTYPE *matricesGrad2Ptr = matrixGrad2 + i * matrixIncr; + + for (int j = 0; j < kStateCount; j++) { + sum += matrices2Ptr[j] * partialGrad2[j] + matricesGrad2Ptr[j] * partial2[j]; + } + REALTYPE child1Grad = gPartialsGrad[a][b][destinationPartialIndex][i]; + REALTYPE child1 = accumulation1[i]; + REALTYPE child2 = accumulation2[i]; + + REALTYPE entry = (child1Grad * child2 + child1 * sum) / sizes[i]; + partial_J_ab += entry; + + destPartialGrad[i] = entry / J; + accumulationGrad1[i] = child1Grad; + accumulationGrad2[i] = sum; + } + + // second half + for (int i = 0; i < kStateCount; i++) { + REALTYPE entry = destPartial[i]; + destPartialGrad[i] -= partial_J_ab * entry / J; + } + coalescentGrad[a][b][intervalNumber] = partial_J_ab; + } + } + } +// for (int a = 0; a < kStateCount; ++a) { +// for (int b = 0; b < kStateCount; ++b) { +// std::cout << "a:" << a << std::endl; +// std::cout << "b:" << b << std::endl; +// if (child2PartialIndex >= 0) { +// for (int i = 0; i < 4; i++) { +// std::cout << " left:" << "\n"; +// std::cout << gPartialsGrad[a][b][accumulation1PartialIndex][i] << ' '; +// } +// +// for (int i = 0; i < 4; i++) { +// std::cout << " right:" << "\n"; +// std::cout << gPartialsGrad[a][b][accumulation2PartialIndex][i] << ' '; +// } +// } +// for (int i = 0; i < 4; i++) { +// std::cout << " result:" << "\n"; +// std::cout << gPartialsGrad[a][b][destinationPartialIndex][i] << ' '; +// } +// std::cout << " " << "\n"; +// } +// } + + } +} + + + +BEAGLE_CPU_TEMPLATE +void BeagleCPUImpl::matrixMultiply(const REALTYPE* matrix1, + const REALTYPE* matrix2, + REALTYPE* output, + int n) { + #pragma omp parallel for + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + REALTYPE sum = 0.0; + for (int k = 0; k < n; k++) { + sum += matrix1[i*n + k] * matrix2[k*n + j]; + } + output[i*n + j] = sum; + } + } +} + +template +inline void for_each(Integer begin, Integer end, Function function, int global_num_threads) { + std::vector threads; + threads.reserve(global_num_threads); + + // Calculate the chunk size for each thread + size_t chunk_size = (end - begin) / global_num_threads; + size_t remainder = (end - begin) % global_num_threads; + + // Perform the operation in parallel using threads + for (size_t i = 0; i < global_num_threads; ++i) { + Integer thread_begin = begin + i * chunk_size; + Integer thread_end = thread_begin + chunk_size; + if (i == global_num_threads - 1) { + // Include the remainder in the last thread + thread_end += remainder; + } + + threads.emplace_back([thread_begin, thread_end, &function] { +// threads.emplace_back([&] { + function(thread_begin, thread_end); +// for (int j = thread_begin; j < thread_end; ++j) { +// function(j); +// } + }); + } + + // Wait for all threads to finish + for (auto &thread : threads) { + thread.join(); + } +} + + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::updateBastaPartials(const int* operations, + const int count, + const int* intervals, + const int intervalCount, + const int populationSizesIndex, + const int coalescentIndex) { + int returnCode = BEAGLE_SUCCESS; + + REALTYPE* coalescent = gCoalescentBuffers.data() + kCoalescentBufferLength * coalescentIndex; + std::fill(coalescent, coalescent + kCoalescentBufferLength, REALTYPE(0)); + + const REALTYPE* sizes = gStateFrequencies[populationSizesIndex]; + + bool THREADING = true; + int CUT_POINT = 1280000; + int nThreads = 2; + + if (THREADING) { + + for (int i = 0; i < intervalCount - 1; ++i) { + + const int begin = intervals[i]; + const int end = intervals[i + 1]; + + if (end - begin > CUT_POINT) { + for_each(begin, end, [&](const int threadBegin, const int threadEnd) { + updateInnerBastaPartials(operations, threadBegin, threadEnd, sizes, coalescent); + }, nThreads); +// for_each(begin, end, [&](const int j) { +// updateInnerBastaPartials2(operations, j, sizes, coalescent); +// }, nThreads); + } else { + updateInnerBastaPartials(operations, begin, end, sizes, coalescent); + } + } + } else { + updateInnerBastaPartials(operations, 0, count, sizes, coalescent); + } + + return returnCode; +} + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::updateBastaPartialsGrad(const int* operations, + const int count, + const int* intervals, + const int intervalCount, + const int populationSizesIndex, + const int coalescentIndex) { + int returnCode = BEAGLE_SUCCESS; + + // REALTYPE* coalescent = gCoalescentBuffers.data() + kCoalescentBufferLength * coalescentIndex; + // std::fill(coalescent, coalescent + kCoalescentBufferLength, REALTYPE(0)); + // just for test + const REALTYPE* coalescent = gCoalescentBuffers.data() + kCoalescentBufferLength * coalescentIndex; + const REALTYPE* sizes = gStateFrequencies[populationSizesIndex]; + + bool THREADING = true; + int CUT_POINT = 1280000; + int nThreads = 2; + + if (THREADING) { + + for (int i = 0; i < intervalCount - 1; ++i) { + const int begin = intervals[i]; + const int end = intervals[i + 1]; + + if (end - begin > CUT_POINT) { + for_each(begin, end, [&](const int threadBegin, const int threadEnd) { + updateInnerBastaPartialsGrad(operations, threadBegin, threadEnd, sizes, coalescent); + }, nThreads); +// for_each(begin, end, [&](const int j) { +// updateInnerBastaPartials2(operations, j, sizes, coalescent); +// }, nThreads); + } else { + updateInnerBastaPartialsGrad(operations, begin, end, sizes, coalescent); + } + } + } else { + updateInnerBastaPartialsGrad(operations, 0, count, sizes, coalescent); + } + + return returnCode; +} + +BEAGLE_CPU_TEMPLATE +REALTYPE BeagleCPUImpl::reduceAcrossIntervals( + REALTYPE* e, REALTYPE* f, + REALTYPE* g, REALTYPE* h, + int interval, REALTYPE length, + const REALTYPE* sizes, + const REALTYPE* coalescent) { + + e += interval * kPartialsPaddedStateCount; + f += interval * kPartialsPaddedStateCount; + g += interval * kPartialsPaddedStateCount; + h += interval * kPartialsPaddedStateCount; + REALTYPE sum = REALTYPE(0); + for (int k = 0; k < kStateCount; ++k) { + sum += (e[k] * e[k] - f[k] + + g[k] * g[k] - h[k]) / sizes[k]; + } + + REALTYPE logL = -length * sum / 4; + + REALTYPE prob = coalescent[interval]; + if (prob != REALTYPE(0)) { + logL += log(prob); + } + + return logL; +} + + +BEAGLE_CPU_TEMPLATE +void BeagleCPUImpl::reduceAcrossIntervalsGrad( + REALTYPE* e, REALTYPE* f, + REALTYPE* g, REALTYPE* h, + REALTYPE*** eGrad, REALTYPE*** fGrad, + REALTYPE*** gGrad, REALTYPE*** hGrad, + REALTYPE** resultGrad, + int interval, REALTYPE length, + const REALTYPE* sizes, + const REALTYPE* coalescent) { + + const int offset = interval * kPartialsPaddedStateCount; + + e += offset; + g += offset; + + for (int a = 0; a < kStateCount; ++a) { + for (int b = 0; b < kStateCount; ++b) { + REALTYPE sum = REALTYPE(0); + REALTYPE* eGrad_ab = (REALTYPE*) eGrad[a][b] + offset; + REALTYPE* fGrad_ab = (REALTYPE*) fGrad[a][b] + offset; + REALTYPE* gGrad_ab = (REALTYPE*) gGrad[a][b] + offset; + REALTYPE* hGrad_ab = (REALTYPE*) hGrad[a][b] + offset; + + for (int k = 0; k < kStateCount; ++k) { + sum += (2 * e[k] * eGrad_ab[k] - fGrad_ab[k] + + 2 * g[k] * gGrad_ab[k] - hGrad_ab[k]) / sizes[k]; + } + resultGrad[a][b] = -length * sum / 4; + REALTYPE prob = coalescent[interval]; + if (prob != REALTYPE(0)) { + resultGrad[a][b] += coalescentGrad[a][b][interval] / prob; + } + } + } +} + +BEAGLE_CPU_TEMPLATE +void BeagleCPUImpl::reduceWithinInterval(REALTYPE* e, REALTYPE* f, + REALTYPE* g, REALTYPE* h, + int startBuffer1, int startBuffer2, + int endBuffer1, int endBuffer2, + int interval) { + + e += interval * kPartialsPaddedStateCount; + f += interval * kPartialsPaddedStateCount; + g += interval * kPartialsPaddedStateCount; + h += interval * kPartialsPaddedStateCount; + + const REALTYPE* startPartials = gPartials[startBuffer1]; + const REALTYPE* endPartials = gPartials[endBuffer1]; + + for (int i = 0; i < kStateCount; ++i) { + REALTYPE startP = startPartials[i]; + e[i] += startP; + f[i] += startP * startP; + + REALTYPE endP = endPartials[i]; + g[i] += endP; + h[i] += endP * endP; + } + + if (startBuffer2 >= 0) { + + const REALTYPE* startPartials = gPartials[startBuffer2]; + const REALTYPE* endPartials = gPartials[endBuffer2]; + + for (int i = 0; i < kStateCount; ++i) { + REALTYPE startP = startPartials[i]; + e[i] += startP; + f[i] += startP * startP; + + REALTYPE endP = endPartials[i]; + g[i] += endP; + h[i] += endP * endP; + } + } +} + + +BEAGLE_CPU_TEMPLATE +void BeagleCPUImpl::reduceWithinIntervalGrad(REALTYPE*** eGrad, REALTYPE*** fGrad, + REALTYPE*** gGrad, REALTYPE*** hGrad, + int startBuffer1, int startBuffer2, + int endBuffer1, int endBuffer2, + int interval) { + const int offset = interval * kPartialsPaddedStateCount; +// std::cout << "interval:" << interval << std::endl; + const REALTYPE* startPartials = gPartials[startBuffer1]; + const REALTYPE* endPartials = gPartials[endBuffer1]; + + for (int a = 0; a < kStateCount; ++a) { + for (int b = 0; b < kStateCount; ++b) { + REALTYPE* eGrad_ab = (REALTYPE*) eGrad[a][b] + offset; + REALTYPE* fGrad_ab = (REALTYPE*) fGrad[a][b] + offset; + REALTYPE* gGrad_ab = (REALTYPE*) gGrad[a][b] + offset; + REALTYPE* hGrad_ab = (REALTYPE*) hGrad[a][b] + offset; +// std::cout << "a:" << a << std::endl; +// std::cout << "b:" << b << std::endl; + for (int i = 0; i < kStateCount; ++i) { + REALTYPE startPGrad = gPartialsGrad[a][b][startBuffer1][i]; + REALTYPE startP = startPartials[i]; +// std::cout << "startPGrad:" << startPGrad << std::endl; + eGrad_ab[i] += startPGrad; + fGrad_ab[i] += 2 * startP * startPGrad; + + + //same for endPGrad and endP + REALTYPE endPGrad = gPartialsGrad[a][b][endBuffer1][i]; + REALTYPE endP = endPartials[i]; + gGrad_ab[i] += endPGrad; + hGrad_ab[i] += 2 * endP * endPGrad; +// std::cout << "endPGrad:" << endPGrad << std::endl; + } + +// for (int i = 0; i < 4; i++) { +// std::cout << "fGrad_ab:" << "\n"; +// std::cout << fGrad_ab[i] << ' '; +// } +// for (int i = 0; i < 4; i++) { +// std::cout << "hGrad_ab:" << "\n"; +// std::cout << hGrad_ab[i] << ' '; +// } + } + } + + + if (startBuffer2 >= 0) { + // same for startBuffer2 and endBuffer2 + const REALTYPE* startPartials = gPartials[startBuffer2]; + const REALTYPE* endPartials = gPartials[endBuffer2]; + + for (int a = 0; a < kStateCount; ++a) { + for (int b = 0; b < kStateCount; ++b) { + +// std::cout << "a:" << a << std::endl; +// std::cout << "b:" << b << std::endl; + + REALTYPE* eGrad_ab = (REALTYPE*) eGrad[a][b] + offset; + REALTYPE* fGrad_ab = (REALTYPE*) fGrad[a][b] + offset; + REALTYPE* gGrad_ab = (REALTYPE*) gGrad[a][b] + offset; + REALTYPE* hGrad_ab = (REALTYPE*) hGrad[a][b] + offset; + + for (int i = 0; i < kStateCount; ++i) { + REALTYPE startPGrad = gPartialsGrad[a][b][startBuffer2][i]; + REALTYPE startP = startPartials[i]; + eGrad_ab[i] += startPGrad; + fGrad_ab[i] += 2 * startP * startPGrad; + + //same for endPGrad and endP + REALTYPE endPGrad = gPartialsGrad[a][b][endBuffer2][i]; + REALTYPE endP = endPartials[i]; + gGrad_ab[i] += endPGrad; + hGrad_ab[i] += 2 * endP * endPGrad; + } + +// for (int i = 0; i < 4; i++) { +// std::cout << "fGrad_ab:" << "\n"; +// std::cout << fGrad_ab[i] << ' '; +// } +// for (int i = 0; i < 4; i++) { +// std::cout << "hGrad_ab:" << "\n"; +// std::cout << hGrad_ab[i] << ' '; +// } + + } + } + } +} + +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::accumulateBastaPartials(const int* operations, + const int operationCount, + const int* intervalStarts, + const int intervalStartsCount, + const double* intervalLengths, + const int populationSizesIndex, + const int coalescentIndex, + double* out) { + int returnCode = BEAGLE_SUCCESS; - // TODO: move loop to within gEigenDecomposition + std::fill(gBastaBuffers.begin(), gBastaBuffers.end(), REALTYPE(0)); - for (int i = 0; i < count; i++) { - // printf("uTMWMM %d %d %f %d\n", eigenIndices[i], probabilityIndices[i], edgeLengths[i], categoryRateIndices[i]); + REALTYPE* e = gBastaBuffers.data() + 0 * kPartialsPaddedStateCount * kCoalescentBufferLength; + REALTYPE* f = gBastaBuffers.data() + 1 * kPartialsPaddedStateCount * kCoalescentBufferLength; + REALTYPE* g = gBastaBuffers.data() + 2 * kPartialsPaddedStateCount * kCoalescentBufferLength; + REALTYPE* h = gBastaBuffers.data() + 3 * kPartialsPaddedStateCount * kCoalescentBufferLength; - const int* firstDeriv = NULL; - const int* secondDeriv = NULL; - if (firstDerivativeIndices != NULL && secondDerivativeIndices == NULL) { - firstDeriv = &firstDerivativeIndices[i]; - } else if (firstDerivativeIndices != NULL && secondDerivativeIndices != NULL) { - firstDeriv = &firstDerivativeIndices[i]; - secondDeriv = &secondDerivativeIndices[i]; + const REALTYPE* coalescent = gCoalescentBuffers.data() + kCoalescentBufferLength * coalescentIndex; + const REALTYPE* sizes = gStateFrequencies[populationSizesIndex]; + for (int interval = 0; interval < intervalStartsCount - 1; ++interval) { // TODO execute in parallel (no race conditions) + const int start = intervalStarts[interval]; + const int end = intervalStarts[interval + 1]; + + for (int op = start; op < end; ++op) { // TODO execute in parallel (has race conditions on e,f,g,h + + const int numOps = BEAGLE_BASTA_OP_COUNT; + + const int destinationPartialIndex = operations[op * numOps]; + const int child1PartialIndex = operations[op * numOps + 1]; + const int child1TransMatIndex = operations[op * numOps + 2]; + const int child2PartialIndex = operations[op * numOps + 3]; + const int child2TransMatIndex = operations[op * numOps + 4]; + const int accumulation1PartialIndex = operations[op * numOps + 5]; + const int accumulation2PartialIndex = operations[op * numOps + 6]; + const int intervalNumber = operations[op * numOps + 7]; + + reduceWithinInterval(e, f, g, h, + child1PartialIndex, child2PartialIndex, + accumulation1PartialIndex, accumulation2PartialIndex, + intervalNumber); } + } - gEigenDecomposition->updateTransitionMatrices(eigenIndices[i], - &probabilityIndices[i], - firstDeriv, - secondDeriv, - &edgeLengths[i], - gCategoryRates[categoryRateIndices[i]], - gTransitionMatrices, - 1); + REALTYPE logL = 0.0; + for (int i = 0; i < intervalStartsCount - 1; ++i) { // TODO execute in parallel + const int op = intervalStarts[i]; + + const int numOps = BEAGLE_BASTA_OP_COUNT; + + const int destinationPartialIndex = operations[op * numOps]; + const int child1PartialIndex = operations[op * numOps + 1]; + const int child1TransMatIndex = operations[op * numOps + 2]; + const int child2PartialIndex = operations[op * numOps + 3]; + const int child2TransMatIndex = operations[op * numOps + 4]; + const int accumulation1PartialIndex = operations[op * numOps + 5]; + const int accumulation2PartialIndex = operations[op * numOps + 6]; + const int intervalNumber = operations[op * numOps + 7]; + + logL += reduceAcrossIntervals(e, f, g, h, + intervalNumber, intervalLengths[i], + sizes, coalescent); } - return BEAGLE_SUCCESS; + out[0] = (double) logL; + + return returnCode; } BEAGLE_CPU_TEMPLATE -int BeagleCPUImpl::updatePartials(const int* operations, - int count, - int cumulativeScaleIndex) { +int BeagleCPUImpl::accumulateBastaPartialsGrad(const int* operations, + const int operationCount, + const int* intervalStarts, + const int intervalStartsCount, + const double* intervalLengths, + const int populationSizesIndex, + const int coalescentIndex, + double* out) { + int returnCode = BEAGLE_SUCCESS; + + REALTYPE* e = gBastaBuffers.data() + 0 * kPartialsPaddedStateCount * kCoalescentBufferLength; + REALTYPE* f = gBastaBuffers.data() + 1 * kPartialsPaddedStateCount * kCoalescentBufferLength; + REALTYPE* g = gBastaBuffers.data() + 2 * kPartialsPaddedStateCount * kCoalescentBufferLength; + REALTYPE* h = gBastaBuffers.data() + 3 * kPartialsPaddedStateCount * kCoalescentBufferLength; + +// std::fill(&efghGrad[0][0][0][0], &efghGrad[0][0][0][0] + sizeof(efghGrad) / sizeof(efghGrad[0][0][0][0]), REALTYPE(0)); +// +// REALTYPE*** eGrad = efghGrad[0]; +// REALTYPE*** fGrad = efghGrad[1]; +// REALTYPE*** gGrad = efghGrad[2]; +// REALTYPE*** hGrad = efghGrad[3]; + std::fill(gBastaGradBuffers.begin(), gBastaGradBuffers.end(), REALTYPE(0)); + // Create the 4D array structure using pointers into the contiguous memory block + REALTYPE**** efghGrad = new REALTYPE***[4]; + for (int i = 0; i < 4; i++) { + efghGrad[i] = new REALTYPE**[kStateCount]; + for (int j = 0; j < kStateCount; j++) { + efghGrad[i][j] = new REALTYPE*[kStateCount]; + for (int k = 0; k < kStateCount; k++) { + int offset = ((i * kStateCount + j) * kStateCount + k) * kPartialsPaddedStateCount * kCoalescentBufferLength; + efghGrad[i][j][k] = gBastaGradBuffers.data() + offset; + } + } + } - int returnCode = BEAGLE_ERROR_GENERAL; + REALTYPE*** eGrad = efghGrad[0]; + REALTYPE*** fGrad = efghGrad[1]; + REALTYPE*** gGrad = efghGrad[2]; + REALTYPE*** hGrad = efghGrad[3]; - if (kAutoPartitioningEnabled) { - autoPartitionPartialsOperations(operations, - gAutoPartitionOperations, - count, - cumulativeScaleIndex); - count *= kPartitionCount; - returnCode = upPartialsByPartitionAsync((const int*) gAutoPartitionOperations, - count); - } else { - bool byPartition = false; - returnCode = upPartials(byPartition, - operations, - count, - cumulativeScaleIndex); - } + const REALTYPE* coalescent = gCoalescentBuffers.data() + kCoalescentBufferLength * coalescentIndex; + const REALTYPE* sizes = gStateFrequencies[populationSizesIndex]; - return returnCode; -} + for (int interval = 0; interval < intervalStartsCount - 1; ++interval) { + const int start = intervalStarts[interval]; + const int end = intervalStarts[interval + 1]; + for (int op = start; op < end; ++op) { // TODO execute in parallel (has race conditions on e,f,g,h -BEAGLE_CPU_TEMPLATE -int BeagleCPUImpl::updatePrePartials(const int *operations, - int count, - int cumulativeScaleIndex) { - int returnCode = BEAGLE_ERROR_GENERAL; + const int numOps = BEAGLE_BASTA_OP_COUNT; - bool byPartition = false; - returnCode = upPrePartials(byPartition, operations, count, cumulativeScaleIndex); + const int destinationPartialIndex = operations[op * numOps]; + const int child1PartialIndex = operations[op * numOps + 1]; + const int child1TransMatIndex = operations[op * numOps + 2]; + const int child2PartialIndex = operations[op * numOps + 3]; + const int child2TransMatIndex = operations[op * numOps + 4]; + const int accumulation1PartialIndex = operations[op * numOps + 5]; + const int accumulation2PartialIndex = operations[op * numOps + 6]; + const int intervalNumber = operations[op * numOps + 7]; - return returnCode; + reduceWithinIntervalGrad(eGrad, fGrad, gGrad, hGrad, + child1PartialIndex, child2PartialIndex, + accumulation1PartialIndex, accumulation2PartialIndex, + intervalNumber); + } + } + + for (int a = 0; a < kStateCount; ++a) { + for (int b = 0; b < kStateCount; ++b) { + out[a*kStateCount+b] = (double) 0; + } + } + + for (int i = 0; i < intervalStartsCount - 1; ++i) { + const int op = intervalStarts[i]; + + const int numOps = BEAGLE_BASTA_OP_COUNT; + + const int destinationPartialIndex = operations[op * numOps]; + const int child1PartialIndex = operations[op * numOps + 1]; + const int child1TransMatIndex = operations[op * numOps + 2]; + const int child2PartialIndex = operations[op * numOps + 3]; + const int child2TransMatIndex = operations[op * numOps + 4]; + const int accumulation1PartialIndex = operations[op * numOps + 5]; + const int accumulation2PartialIndex = operations[op * numOps + 6]; + const int intervalNumber = operations[op * numOps + 7]; + reduceAcrossIntervalsGrad(e, f, g, h, + eGrad, fGrad, gGrad, hGrad, + tempGrad, // save output here! + intervalNumber, intervalLengths[i], + sizes, coalescent); + for (int a = 0; a < kStateCount; ++a) { + for (int b = 0; b < kStateCount; ++b) { + out[a*kStateCount+b] += tempGrad[a][b]; + } + } + } + return returnCode; } //BEAGLE_CPU_TEMPLATE @@ -1375,13 +2448,149 @@ int BeagleCPUImpl::calculateEdgeDerivatives(const int *postB double *outDerivatives, double *outSumDerivatives, double *outSumSquaredDerivatives) { - return calcEdgeLogDerivatives( - postBufferIndices, preBufferIndices, - derivativeMatrixIndices, NULL, - categoryWeightsIndices,categoryRatesIndices, cumulativeScaleIndices, - count, - outDerivatives, - outSumDerivatives, outSumSquaredDerivatives); + int returnCode = BEAGLE_ERROR_GENERAL; + + if (kAutoPartitioningEnabled && kPartitionCount > 1) { + + + + int numOps = BEAGLE_OP_COUNT; + int numOpsP = BEAGLE_PARTITION_OP_COUNT; + + int perThreadCount = (count - (count % kPartitionCount)) / kPartitionCount; + +#ifdef BEAGLE_DEBUG_FLOW + std::cerr<<"Mark 0" << ", Original count = "<< count << ", perThreadCount = " << perThreadCount < threadTask( + std::bind(&BeagleCPUImpl::calcEdgeLogDerivativesByAutoPartitionAsync, this, + (const int*) gThreadOperations[i], + gThreadOpCounts[i], + outDerivatives, + outSumDerivatives, + outSumSquaredDerivatives)); + + gFutures[i] = threadTask.get_future(); + threadData* td = &gThreads[i]; + + std::unique_lock l(td->m); + td->jobs.push(std::move(threadTask)); + l.unlock(); + + gThreads[i].cv.notify_one(); + } + + for (int i=0; i::updatePrePartialsByPartition(const int* o int returnCode = BEAGLE_ERROR_GENERAL; if (kThreadingEnabled) { -// TODO -// returnCode = upPrePartialsByPartitionAsync(operations, -// count); + returnCode = upPrePartialsByPartitionAsync(operations, + count); } else { bool byPartition = true; returnCode = upPrePartials(byPartition, @@ -1505,6 +2713,47 @@ int BeagleCPUImpl::upPartialsByPartitionAsync(const int* ope return BEAGLE_SUCCESS; } +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::upPrePartialsByPartitionAsync(const int* operations, + int count) { + + int numOps = BEAGLE_PARTITION_OP_COUNT; + + memset(gThreadOpCounts, 0, sizeof(int) * kNumThreads); + + for (int i=0; i threadTask( + std::bind(&BeagleCPUImpl::upPrePartials, this, + true, + (const int*) gThreadOperations[i], + gThreadOpCounts[i], + BEAGLE_OP_NONE)); + + gFutures[i] = threadTask.get_future(); + threadData* td = &gThreads[i]; + + std::unique_lock l(td->m); + td->jobs.push(std::move(threadTask)); + l.unlock(); + + gThreads[i].cv.notify_one(); + } + + for (int i=0; i::upPartials(bool byPartition, const int* operations, @@ -1948,6 +3197,100 @@ int BeagleCPUImpl::calcCrossProducts(const int *postBufferIn return returnCode; } +BEAGLE_CPU_TEMPLATE +int BeagleCPUImpl::calcEdgeLogDerivativesByAutoPartitionAsync(const int *operations, + int count, + double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives) { + + int returnCode = BEAGLE_SUCCESS; + + int numOps = BEAGLE_OP_COUNT; + int numOpsP = BEAGLE_PARTITION_OP_COUNT; + + const int secondDerivativeIndex = BEAGLE_OP_NONE; + const double *categoryRates = NULL; // gCategoryRates[categoryRatesIndices[0]]; // TODO Generalize + const REALTYPE *categoryWeights = gCategoryWeights[operations[3]]; // TODO Generalize + + + + for (int nodeNum = 0; nodeNum < count; nodeNum++) { + + const REALTYPE *preOrderPartial = gPartials[operations[nodeNum * numOpsP + 1]]; + const int *tipStates = gTipStates[operations[nodeNum * numOpsP]]; + + const int firstDerivativeIndex = operations[nodeNum * numOpsP + 2]; + const int scalingFactorsIndex = -1; // cumulativeScaleIndices[nodeNum]; + + const int patternOffset = operations[nodeNum * numOpsP + 4] * kPatternCount; + const int threadOffset = operations[nodeNum * numOpsP + 5] * kPatternCount; + + +#ifdef BEAGLE_DEBUG_FLOW + std::cerr<<"Job = " << operations[nodeNum * numOpsP + 4] <::calcEdgeLogDerivatives(const int *postBufferIndices, const int *preBufferIndices, @@ -1983,30 +3326,30 @@ int BeagleCPUImpl::calcEdgeLogDerivatives(const int *postBuf double* outSumSquaredDerivativesForNode = (outSumSquaredDerivatives == NULL) ? NULL : outSumSquaredDerivatives + nodeNum; - resetDerivativeTemporaries(); + resetDerivativeTemporaries(0); if (tipStates != NULL) { calcEdgeLogDerivativesStates(tipStates, preOrderPartial, firstDerivativeIndex, - secondDerivativeIndex, categoryRates, categoryWeights, - outDerivativesForNode, - outSumDerivativesForNode, - outSumSquaredDerivativesForNode); + secondDerivativeIndex, categoryRates, categoryWeights, + outDerivativesForNode, + outSumDerivativesForNode, + outSumSquaredDerivativesForNode, 0); } else { const REALTYPE *postOrderPartial = gPartials[postBufferIndices[nodeNum]]; calcEdgeLogDerivativesPartials(postOrderPartial, preOrderPartial, firstDerivativeIndex, - secondDerivativeIndex, categoryRates, categoryWeights, - scalingFactorsIndex, - outDerivativesForNode, - outSumDerivativesForNode, - outSumSquaredDerivativesForNode); + secondDerivativeIndex, categoryRates, categoryWeights, + scalingFactorsIndex, + outDerivativesForNode, + outSumDerivativesForNode, + outSumSquaredDerivativesForNode, 0); } accumulateDerivatives(outDerivativesForNode, - outSumDerivativesForNode, - outSumSquaredDerivativesForNode); + outSumDerivativesForNode, + outSumSquaredDerivativesForNode, 0); } @@ -2014,16 +3357,16 @@ int BeagleCPUImpl::calcEdgeLogDerivatives(const int *postBuf } BEAGLE_CPU_TEMPLATE template -void BeagleCPUImpl::accumulateDerivativesImpl( - double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void BeagleCPUImpl::accumulateDerivativesImpl(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { REALTYPE sum = 0.0; REALTYPE sumSquared = 0.0; for (int k = 0; k < kPatternCount; k++) { - REALTYPE derivative = grandNumeratorDerivTmp[k] / grandDenominatorDerivTmp[k]; + REALTYPE derivative = grandNumeratorDerivTmp[offset + k] / grandDenominatorDerivTmp[offset + k]; if (DoDerivatives) { outDerivatives[k] = derivative; } @@ -2045,65 +3388,69 @@ void BeagleCPUImpl::accumulateDerivativesImpl( } BEAGLE_CPU_TEMPLATE template -void BeagleCPUImpl::accumulateDerivativesDispatch2( - double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void +BeagleCPUImpl::accumulateDerivativesDispatch2(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { if (outSumSquaredDerivatives == NULL) { accumulateDerivativesImpl( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } else { accumulateDerivativesImpl( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } } BEAGLE_CPU_TEMPLATE template -void BeagleCPUImpl::accumulateDerivativesDispatch1( - double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void +BeagleCPUImpl::accumulateDerivativesDispatch1(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { if (outSumDerivatives == NULL) { accumulateDerivativesDispatch2( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } else { accumulateDerivativesDispatch2( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } } BEAGLE_CPU_TEMPLATE -void BeagleCPUImpl::resetDerivativeTemporaries() { - std::fill(grandNumeratorDerivTmp, grandNumeratorDerivTmp + kPaddedPatternCount, 0); - std::fill(grandDenominatorDerivTmp, grandDenominatorDerivTmp + kPaddedPatternCount, 0); +void BeagleCPUImpl::resetDerivativeTemporaries(int offset) { + std::fill(grandNumeratorDerivTmp + offset, grandNumeratorDerivTmp + offset + kPaddedPatternCount, 0); + std::fill(grandDenominatorDerivTmp + offset, grandDenominatorDerivTmp + offset + kPaddedPatternCount, 0); } BEAGLE_CPU_TEMPLATE -void BeagleCPUImpl::accumulateDerivatives(double* outDerivatives, - double* outSumDerivatives, - double* outSumSquaredDerivatives) { +void BeagleCPUImpl::accumulateDerivatives(double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int offset) { if (outDerivatives == NULL) { accumulateDerivativesDispatch1( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } else { accumulateDerivativesDispatch1( - outDerivatives, outSumDerivatives, outSumSquaredDerivatives); + outDerivatives, outSumDerivatives, outSumSquaredDerivatives, offset); } } BEAGLE_CPU_TEMPLATE -void BeagleCPUImpl::calcEdgeLogDerivativesStates(const int *tipStates, - const REALTYPE *preOrderPartial, - const int firstDerivativeIndex, - const int secondDerivativeIndex, - const double *categoryRates, - const REALTYPE *categoryWeights, - double *outDerivatives, - double *outSumDerivatives, - double *outSumSquaredDerivatives) { +void +BeagleCPUImpl::calcEdgeLogDerivativesStates(const int *tipStates, const REALTYPE *preOrderPartial, + const int firstDerivativeIndex, + const int secondDerivativeIndex, + const double *categoryRates, + const REALTYPE *categoryWeights, + double *outDerivatives, + double *outSumDerivatives, + double *outSumSquaredDerivatives, + int cacheOffset) { const REALTYPE *firstDerivMatrix = gTransitionMatrices[firstDerivativeIndex]; @@ -2124,8 +3471,8 @@ void BeagleCPUImpl::calcEdgeLogDerivativesStates(const int * preOrderPartial[patternIndex * kPartialsPaddedStateCount + k]; } - grandNumeratorDerivTmp[pattern] += categoryWeights[category] * numerator; - grandDenominatorDerivTmp[pattern] += categoryWeights[category] * denominator; + grandNumeratorDerivTmp[cacheOffset + pattern] += categoryWeights[category] * numerator; + grandDenominatorDerivTmp[cacheOffset + pattern] += categoryWeights[category] * denominator; } } } @@ -2256,10 +3603,10 @@ void BeagleCPUImpl::calcEdgeLogDerivativesPartials(const REA const double *categoryRates, const REALTYPE *categoryWeights, const int scalingFactorsIndex, -// const REALTYPE *cumulativeScaleBuffer, double *outDerivatives, double *outSumDerivatives, - double *outSumSquaredDerivatives) { + double *outSumSquaredDerivatives, + int cacheOffset) { const REALTYPE *firstDerivMatrix = gTransitionMatrices[firstDerivativeIndex]; @@ -2290,8 +3637,8 @@ void BeagleCPUImpl::calcEdgeLogDerivativesPartials(const REA denominator += postOrderPartial[v + k] * preOrderPartial[v + k]; } - grandNumeratorDerivTmp[pattern] += weight * numerator; - grandDenominatorDerivTmp[pattern] += weight * denominator; + grandNumeratorDerivTmp[cacheOffset + pattern] += weight * numerator; + grandDenominatorDerivTmp[cacheOffset + pattern] += weight * denominator; } } } @@ -4554,11 +5901,12 @@ void BeagleCPUImpl::calcPrePartialsPartials(REALTYPE* destP, int stateCountModFour = (kStateCount / 4) * 4; REALTYPE* tmpdestPtr = destP; //clean up the partial first, set every entry to 0 - std::fill(tmpdestPtr, tmpdestPtr + kPartialsSize, 0); +// std::fill(tmpdestPtr, tmpdestPtr + kPartialsSize, 0); #pragma omp parallel for num_threads(kCategoryCount) for (int l = 0; l < kCategoryCount; l++) { - int v = l*kPartialsPaddedStateCount*kPatternCount + kPartialsPaddedStateCount*startPattern; + int v = l*kPartialsPaddedStateCount*kPaddedPatternCount + kPartialsPaddedStateCount*startPattern; + std::fill(destP + v, destP + l*kPartialsPaddedStateCount*kPaddedPatternCount + kPartialsPaddedStateCount*endPattern, 0); int matrixOffset = l*kMatrixSize; const REALTYPE* partials1Ptr = &partials1[v]; const REALTYPE* partials2Ptr = &partials2[v]; @@ -4630,11 +5978,12 @@ void BeagleCPUImpl::calcPrePartialsStates(REALTYPE* destP, int stateCountModFour = (kStateCount / 4) * 4; REALTYPE* tmpdestPtr = destP; //clean up the partial first, set every entry to 0 - std::fill(tmpdestPtr, tmpdestPtr + kPartialsSize, 0); +// std::fill(tmpdestPtr, tmpdestPtr + kPartialsSize, 0); #pragma omp parallel for num_threads(kCategoryCount) for (int l = 0; l < kCategoryCount; l++) { - int v = l*kPartialsPaddedStateCount*kPatternCount + kPartialsPaddedStateCount*startPattern; + int v = l*kPartialsPaddedStateCount*kPaddedPatternCount + kPartialsPaddedStateCount*startPattern; + std::fill(destP + v, destP + l*kPartialsPaddedStateCount*kPaddedPatternCount + kPartialsPaddedStateCount*endPattern, 0); int matrixOffset = l*kMatrixSize; const REALTYPE* partials1Ptr = &partials1[v]; @@ -4805,6 +6154,7 @@ void* BeagleCPUImpl::mallocAligned(size_t size) { int res; res = posix_memalign(&ptr, align, size); if (res != 0) { + std::cerr<<"Aligned malloc for "<::createImpl(int tip if (*errorCode == BEAGLE_SUCCESS) { return impl; } + } + catch(const std::exception& e) + { + std::cerr<<"BEAGLE: exception in createInstance: "<. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -115,7 +105,7 @@ class BeagleCPUSSEImpl : public BeagleCPUImpl : public BeagleCPUImpl : public BeagleCPUImpl { @@ -195,7 +185,7 @@ class BeagleCPUSSEImpl : public BeagleCPUImpl : public BeagleCPUImpl. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author David Swofford @@ -302,9 +292,9 @@ void BeagleCPUSSEImpl::calcPartialsPartials(double* __res BEAGLE_CPU_SSE_TEMPLATE void BeagleCPUSSEImpl::calcPartialsPartialsFixedScaling(double* __restrict destP, - const double* __restrict partials1, - const double* __restrict matrices1, - const double* __restrict partials2, + const double* __restrict partials1, + const double* __restrict matrices1, + const double* __restrict partials2, const double* __restrict matrices2, const double* __restrict scaleFactors, int startPattern, @@ -358,7 +348,7 @@ void BeagleCPUSSEImpl::calcPartialsPartialsFixedScaling(d } } - + BEAGLE_CPU_SSE_TEMPLATE void BeagleCPUSSEImpl::calcPartialsPartialsAutoScaling(double* destP, const double* partials_q, @@ -389,7 +379,7 @@ void BeagleCPUSSEImpl::calcPartialsPartialsAutoScaling(do // matrices_r, // activateScaling); //} - + BEAGLE_CPU_SSE_TEMPLATE int BeagleCPUSSEImpl::calcEdgeLogLikelihoods(const int parIndex, const int childIndex, @@ -525,7 +515,7 @@ return BeagleCPUImpl::calcEdgeLogLikelihoods( // for (int i = 0; i < kPatternCount; i++) { // *outSumLogLikelihood += outLogLikelihoodsTmp[i] * gPatternWeights[i]; // } -// +// // if (!(*outSumLogLikelihood - *outSumLogLikelihood == 0.0)) // returnCode = BEAGLE_ERROR_FLOATING_POINT; // @@ -536,7 +526,7 @@ BEAGLE_CPU_SSE_TEMPLATE int BeagleCPUSSEImpl::getPaddedPatternsModulus() { return 1; // We currently do not vectorize across patterns } - + BEAGLE_CPU_SSE_TEMPLATE const char* BeagleCPUSSEImpl::getName() { return getBeagleCPUSSEName(); @@ -546,7 +536,7 @@ BEAGLE_CPU_SSE_TEMPLATE const char* BeagleCPUSSEImpl::getName() { return getBeagleCPUSSEName(); } - + BEAGLE_CPU_SSE_TEMPLATE long long BeagleCPUSSEImpl::getFlags() { return BEAGLE_FLAG_COMPUTATION_SYNCH | @@ -592,46 +582,63 @@ BeagleImpl* BeagleCPUSSEImplFactory::createImpl(int BeagleCPUSSEImpl* impl = new BeagleCPUSSEImpl(); - + try { - if (impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount, + *errorCode = + impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount, patternCount, eigenBufferCount, matrixBufferCount, - categoryCount,scaleBufferCount, resourceNumber, - pluginResourceNumber, - preferenceFlags, requirementFlags) == 0) + categoryCount,scaleBufferCount, resourceNumber, + pluginResourceNumber, + preferenceFlags, requirementFlags); + + if (*errorCode == BEAGLE_SUCCESS) + { return impl; + } + } + catch(const std::exception& e) + { + std::cerr<<"BEAGLE: exception in createInstance: "<* impl = new BeagleCPUSSEImpl(); try { - if (impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount, + *errorCode = + impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount, patternCount, eigenBufferCount, matrixBufferCount, categoryCount,scaleBufferCount, resourceNumber, - pluginResourceNumber, - preferenceFlags, requirementFlags) == 0) + pluginResourceNumber, + preferenceFlags, requirementFlags); + + + if (*errorCode == BEAGLE_SUCCESS) return impl; } + catch(const std::exception& e) + { + std::cerr<<"BEAGLE: exception in createInstance: "< result[3] : "0" (opcode) : "cc"); - return result[3] & 0x04000000; + return (result[3] & 0x04000000) && (result[2] & 0x00080000); #endif // HAVE_CPUID.H } -#else // For Mac OS X GNU C -#if defined(__ARM64_ARCH_8__) +#else +#if defined(__aarch64__) bool check_sse2() { return 1; } #else bool check_sse2(){ @@ -167,7 +174,7 @@ bool check_sse2(){ __asm__("cpuid" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (op)); - return edx & 0x04000000; + return (edx & 0x04000000) && (ecx & 0x00080000); } #endif #endif diff --git a/libhmsbeagle/CPU/CMakeLists.txt b/libhmsbeagle/CPU/CMakeLists.txt index c04c73e89..a64f3b991 100644 --- a/libhmsbeagle/CPU/CMakeLists.txt +++ b/libhmsbeagle/CPU/CMakeLists.txt @@ -25,6 +25,7 @@ SET_TARGET_PROPERTIES(hmsbeagle-cpu SUFFIX "${BEAGLE_PLUGIN_SUFFIX}" ) +if(BUILD_SSE) add_library(hmsbeagle-cpu-sse SHARED BeagleCPU4StateSSEImpl.h BeagleCPU4StateSSEImpl.hpp @@ -56,6 +57,22 @@ SET_TARGET_PROPERTIES(hmsbeagle-cpu-sse SUFFIX "${BEAGLE_PLUGIN_SUFFIX}" ) +# The plugin uses SSE4.1 intrinsics on x86 (on arm64, sse2neon.h provides them), which need -msse4.1 unless +# -march=native already enables them. The plugin checks for SSE4.1 when it is loaded. +include(CheckCXXCompilerFlag) +if(APPLE AND CMAKE_OSX_ARCHITECTURES MATCHES "x86_64" AND CMAKE_OSX_ARCHITECTURES MATCHES "arm64") + # universal build: only the x86_64 slice + target_compile_options(hmsbeagle-cpu-sse PRIVATE "SHELL:-Xarch_x86_64 -msse4.1") +elseif(NOT MSVC) + # (compilers for arm64 reject the flag) + CHECK_CXX_COMPILER_FLAG("-msse4.1" COMPILER_SUPPORTS_SSE41) + if(COMPILER_SUPPORTS_SSE41) + target_compile_options(hmsbeagle-cpu-sse PRIVATE -msse4.1) + endif() +endif() + +endif(BUILD_SSE) + if(BUILD_ACTION) add_library(hmsbeagle-cpu-action SHARED BeagleCPUImpl.h diff --git a/libhmsbeagle/CPU/EigenDecompositionCube.hpp b/libhmsbeagle/CPU/EigenDecompositionCube.hpp index c9647dddc..3782d1e5d 100644 --- a/libhmsbeagle/CPU/EigenDecompositionCube.hpp +++ b/libhmsbeagle/CPU/EigenDecompositionCube.hpp @@ -41,7 +41,10 @@ EigenDecompositionCube::EigenDecompositionCube(int dec size_t mem = ((size_t)kStateCount) * kStateCount * kStateCount; gCMatrices[i] = (REALTYPE*) malloc(sizeof(REALTYPE) * mem); if (gCMatrices[i] == NULL) - throw std::bad_alloc(); + { + std::cerr<<"BEAGLE: EigenDecompositionCube: memory allocation failed for "<. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -33,40 +23,12 @@ #define DLS_USE_SSE2 #if defined(DLS_USE_SSE2) -# if defined(__ARM64_ARCH_8__) +# if defined(__aarch64__) # include "libhmsbeagle/CPU/sse2neon.h" # define _MM_SHUFFLE2(fp1,fp0) (((fp1) << 1) | (fp0)) # define VEC_SHUFFLE0(a,b) _mm_shuffle_pd(a, b, _MM_SHUFFLE2(0,0)) // vreinterpretq_f64_m128d(a) # define VEC_SHUFFLE1(a,b) _mm_shuffle_pd(a, b, _MM_SHUFFLE2(1,1)) // vreinterpretq_f64_m128d(a) -# if __has_builtin(__builtin_shufflevector) -# define _mm_shuffle_pd(a,b,imm) \ - __extension__({ \ - float64x2_t _input1 = vreinterpretq_f64_m128(a); \ - float64x2_t _input2 = vreinterpretq_f64_m128(b); \ - float64x2_t _shuf = __builtin_shufflevector( \ - _input1, _input2, (imm) & (0x1), ((imm) >> 1) & 0x1); \ - vreinterpretq_m128_f32(_shuf); \ - }) -# else -# error "Need to implement NEON translation of _mm_shuffle_pd" -# endif - - static inline __m128 _mm_div_pd(__m128 a, __m128 b) { - return vreinterpretq_m128_f64( - vdivq_f64(vreinterpretq_f64_m128(a), vreinterpretq_f64_m128(b))); - } - - static inline void _mm_store_sd(double* a, __m128 b) { - const auto _b = vreinterpretq_f64_m128(b); - a[0] = _b[0]; - } - static inline __m128 _mm_dp_pd(__m128 lhs, __m128 rhs, const int) { - auto const product = vmulq_f64(vreinterpretq_f64_m128d(lhs), - vreinterpretq_f64_m128d(rhs)); - auto const sum = product[0] + product[1]; // TODO Almost surely an more efficient way - return vreinterpretq_m128d_f64(vdupq_n_f64(sum)); - } # else # if !defined(DLS_MACOS) # include diff --git a/libhmsbeagle/CPU/sse2neon.h b/libhmsbeagle/CPU/sse2neon.h index 4e02e80d7..8d6059738 100644 --- a/libhmsbeagle/CPU/sse2neon.h +++ b/libhmsbeagle/CPU/sse2neon.h @@ -1,13 +1,9 @@ #ifndef SSE2NEON_H #define SSE2NEON_H -// Source: https://github.com/DLTcollab/sse2neon (05-Jan-2021) - // This header file provides a simple API translation layer // between SSE intrinsics to their corresponding Arm/Aarch64 NEON versions // -// This header file does not yet translate all of the SSE intrinsics. -// // Contributors to this work are: // John W. Ratcliff // Brandon Rowlett @@ -15,8 +11,8 @@ // Eric van Beurden // Alexander Potylitsin // Hasindu Gamaarachchi -// Jim Huang -// Mark Cheng +// Jim Huang +// Mark Cheng // Malcolm James MacLeod // Devin Hussey (easyaspi314) // Sebastian Pop @@ -24,7 +20,13 @@ // Danila Kutenin // François Turban (JishinMaster) // Pei-Hsuan Hung -// Yang-Hao Yuan +// Yang-Hao Yuan +// Syoyo Fujita +// Brecht Van Lommel +// Jonathan Hue +// Cuda Chen +// Aymen Qader +// Anthony Roberts /* * sse2neon is freely redistributable under the MIT License. @@ -50,33 +52,160 @@ /* Tunable configurations */ -/* Enable precise implementation of _mm_min_ps and _mm_max_ps +/* Enable precise implementation of math operations * This would slow down the computation a bit, but gives consistent result with - * x86 SSE2. (e.g. would solve a hole or NaN pixel in the rendering result) + * x86 SSE. (e.g. would solve a hole or NaN pixel in the rendering result) */ +/* _mm_min|max_ps|ss|pd|sd */ #ifndef SSE2NEON_PRECISE_MINMAX #define SSE2NEON_PRECISE_MINMAX (0) #endif +/* _mm_rcp_ps and _mm_div_ps */ +#ifndef SSE2NEON_PRECISE_DIV +#define SSE2NEON_PRECISE_DIV (0) +#endif +/* _mm_sqrt_ps and _mm_rsqrt_ps */ +#ifndef SSE2NEON_PRECISE_SQRT +#define SSE2NEON_PRECISE_SQRT (0) +#endif +/* _mm_dp_pd */ +#ifndef SSE2NEON_PRECISE_DP +#define SSE2NEON_PRECISE_DP (0) +#endif + +/* Enable inclusion of windows.h on MSVC platforms + * This makes _mm_clflush functional on windows, as there is no builtin. + */ +#ifndef SSE2NEON_INCLUDE_WINDOWS_H +#define SSE2NEON_INCLUDE_WINDOWS_H (0) +#endif +/* compiler specific definitions */ #if defined(__GNUC__) || defined(__clang__) #pragma push_macro("FORCE_INLINE") #pragma push_macro("ALIGN_STRUCT") #define FORCE_INLINE static inline __attribute__((always_inline)) #define ALIGN_STRUCT(x) __attribute__((aligned(x))) -#else -#error "Macro name collisions may happen with unsupported compiler." -#ifdef FORCE_INLINE -#undef FORCE_INLINE +#define _sse2neon_likely(x) __builtin_expect(!!(x), 1) +#define _sse2neon_unlikely(x) __builtin_expect(!!(x), 0) +#elif defined(_MSC_VER) +#if _MSVC_TRADITIONAL +#error Using the traditional MSVC preprocessor is not supported! Use /Zc:preprocessor instead. #endif +#ifndef FORCE_INLINE #define FORCE_INLINE static inline +#endif #ifndef ALIGN_STRUCT #define ALIGN_STRUCT(x) __declspec(align(x)) #endif +#define _sse2neon_likely(x) (x) +#define _sse2neon_unlikely(x) (x) +#else +#pragma message("Macro name collisions may happen with unsupported compilers.") +#endif + +/* C language does not allow initializing a variable with a function call. */ +#ifdef __cplusplus +#define _sse2neon_const static const +#else +#define _sse2neon_const const #endif #include #include +#if defined(_WIN32) +/* Definitions for _mm_{malloc,free} are provided by + * from both MinGW-w64 and MSVC. + */ +#define SSE2NEON_ALLOC_DEFINED +#endif + +/* If using MSVC */ +#ifdef _MSC_VER +#include +#if SSE2NEON_INCLUDE_WINDOWS_H +#include +#include +#endif + +#if !defined(__cplusplus) +#error sse2neon only supports C++ compilation with this compiler +#endif + +#ifdef SSE2NEON_ALLOC_DEFINED +#include +#endif + +#if (defined(_M_AMD64) || defined(__x86_64__)) || \ + (defined(_M_ARM64) || defined(__arm64__)) +#define SSE2NEON_HAS_BITSCAN64 +#endif +#endif + +#if defined(__GNUC__) || defined(__clang__) +#define _sse2neon_define0(type, s, body) \ + __extension__({ \ + type _a = (s); \ + body \ + }) +#define _sse2neon_define1(type, s, body) \ + __extension__({ \ + type _a = (s); \ + body \ + }) +#define _sse2neon_define2(type, a, b, body) \ + __extension__({ \ + type _a = (a), _b = (b); \ + body \ + }) +#define _sse2neon_return(ret) (ret) +#else +#define _sse2neon_define0(type, a, body) [=](type _a) { body }(a) +#define _sse2neon_define1(type, a, body) [](type _a) { body }(a) +#define _sse2neon_define2(type, a, b, body) \ + [](type _a, type _b) { body }((a), (b)) +#define _sse2neon_return(ret) return ret +#endif + +#define _sse2neon_init(...) \ + { \ + __VA_ARGS__ \ + } + +/* Compiler barrier */ +#if defined(_MSC_VER) +#define SSE2NEON_BARRIER() _ReadWriteBarrier() +#else +#define SSE2NEON_BARRIER() \ + do { \ + __asm__ __volatile__("" ::: "memory"); \ + (void) 0; \ + } while (0) +#endif + +/* Memory barriers + * __atomic_thread_fence does not include a compiler barrier; instead, + * the barrier is part of __atomic_load/__atomic_store's "volatile-like" + * semantics. + */ +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) +#include +#endif + +FORCE_INLINE void _sse2neon_smp_mb(void) +{ + SSE2NEON_BARRIER(); +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(__STDC_NO_ATOMICS__) + atomic_thread_fence(memory_order_seq_cst); +#elif defined(__GNUC__) || defined(__clang__) + __atomic_thread_fence(__ATOMIC_SEQ_CST); +#else /* MSVC */ + __dmb(_ARM64_BARRIER_ISH); +#endif +} + /* Architecture-specific build options */ /* FIXME: #pragma GCC push_options is only available on GCC */ #if defined(__GNUC__) @@ -88,32 +217,79 @@ #if !defined(__ARM_NEON) || !defined(__ARM_NEON__) #error "You must enable NEON instructions (e.g. -mfpu=neon) to use SSE2NEON." #endif +#if !defined(__clang__) #pragma GCC push_options #pragma GCC target("fpu=neon") -#elif defined(__aarch64__) +#endif +#elif defined(__aarch64__) || defined(_M_ARM64) +#if !defined(__clang__) && !defined(_MSC_VER) #pragma GCC push_options #pragma GCC target("+simd") +#endif +#elif __ARM_ARCH == 8 +#if !defined(__ARM_NEON) || !defined(__ARM_NEON__) +#error \ + "You must enable NEON instructions (e.g. -mfpu=neon-fp-armv8) to use SSE2NEON." +#endif +#if !defined(__clang__) && !defined(_MSC_VER) +#pragma GCC push_options +#endif #else #error "Unsupported target. Must be either ARMv7-A+NEON or ARMv8-A." #endif #endif #include +#if (!defined(__aarch64__) && !defined(_M_ARM64)) && (__ARM_ARCH == 8) +#if defined __has_include && __has_include() +#include +#endif +#endif + +/* Apple Silicon cache lines are double of what is commonly used by Intel, AMD + * and other Arm microarchitectures use. + * From sysctl -a on Apple M1: + * hw.cachelinesize: 128 + */ +#if defined(__APPLE__) && (defined(__aarch64__) || defined(__arm64__)) +#define SSE2NEON_CACHELINE_SIZE 128 +#else +#define SSE2NEON_CACHELINE_SIZE 64 +#endif -/* Rounding functions require either Aarch64 instructions or libm failback */ -#if !defined(__aarch64__) +/* Rounding functions require either Aarch64 instructions or libm fallback */ +#if !defined(__aarch64__) && !defined(_M_ARM64) #include #endif +/* On ARMv7, some registers, such as PMUSERENR and PMCCNTR, are read-only + * or even not accessible in user mode. + * To write or access to these registers in user mode, + * we have to perform syscall instead. + */ +#if (!defined(__aarch64__) && !defined(_M_ARM64)) +#include +#endif + /* "__has_builtin" can be used to query support for built-in functions * provided by gcc/clang and other compilers that support it. */ #ifndef __has_builtin /* GCC prior to 10 or non-clang compilers */ /* Compatibility with gcc <= 9 */ -#if __GNUC__ <= 9 +#if defined(__GNUC__) && (__GNUC__ <= 9) #define __has_builtin(x) HAS##x #define HAS__builtin_popcount 1 #define HAS__builtin_popcountll 1 + +// __builtin_shuffle introduced in GCC 4.7.0 +#if (__GNUC__ >= 5) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) +#define HAS__builtin_shuffle 1 +#else +#define HAS__builtin_shuffle 0 +#endif + +#define HAS__builtin_shufflevector 0 +#define HAS__builtin_nontemporal_store 0 #else #define __has_builtin(x) 0 #endif @@ -130,6 +306,26 @@ #define _MM_SHUFFLE(fp3, fp2, fp1, fp0) \ (((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | ((fp0))) +#if __has_builtin(__builtin_shufflevector) +#define _sse2neon_shuffle(type, a, b, ...) \ + __builtin_shufflevector(a, b, __VA_ARGS__) +#elif __has_builtin(__builtin_shuffle) +#define _sse2neon_shuffle(type, a, b, ...) \ + __extension__({ \ + type tmp = {__VA_ARGS__}; \ + __builtin_shuffle(a, b, tmp); \ + }) +#endif + +#ifdef _sse2neon_shuffle +#define vshuffle_s16(a, b, ...) _sse2neon_shuffle(int16x4_t, a, b, __VA_ARGS__) +#define vshuffleq_s16(a, b, ...) _sse2neon_shuffle(int16x8_t, a, b, __VA_ARGS__) +#define vshuffle_s32(a, b, ...) _sse2neon_shuffle(int32x2_t, a, b, __VA_ARGS__) +#define vshuffleq_s32(a, b, ...) _sse2neon_shuffle(int32x4_t, a, b, __VA_ARGS__) +#define vshuffle_s64(a, b, ...) _sse2neon_shuffle(int64x1_t, a, b, __VA_ARGS__) +#define vshuffleq_s64(a, b, ...) _sse2neon_shuffle(int64x2_t, a, b, __VA_ARGS__) +#endif + /* Rounding mode macros. */ #define _MM_FROUND_TO_NEAREST_INT 0x00 #define _MM_FROUND_TO_NEG_INF 0x01 @@ -137,6 +333,25 @@ #define _MM_FROUND_TO_ZERO 0x03 #define _MM_FROUND_CUR_DIRECTION 0x04 #define _MM_FROUND_NO_EXC 0x08 +#define _MM_FROUND_RAISE_EXC 0x00 +#define _MM_FROUND_NINT (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_RAISE_EXC) +#define _MM_FROUND_FLOOR (_MM_FROUND_TO_NEG_INF | _MM_FROUND_RAISE_EXC) +#define _MM_FROUND_CEIL (_MM_FROUND_TO_POS_INF | _MM_FROUND_RAISE_EXC) +#define _MM_FROUND_TRUNC (_MM_FROUND_TO_ZERO | _MM_FROUND_RAISE_EXC) +#define _MM_FROUND_RINT (_MM_FROUND_CUR_DIRECTION | _MM_FROUND_RAISE_EXC) +#define _MM_FROUND_NEARBYINT (_MM_FROUND_CUR_DIRECTION | _MM_FROUND_NO_EXC) +#define _MM_ROUND_NEAREST 0x0000 +#define _MM_ROUND_DOWN 0x2000 +#define _MM_ROUND_UP 0x4000 +#define _MM_ROUND_TOWARD_ZERO 0x6000 +/* Flush zero mode macros. */ +#define _MM_FLUSH_ZERO_MASK 0x8000 +#define _MM_FLUSH_ZERO_ON 0x8000 +#define _MM_FLUSH_ZERO_OFF 0x0000 +/* Denormals are zeros mode macros. */ +#define _MM_DENORMALS_ZERO_MASK 0x0040 +#define _MM_DENORMALS_ZERO_ON 0x0040 +#define _MM_DENORMALS_ZERO_OFF 0x0000 /* indicate immediate constant argument in a given range */ #define __constrange(a, b) const @@ -152,13 +367,23 @@ typedef float32x4_t __m128; /* 128-bit vector containing 4 floats */ // On ARM 32-bit architecture, the float64x2_t is not supported. // The data type __m128d should be represented in a different way for related // intrinsic conversion. -#if defined(__aarch64__) +#if defined(__aarch64__) || defined(_M_ARM64) typedef float64x2_t __m128d; /* 128-bit vector containing 2 doubles */ #else typedef float32x4_t __m128d; #endif typedef int64x2_t __m128i; /* 128-bit vector containing integers */ +// __int64 is defined in the Intrinsics Guide which maps to different datatype +// in different data model +#if !(defined(_WIN32) || defined(_WIN64) || defined(__int64)) +#if (defined(__x86_64__) || defined(__i386__)) +#define __int64 long long +#else +#define __int64 int64_t +#endif +#endif + /* type-safe casting between types */ #define vreinterpretq_m128_f16(x) vreinterpretq_f32_f16(x) @@ -199,6 +424,9 @@ typedef int64x2_t __m128i; /* 128-bit vector containing integers */ #define vreinterpretq_m128i_u32(x) vreinterpretq_s64_u32(x) #define vreinterpretq_m128i_u64(x) vreinterpretq_s64_u64(x) +#define vreinterpretq_f32_m128i(x) vreinterpretq_f32_s64(x) +#define vreinterpretq_f64_m128i(x) vreinterpretq_f64_s64(x) + #define vreinterpretq_s8_m128i(x) vreinterpretq_s8_s64(x) #define vreinterpretq_s16_m128i(x) vreinterpretq_s16_s64(x) #define vreinterpretq_s32_m128i(x) vreinterpretq_s32_s64(x) @@ -235,36 +463,44 @@ typedef int64x2_t __m128i; /* 128-bit vector containing integers */ #define vreinterpret_f32_m64(x) vreinterpret_f32_s64(x) -#if defined(__aarch64__) +#if defined(__aarch64__) || defined(_M_ARM64) #define vreinterpretq_m128d_s32(x) vreinterpretq_f64_s32(x) #define vreinterpretq_m128d_s64(x) vreinterpretq_f64_s64(x) +#define vreinterpretq_m128d_u64(x) vreinterpretq_f64_u64(x) + #define vreinterpretq_m128d_f32(x) vreinterpretq_f64_f32(x) #define vreinterpretq_m128d_f64(x) (x) #define vreinterpretq_s64_m128d(x) vreinterpretq_s64_f64(x) +#define vreinterpretq_u32_m128d(x) vreinterpretq_u32_f64(x) +#define vreinterpretq_u64_m128d(x) vreinterpretq_u64_f64(x) + #define vreinterpretq_f64_m128d(x) (x) #define vreinterpretq_f32_m128d(x) vreinterpretq_f32_f64(x) #else #define vreinterpretq_m128d_s32(x) vreinterpretq_f32_s32(x) #define vreinterpretq_m128d_s64(x) vreinterpretq_f32_s64(x) + +#define vreinterpretq_m128d_u32(x) vreinterpretq_f32_u32(x) #define vreinterpretq_m128d_u64(x) vreinterpretq_f32_u64(x) #define vreinterpretq_m128d_f32(x) (x) #define vreinterpretq_s64_m128d(x) vreinterpretq_s64_f32(x) +#define vreinterpretq_u32_m128d(x) vreinterpretq_u32_f32(x) #define vreinterpretq_u64_m128d(x) vreinterpretq_u64_f32(x) #define vreinterpretq_f32_m128d(x) (x) #endif // A struct is defined in this header file called 'SIMDVec' which can be used -// by applications which attempt to access the contents of an _m128 struct +// by applications which attempt to access the contents of an __m128 struct // directly. It is important to note that accessing the __m128 struct directly // is bad coding practice by Microsoft: @see: -// https://msdn.microsoft.com/en-us/library/ayeb3ayc.aspx +// https://learn.microsoft.com/en-us/cpp/cpp/m128 // // However, some legacy source code may try to access the contents of an __m128 // struct directly so the developer can use the SIMDVec as an alias for it. Any @@ -300,12 +536,49 @@ typedef union ALIGN_STRUCT(16) SIMDVec { #define vreinterpretq_nth_u32_m128i(x, n) (((SIMDVec *) &x)->m128_u32[n]) #define vreinterpretq_nth_u8_m128i(x, n) (((SIMDVec *) &x)->m128_u8[n]) +/* SSE macros */ +#define _MM_GET_FLUSH_ZERO_MODE _sse2neon_mm_get_flush_zero_mode +#define _MM_SET_FLUSH_ZERO_MODE _sse2neon_mm_set_flush_zero_mode +#define _MM_GET_DENORMALS_ZERO_MODE _sse2neon_mm_get_denormals_zero_mode +#define _MM_SET_DENORMALS_ZERO_MODE _sse2neon_mm_set_denormals_zero_mode + +// Function declaration +// SSE +FORCE_INLINE unsigned int _MM_GET_ROUNDING_MODE(void); +FORCE_INLINE __m128 _mm_move_ss(__m128, __m128); +FORCE_INLINE __m128 _mm_or_ps(__m128, __m128); +FORCE_INLINE __m128 _mm_set_ps1(float); +FORCE_INLINE __m128 _mm_setzero_ps(void); +// SSE2 +FORCE_INLINE __m128i _mm_and_si128(__m128i, __m128i); +FORCE_INLINE __m128i _mm_castps_si128(__m128); +FORCE_INLINE __m128i _mm_cmpeq_epi32(__m128i, __m128i); +FORCE_INLINE __m128i _mm_cvtps_epi32(__m128); +FORCE_INLINE __m128d _mm_move_sd(__m128d, __m128d); +FORCE_INLINE __m128i _mm_or_si128(__m128i, __m128i); +FORCE_INLINE __m128i _mm_set_epi32(int, int, int, int); +FORCE_INLINE __m128i _mm_set_epi64x(int64_t, int64_t); +FORCE_INLINE __m128d _mm_set_pd(double, double); +FORCE_INLINE __m128i _mm_set1_epi32(int); +FORCE_INLINE __m128i _mm_setzero_si128(void); +// SSE4.1 +FORCE_INLINE __m128d _mm_ceil_pd(__m128d); +FORCE_INLINE __m128 _mm_ceil_ps(__m128); +FORCE_INLINE __m128d _mm_floor_pd(__m128d); +FORCE_INLINE __m128 _mm_floor_ps(__m128); +FORCE_INLINE __m128d _mm_round_pd(__m128d, int); +FORCE_INLINE __m128 _mm_round_ps(__m128, int); +// SSE4.2 +FORCE_INLINE uint32_t _mm_crc32_u8(uint32_t, uint8_t); + /* Backwards compatibility for compilers with lack of specific type support */ // Older gcc does not define vld1q_u8_x4 type -#if defined(__GNUC__) && !defined(__clang__) -#if __GNUC__ <= 9 -FORCE_INLINE uint8x16x4_t vld1q_u8_x4(const uint8_t *p) +#if defined(__GNUC__) && !defined(__clang__) && \ + ((__GNUC__ <= 13 && defined(__arm__)) || \ + (__GNUC__ == 10 && __GNUC_MINOR__ < 3 && defined(__aarch64__)) || \ + (__GNUC__ <= 9 && defined(__aarch64__))) +FORCE_INLINE uint8x16x4_t _sse2neon_vld1q_u8_x4(const uint8_t *p) { uint8x16x4_t ret; ret.val[0] = vld1q_u8(p + 0); @@ -314,7 +587,63 @@ FORCE_INLINE uint8x16x4_t vld1q_u8_x4(const uint8_t *p) ret.val[3] = vld1q_u8(p + 48); return ret; } +#else +// Wraps vld1q_u8_x4 +FORCE_INLINE uint8x16x4_t _sse2neon_vld1q_u8_x4(const uint8_t *p) +{ + return vld1q_u8_x4(p); +} +#endif + +#if !defined(__aarch64__) && !defined(_M_ARM64) +/* emulate vaddv u8 variant */ +FORCE_INLINE uint8_t _sse2neon_vaddv_u8(uint8x8_t v8) +{ + const uint64x1_t v1 = vpaddl_u32(vpaddl_u16(vpaddl_u8(v8))); + return vget_lane_u8(vreinterpret_u8_u64(v1), 0); +} +#else +// Wraps vaddv_u8 +FORCE_INLINE uint8_t _sse2neon_vaddv_u8(uint8x8_t v8) +{ + return vaddv_u8(v8); +} +#endif + +#if !defined(__aarch64__) && !defined(_M_ARM64) +/* emulate vaddvq u8 variant */ +FORCE_INLINE uint8_t _sse2neon_vaddvq_u8(uint8x16_t a) +{ + uint8x8_t tmp = vpadd_u8(vget_low_u8(a), vget_high_u8(a)); + uint8_t res = 0; + for (int i = 0; i < 8; ++i) + res += tmp[i]; + return res; +} +#else +// Wraps vaddvq_u8 +FORCE_INLINE uint8_t _sse2neon_vaddvq_u8(uint8x16_t a) +{ + return vaddvq_u8(a); +} #endif + +#if !defined(__aarch64__) && !defined(_M_ARM64) +/* emulate vaddvq u16 variant */ +FORCE_INLINE uint16_t _sse2neon_vaddvq_u16(uint16x8_t a) +{ + uint32x4_t m = vpaddlq_u16(a); + uint64x2_t n = vpaddlq_u32(m); + uint64x1_t o = vget_low_u64(n) + vget_high_u64(n); + + return vget_lane_u32((uint32x2_t) o, 0); +} +#else +// Wraps vaddvq_u16 +FORCE_INLINE uint16_t _sse2neon_vaddvq_u16(uint16x8_t a) +{ + return vaddvq_u16(a); +} #endif /* Function Naming Conventions @@ -329,7 +658,7 @@ FORCE_INLINE uint8x16x4_t vld1q_u8_x4(const uint8_t *p) * This last part, , is a little complicated. It identifies the * content of the input values, and can be set to any of the following values: * + ps - vectors contain floats (ps stands for packed single-precision) - * + pd - vectors cantain doubles (pd stands for packed double-precision) + * + pd - vectors contain doubles (pd stands for packed double-precision) * + epi8/epi16/epi32/epi64 - vectors contain 8-bit/16-bit/32-bit/64-bit * signed integers * + epu8/epu16/epu32/epu64 - vectors contain 8-bit/16-bit/32-bit/64-bit @@ -351,2653 +680,2271 @@ FORCE_INLINE uint8x16x4_t vld1q_u8_x4(const uint8_t *p) * 4, 5, 12, 13, 6, 7, 14, 15); * // Shuffle packed 8-bit integers * __m128i v_out = _mm_shuffle_epi8(v_in, v_perm); // pshufb - * - * Data (Number, Binary, Byte Index): - +------+------+-------------+------+------+-------------+ - | 1 | 2 | 3 | 4 | Number - +------+------+------+------+------+------+------+------+ - | 0000 | 0001 | 0000 | 0010 | 0000 | 0011 | 0000 | 0100 | Binary - +------+------+------+------+------+------+------+------+ - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | Index - +------+------+------+------+------+------+------+------+ - - +------+------+------+------+------+------+------+------+ - | 5 | 6 | 7 | 8 | Number - +------+------+------+------+------+------+------+------+ - | 0000 | 0101 | 0000 | 0110 | 0000 | 0111 | 0000 | 1000 | Binary - +------+------+------+------+------+------+------+------+ - | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Index - +------+------+------+------+------+------+------+------+ - * Index (Byte Index): - +------+------+------+------+------+------+------+------+ - | 1 | 0 | 2 | 3 | 8 | 9 | 10 | 11 | - +------+------+------+------+------+------+------+------+ - - +------+------+------+------+------+------+------+------+ - | 4 | 5 | 12 | 13 | 6 | 7 | 14 | 15 | - +------+------+------+------+------+------+------+------+ - * Result: - +------+------+------+------+------+------+------+------+ - | 1 | 0 | 2 | 3 | 8 | 9 | 10 | 11 | Index - +------+------+------+------+------+------+------+------+ - | 0001 | 0000 | 0000 | 0010 | 0000 | 0101 | 0000 | 0110 | Binary - +------+------+------+------+------+------+------+------+ - | 256 | 2 | 5 | 6 | Number - +------+------+------+------+------+------+------+------+ - - +------+------+------+------+------+------+------+------+ - | 4 | 5 | 12 | 13 | 6 | 7 | 14 | 15 | Index - +------+------+------+------+------+------+------+------+ - | 0000 | 0011 | 0000 | 0111 | 0000 | 0100 | 0000 | 1000 | Binary - +------+------+------+------+------+------+------+------+ - | 3 | 7 | 4 | 8 | Number - +------+------+------+------+------+------+-------------+ */ -/* Set/get methods */ - -/* Constants for use with _mm_prefetch. */ +/* Constants for use with _mm_prefetch. */ enum _mm_hint { - _MM_HINT_NTA = 0, /* load data to L1 and L2 cache, mark it as NTA */ - _MM_HINT_T0 = 1, /* load data to L1 and L2 cache */ - _MM_HINT_T1 = 2, /* load data to L2 cache only */ - _MM_HINT_T2 = 3, /* load data to L2 cache only, mark it as NTA */ - _MM_HINT_ENTA = 4, /* exclusive version of _MM_HINT_NTA */ - _MM_HINT_ET0 = 5, /* exclusive version of _MM_HINT_T0 */ - _MM_HINT_ET1 = 6, /* exclusive version of _MM_HINT_T1 */ - _MM_HINT_ET2 = 7 /* exclusive version of _MM_HINT_T2 */ + _MM_HINT_NTA = 0, /* load data to L1 and L2 cache, mark it as NTA */ + _MM_HINT_T0 = 1, /* load data to L1 and L2 cache */ + _MM_HINT_T1 = 2, /* load data to L2 cache only */ + _MM_HINT_T2 = 3, /* load data to L2 cache only, mark it as NTA */ }; -// Loads one cache line of data from address p to a location closer to the -// processor. https://msdn.microsoft.com/en-us/library/84szxsww(v=vs.100).aspx -FORCE_INLINE void _mm_prefetch(const void *p, int i) +// The bit field mapping to the FPCR(floating-point control register) +typedef struct { + uint16_t res0; + uint8_t res1 : 6; + uint8_t bit22 : 1; + uint8_t bit23 : 1; + uint8_t bit24 : 1; + uint8_t res2 : 7; +#if defined(__aarch64__) || defined(_M_ARM64) + uint32_t res3; +#endif +} fpcr_bitfield; + +// Takes the upper 64 bits of a and places it in the low end of the result +// Takes the lower 64 bits of b and places it into the high end of the result. +FORCE_INLINE __m128 _mm_shuffle_ps_1032(__m128 a, __m128 b) { - (void) i; - __builtin_prefetch(p); + float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); + float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_f32(vcombine_f32(a32, b10)); } -// Copy the lower single-precision (32-bit) floating-point element of a to dst. -// -// dst[31:0] := a[31:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtss_f32 -FORCE_INLINE float _mm_cvtss_f32(__m128 a) +// takes the lower two 32-bit values from a and swaps them and places in high +// end of result takes the higher two 32 bit values from b and swaps them and +// places in low end of result. +FORCE_INLINE __m128 _mm_shuffle_ps_2301(__m128 a, __m128 b) { - return vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); + float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); + float32x2_t b23 = vrev64_f32(vget_high_f32(vreinterpretq_f32_m128(b))); + return vreinterpretq_m128_f32(vcombine_f32(a01, b23)); } -// Convert the lower single-precision (32-bit) floating-point element in a to a -// 32-bit integer, and store the result in dst. -// -// dst[31:0] := Convert_FP32_To_Int32(a[31:0]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtss_si32 -#define _mm_cvtss_si32(a) _mm_cvt_ss2si(a) - -// Convert the lower single-precision (32-bit) floating-point element in a to a -// 64-bit integer, and store the result in dst. -// -// dst[63:0] := Convert_FP32_To_Int64(a[31:0]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtss_si64 -FORCE_INLINE int _mm_cvtss_si64(__m128 a) +FORCE_INLINE __m128 _mm_shuffle_ps_0321(__m128 a, __m128 b) { -#if defined(__aarch64__) - return vgetq_lane_s64( - vreinterpretq_s64_s32(vcvtnq_s32_f32(vreinterpretq_f32_m128(a))), 0); -#else - float32_t data = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); - float32_t diff = data - floor(data); - if (diff > 0.5) - return (int64_t) ceil(data); - if (diff == 0.5) { - int64_t f = (int64_t) floor(data); - int64_t c = (int64_t) ceil(data); - return c & 1 ? f : c; - } - return (int64_t) floor(data); -#endif + float32x2_t a21 = vget_high_f32( + vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); + float32x2_t b03 = vget_low_f32( + vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); + return vreinterpretq_m128_f32(vcombine_f32(a21, b03)); } -// Convert packed single-precision (32-bit) floating-point elements in a to -// packed 32-bit integers with truncation, and store the results in dst. -// -// FOR j := 0 to 1 -// i := 32*j -// dst[i+31:i] := Convert_FP32_To_Int32_Truncate(a[i+31:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtt_ps2pi -FORCE_INLINE __m64 _mm_cvtt_ps2pi(__m128 a) +FORCE_INLINE __m128 _mm_shuffle_ps_2103(__m128 a, __m128 b) { - return vreinterpret_m64_s32( - vget_low_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a)))); + float32x2_t a03 = vget_low_f32( + vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); + float32x2_t b21 = vget_high_f32( + vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); + return vreinterpretq_m128_f32(vcombine_f32(a03, b21)); } -// Convert the lower single-precision (32-bit) floating-point element in a to a -// 32-bit integer with truncation, and store the result in dst. -// -// dst[31:0] := Convert_FP32_To_Int32_Truncate(a[31:0]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtt_ss2si -FORCE_INLINE int _mm_cvtt_ss2si(__m128 a) +FORCE_INLINE __m128 _mm_shuffle_ps_1010(__m128 a, __m128 b) { - return vgetq_lane_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a)), 0); + float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); + float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); } -// Convert packed single-precision (32-bit) floating-point elements in a to -// packed 32-bit integers with truncation, and store the results in dst. -// -// FOR j := 0 to 1 -// i := 32*j -// dst[i+31:i] := Convert_FP32_To_Int32_Truncate(a[i+31:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvttps_pi32 -#define _mm_cvttps_pi32(a) _mm_cvtt_ps2pi(a) - -// Convert the lower single-precision (32-bit) floating-point element in a to a -// 32-bit integer with truncation, and store the result in dst. -// -// dst[31:0] := Convert_FP32_To_Int32_Truncate(a[31:0]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvttss_si32 -#define _mm_cvttss_si32(a) _mm_cvtt_ss2si(a) - -// Convert the lower single-precision (32-bit) floating-point element in a to a -// 64-bit integer with truncation, and store the result in dst. -// -// dst[63:0] := Convert_FP32_To_Int64_Truncate(a[31:0]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvttss_si64 -FORCE_INLINE int64_t _mm_cvttss_si64(__m128 a) +FORCE_INLINE __m128 _mm_shuffle_ps_1001(__m128 a, __m128 b) { - return vgetq_lane_s64( - vmovl_s32(vget_low_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a)))), 0); + float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); + float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_f32(vcombine_f32(a01, b10)); } -// Sets the 128-bit value to zero -// https://msdn.microsoft.com/en-us/library/vstudio/ys7dw0kh(v=vs.100).aspx -FORCE_INLINE __m128i _mm_setzero_si128(void) +FORCE_INLINE __m128 _mm_shuffle_ps_0101(__m128 a, __m128 b) { - return vreinterpretq_m128i_s32(vdupq_n_s32(0)); + float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); + float32x2_t b01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(b))); + return vreinterpretq_m128_f32(vcombine_f32(a01, b01)); } -// Clears the four single-precision, floating-point values. -// https://msdn.microsoft.com/en-us/library/vstudio/tk1t2tbz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_setzero_ps(void) +// keeps the low 64 bits of b in the low and puts the high 64 bits of a in the +// high +FORCE_INLINE __m128 _mm_shuffle_ps_3210(__m128 a, __m128 b) { - return vreinterpretq_m128_f32(vdupq_n_f32(0)); + float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); + float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_f32(vcombine_f32(a10, b32)); } -// Return vector of type __m128d with all elements set to zero. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_setzero_pd -FORCE_INLINE __m128d _mm_setzero_pd(void) +FORCE_INLINE __m128 _mm_shuffle_ps_0011(__m128 a, __m128 b) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64(vdupq_n_f64(0)); -#else - return vreinterpretq_m128d_f32(vdupq_n_f32(0)); -#endif + float32x2_t a11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 1); + float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); + return vreinterpretq_m128_f32(vcombine_f32(a11, b00)); } -// Sets the four single-precision, floating-point values to w. -// -// r0 := r1 := r2 := r3 := w -// -// https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set1_ps(float _w) +FORCE_INLINE __m128 _mm_shuffle_ps_0022(__m128 a, __m128 b) { - return vreinterpretq_m128_f32(vdupq_n_f32(_w)); + float32x2_t a22 = + vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); + float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); + return vreinterpretq_m128_f32(vcombine_f32(a22, b00)); } -// Sets the four single-precision, floating-point values to w. -// https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set_ps1(float _w) +FORCE_INLINE __m128 _mm_shuffle_ps_2200(__m128 a, __m128 b) { - return vreinterpretq_m128_f32(vdupq_n_f32(_w)); + float32x2_t a00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 0); + float32x2_t b22 = + vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(b)), 0); + return vreinterpretq_m128_f32(vcombine_f32(a00, b22)); } -// Sets the four single-precision, floating-point values to the four inputs. -// https://msdn.microsoft.com/en-us/library/vstudio/afh0zf75(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set_ps(float w, float z, float y, float x) +FORCE_INLINE __m128 _mm_shuffle_ps_3202(__m128 a, __m128 b) { - float ALIGN_STRUCT(16) data[4] = {x, y, z, w}; - return vreinterpretq_m128_f32(vld1q_f32(data)); + float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); + float32x2_t a22 = + vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); + float32x2_t a02 = vset_lane_f32(a0, a22, 1); /* TODO: use vzip ?*/ + float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_f32(vcombine_f32(a02, b32)); } -// Copy single-precision (32-bit) floating-point element a to the lower element -// of dst, and zero the upper 3 elements. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_set_ss -FORCE_INLINE __m128 _mm_set_ss(float a) +FORCE_INLINE __m128 _mm_shuffle_ps_1133(__m128 a, __m128 b) { - float ALIGN_STRUCT(16) data[4] = {a, 0, 0, 0}; - return vreinterpretq_m128_f32(vld1q_f32(data)); + float32x2_t a33 = + vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 1); + float32x2_t b11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 1); + return vreinterpretq_m128_f32(vcombine_f32(a33, b11)); } -// Sets the four single-precision, floating-point values to the four inputs in -// reverse order. -// https://msdn.microsoft.com/en-us/library/vstudio/d2172ct3(v=vs.100).aspx -FORCE_INLINE __m128 _mm_setr_ps(float w, float z, float y, float x) +FORCE_INLINE __m128 _mm_shuffle_ps_2010(__m128 a, __m128 b) { - float ALIGN_STRUCT(16) data[4] = {w, z, y, x}; - return vreinterpretq_m128_f32(vld1q_f32(data)); + float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); + float32_t b2 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 2); + float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); + float32x2_t b20 = vset_lane_f32(b2, b00, 1); + return vreinterpretq_m128_f32(vcombine_f32(a10, b20)); } -// Sets the 8 signed 16-bit integer values in reverse order. -// -// Return Value -// r0 := w0 -// r1 := w1 -// ... -// r7 := w7 -FORCE_INLINE __m128i _mm_setr_epi16(short w0, - short w1, - short w2, - short w3, - short w4, - short w5, - short w6, - short w7) +FORCE_INLINE __m128 _mm_shuffle_ps_2001(__m128 a, __m128 b) { - int16_t ALIGN_STRUCT(16) data[8] = {w0, w1, w2, w3, w4, w5, w6, w7}; - return vreinterpretq_m128i_s16(vld1q_s16((int16_t *) data)); + float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); + float32_t b2 = vgetq_lane_f32(b, 2); + float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); + float32x2_t b20 = vset_lane_f32(b2, b00, 1); + return vreinterpretq_m128_f32(vcombine_f32(a01, b20)); } -// Sets the 4 signed 32-bit integer values in reverse order -// https://technet.microsoft.com/en-us/library/security/27yb3ee5(v=vs.90).aspx -FORCE_INLINE __m128i _mm_setr_epi32(int i3, int i2, int i1, int i0) +FORCE_INLINE __m128 _mm_shuffle_ps_2032(__m128 a, __m128 b) { - int32_t ALIGN_STRUCT(16) data[4] = {i3, i2, i1, i0}; - return vreinterpretq_m128i_s32(vld1q_s32(data)); + float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); + float32_t b2 = vgetq_lane_f32(b, 2); + float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); + float32x2_t b20 = vset_lane_f32(b2, b00, 1); + return vreinterpretq_m128_f32(vcombine_f32(a32, b20)); } -// Set packed 64-bit integers in dst with the supplied values in reverse order. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_setr_epi64 -FORCE_INLINE __m128i _mm_setr_epi64(__m64 e1, __m64 e0) +// For MSVC, we check only if it is ARM64, as every single ARM64 processor +// supported by WoA has crypto extensions. If this changes in the future, +// this can be verified via the runtime-only method of: +// IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE) +#if (defined(_M_ARM64) && !defined(__clang__)) || \ + (defined(__ARM_FEATURE_CRYPTO) && \ + (defined(__aarch64__) || __has_builtin(__builtin_arm_crypto_vmullp64))) +// Wraps vmull_p64 +FORCE_INLINE uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b) { - return vreinterpretq_m128i_s64(vcombine_s64(e1, e0)); + poly64_t a = vget_lane_p64(vreinterpret_p64_u64(_a), 0); + poly64_t b = vget_lane_p64(vreinterpret_p64_u64(_b), 0); +#if defined(_MSC_VER) + __n64 a1 = {a}, b1 = {b}; + return vreinterpretq_u64_p128(vmull_p64(a1, b1)); +#else + return vreinterpretq_u64_p128(vmull_p64(a, b)); +#endif } - -// Sets the 16 signed 8-bit integer values to b. +#else // ARMv7 polyfill +// ARMv7/some A64 lacks vmull_p64, but it has vmull_p8. // -// r0 := b -// r1 := b -// ... -// r15 := b +// vmull_p8 calculates 8 8-bit->16-bit polynomial multiplies, but we need a +// 64-bit->128-bit polynomial multiply. // -// https://msdn.microsoft.com/en-us/library/6e14xhyf(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set1_epi8(signed char w) +// It needs some work and is somewhat slow, but it is still faster than all +// known scalar methods. +// +// Algorithm adapted to C from +// https://www.workofard.com/2017/07/ghash-for-low-end-cores/, which is adapted +// from "Fast Software Polynomial Multiplication on ARM Processors Using the +// NEON Engine" by Danilo Camara, Conrado Gouvea, Julio Lopez and Ricardo Dahab +// (https://hal.inria.fr/hal-01506572) +static uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b) { - return vreinterpretq_m128i_s8(vdupq_n_s8(w)); -} + poly8x8_t a = vreinterpret_p8_u64(_a); + poly8x8_t b = vreinterpret_p8_u64(_b); -// Broadcast double-precision (64-bit) floating-point value a to all elements of -// dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_set1_pd -FORCE_INLINE __m128d _mm_set1_pd(double d) -{ + // Masks + uint8x16_t k48_32 = vcombine_u8(vcreate_u8(0x0000ffffffffffff), + vcreate_u8(0x00000000ffffffff)); + uint8x16_t k16_00 = vcombine_u8(vcreate_u8(0x000000000000ffff), + vcreate_u8(0x0000000000000000)); + + // Do the multiplies, rotating with vext to get all combinations + uint8x16_t d = vreinterpretq_u8_p16(vmull_p8(a, b)); // D = A0 * B0 + uint8x16_t e = + vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 1))); // E = A0 * B1 + uint8x16_t f = + vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 1), b)); // F = A1 * B0 + uint8x16_t g = + vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 2))); // G = A0 * B2 + uint8x16_t h = + vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 2), b)); // H = A2 * B0 + uint8x16_t i = + vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 3))); // I = A0 * B3 + uint8x16_t j = + vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 3), b)); // J = A3 * B0 + uint8x16_t k = + vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 4))); // L = A0 * B4 + + // Add cross products + uint8x16_t l = veorq_u8(e, f); // L = E + F + uint8x16_t m = veorq_u8(g, h); // M = G + H + uint8x16_t n = veorq_u8(i, j); // N = I + J + + // Interleave. Using vzip1 and vzip2 prevents Clang from emitting TBL + // instructions. #if defined(__aarch64__) - return vreinterpretq_m128d_f64(vdupq_n_f64(d)); + uint8x16_t lm_p0 = vreinterpretq_u8_u64( + vzip1q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m))); + uint8x16_t lm_p1 = vreinterpretq_u8_u64( + vzip2q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m))); + uint8x16_t nk_p0 = vreinterpretq_u8_u64( + vzip1q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k))); + uint8x16_t nk_p1 = vreinterpretq_u8_u64( + vzip2q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k))); #else - return vreinterpretq_m128d_s64(vdupq_n_s64(*(int64_t *) &d)); + uint8x16_t lm_p0 = vcombine_u8(vget_low_u8(l), vget_low_u8(m)); + uint8x16_t lm_p1 = vcombine_u8(vget_high_u8(l), vget_high_u8(m)); + uint8x16_t nk_p0 = vcombine_u8(vget_low_u8(n), vget_low_u8(k)); + uint8x16_t nk_p1 = vcombine_u8(vget_high_u8(n), vget_high_u8(k)); +#endif + // t0 = (L) (P0 + P1) << 8 + // t1 = (M) (P2 + P3) << 16 + uint8x16_t t0t1_tmp = veorq_u8(lm_p0, lm_p1); + uint8x16_t t0t1_h = vandq_u8(lm_p1, k48_32); + uint8x16_t t0t1_l = veorq_u8(t0t1_tmp, t0t1_h); + + // t2 = (N) (P4 + P5) << 24 + // t3 = (K) (P6 + P7) << 32 + uint8x16_t t2t3_tmp = veorq_u8(nk_p0, nk_p1); + uint8x16_t t2t3_h = vandq_u8(nk_p1, k16_00); + uint8x16_t t2t3_l = veorq_u8(t2t3_tmp, t2t3_h); + + // De-interleave +#if defined(__aarch64__) + uint8x16_t t0 = vreinterpretq_u8_u64( + vuzp1q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h))); + uint8x16_t t1 = vreinterpretq_u8_u64( + vuzp2q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h))); + uint8x16_t t2 = vreinterpretq_u8_u64( + vuzp1q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h))); + uint8x16_t t3 = vreinterpretq_u8_u64( + vuzp2q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h))); +#else + uint8x16_t t1 = vcombine_u8(vget_high_u8(t0t1_l), vget_high_u8(t0t1_h)); + uint8x16_t t0 = vcombine_u8(vget_low_u8(t0t1_l), vget_low_u8(t0t1_h)); + uint8x16_t t3 = vcombine_u8(vget_high_u8(t2t3_l), vget_high_u8(t2t3_h)); + uint8x16_t t2 = vcombine_u8(vget_low_u8(t2t3_l), vget_low_u8(t2t3_h)); #endif + // Shift the cross products + uint8x16_t t0_shift = vextq_u8(t0, t0, 15); // t0 << 8 + uint8x16_t t1_shift = vextq_u8(t1, t1, 14); // t1 << 16 + uint8x16_t t2_shift = vextq_u8(t2, t2, 13); // t2 << 24 + uint8x16_t t3_shift = vextq_u8(t3, t3, 12); // t3 << 32 + + // Accumulate the products + uint8x16_t cross1 = veorq_u8(t0_shift, t1_shift); + uint8x16_t cross2 = veorq_u8(t2_shift, t3_shift); + uint8x16_t mix = veorq_u8(d, cross1); + uint8x16_t r = veorq_u8(mix, cross2); + return vreinterpretq_u64_u8(r); } +#endif // ARMv7 polyfill -// Sets the 8 signed 16-bit integer values to w. -// -// r0 := w -// r1 := w -// ... -// r7 := w -// -// https://msdn.microsoft.com/en-us/library/k0ya3x0e(v=vs.90).aspx -FORCE_INLINE __m128i _mm_set1_epi16(short w) +// C equivalent: +// __m128i _mm_shuffle_epi32_default(__m128i a, +// __constrange(0, 255) int imm) { +// __m128i ret; +// ret[0] = a[imm & 0x3]; ret[1] = a[(imm >> 2) & 0x3]; +// ret[2] = a[(imm >> 4) & 0x03]; ret[3] = a[(imm >> 6) & 0x03]; +// return ret; +// } +#define _mm_shuffle_epi32_default(a, imm) \ + vreinterpretq_m128i_s32(vsetq_lane_s32( \ + vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 6) & 0x3), \ + vsetq_lane_s32( \ + vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 4) & 0x3), \ + vsetq_lane_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), \ + ((imm) >> 2) & 0x3), \ + vmovq_n_s32(vgetq_lane_s32( \ + vreinterpretq_s32_m128i(a), (imm) & (0x3))), \ + 1), \ + 2), \ + 3)) + +// Takes the upper 64 bits of a and places it in the low end of the result +// Takes the lower 64 bits of a and places it into the high end of the result. +FORCE_INLINE __m128i _mm_shuffle_epi_1032(__m128i a) { - return vreinterpretq_m128i_s16(vdupq_n_s16(w)); + int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); + int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); + return vreinterpretq_m128i_s32(vcombine_s32(a32, a10)); } -// Sets the 16 signed 8-bit integer values. -// https://msdn.microsoft.com/en-us/library/x0cx8zd3(v=vs.90).aspx -FORCE_INLINE __m128i _mm_set_epi8(signed char b15, - signed char b14, - signed char b13, - signed char b12, - signed char b11, - signed char b10, - signed char b9, - signed char b8, - signed char b7, - signed char b6, - signed char b5, - signed char b4, - signed char b3, - signed char b2, - signed char b1, - signed char b0) +// takes the lower two 32-bit values from a and swaps them and places in low end +// of result takes the higher two 32 bit values from a and swaps them and places +// in high end of result. +FORCE_INLINE __m128i _mm_shuffle_epi_2301(__m128i a) { - int8_t ALIGN_STRUCT(16) - data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3, - (int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7, - (int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11, - (int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15}; - return (__m128i) vld1q_s8(data); + int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); + int32x2_t a23 = vrev64_s32(vget_high_s32(vreinterpretq_s32_m128i(a))); + return vreinterpretq_m128i_s32(vcombine_s32(a01, a23)); } -// Sets the 8 signed 16-bit integer values. -// https://msdn.microsoft.com/en-au/library/3e0fek84(v=vs.90).aspx -FORCE_INLINE __m128i _mm_set_epi16(short i7, - short i6, - short i5, - short i4, - short i3, - short i2, - short i1, - short i0) +// rotates the least significant 32 bits into the most significant 32 bits, and +// shifts the rest down +FORCE_INLINE __m128i _mm_shuffle_epi_0321(__m128i a) { - int16_t ALIGN_STRUCT(16) data[8] = {i0, i1, i2, i3, i4, i5, i6, i7}; - return vreinterpretq_m128i_s16(vld1q_s16(data)); + return vreinterpretq_m128i_s32( + vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 1)); } -// Sets the 16 signed 8-bit integer values in reverse order. -// https://msdn.microsoft.com/en-us/library/2khb9c7k(v=vs.90).aspx -FORCE_INLINE __m128i _mm_setr_epi8(signed char b0, - signed char b1, - signed char b2, - signed char b3, - signed char b4, - signed char b5, - signed char b6, - signed char b7, - signed char b8, - signed char b9, - signed char b10, - signed char b11, - signed char b12, - signed char b13, - signed char b14, - signed char b15) +// rotates the most significant 32 bits into the least significant 32 bits, and +// shifts the rest up +FORCE_INLINE __m128i _mm_shuffle_epi_2103(__m128i a) { - int8_t ALIGN_STRUCT(16) - data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3, - (int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7, - (int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11, - (int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15}; - return (__m128i) vld1q_s8(data); + return vreinterpretq_m128i_s32( + vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 3)); } -// Sets the 4 signed 32-bit integer values to i. -// -// r0 := i -// r1 := i -// r2 := i -// r3 := I -// -// https://msdn.microsoft.com/en-us/library/vstudio/h4xscxat(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set1_epi32(int _i) +// gets the lower 64 bits of a, and places it in the upper 64 bits +// gets the lower 64 bits of a and places it in the lower 64 bits +FORCE_INLINE __m128i _mm_shuffle_epi_1010(__m128i a) { - return vreinterpretq_m128i_s32(vdupq_n_s32(_i)); + int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); + return vreinterpretq_m128i_s32(vcombine_s32(a10, a10)); } -// Sets the 2 signed 64-bit integer values to i. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/whtfzhzk(v=vs.100) -FORCE_INLINE __m128i _mm_set1_epi64(__m64 _i) +// gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the +// lower 64 bits gets the lower 64 bits of a, and places it in the upper 64 bits +FORCE_INLINE __m128i _mm_shuffle_epi_1001(__m128i a) { - return vreinterpretq_m128i_s64(vdupq_n_s64((int64_t) _i)); + int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); + int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); + return vreinterpretq_m128i_s32(vcombine_s32(a01, a10)); } -// Sets the 2 signed 64-bit integer values to i. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_set1_epi64x -FORCE_INLINE __m128i _mm_set1_epi64x(int64_t _i) +// gets the lower 64 bits of a, swaps the 0 and 1 elements and places it in the +// upper 64 bits gets the lower 64 bits of a, swaps the 0 and 1 elements, and +// places it in the lower 64 bits +FORCE_INLINE __m128i _mm_shuffle_epi_0101(__m128i a) { - return vreinterpretq_m128i_s64(vdupq_n_s64(_i)); + int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); + return vreinterpretq_m128i_s32(vcombine_s32(a01, a01)); } -// Sets the 4 signed 32-bit integer values. -// https://msdn.microsoft.com/en-us/library/vstudio/019beekt(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set_epi32(int i3, int i2, int i1, int i0) +FORCE_INLINE __m128i _mm_shuffle_epi_2211(__m128i a) { - int32_t ALIGN_STRUCT(16) data[4] = {i0, i1, i2, i3}; - return vreinterpretq_m128i_s32(vld1q_s32(data)); + int32x2_t a11 = vdup_lane_s32(vget_low_s32(vreinterpretq_s32_m128i(a)), 1); + int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); + return vreinterpretq_m128i_s32(vcombine_s32(a11, a22)); } -// Returns the __m128i structure with its two 64-bit integer values -// initialized to the values of the two 64-bit integers passed in. -// https://msdn.microsoft.com/en-us/library/dk2sdw0h(v=vs.120).aspx -FORCE_INLINE __m128i _mm_set_epi64x(int64_t i1, int64_t i2) +FORCE_INLINE __m128i _mm_shuffle_epi_0122(__m128i a) { - int64_t ALIGN_STRUCT(16) data[2] = {i2, i1}; - return vreinterpretq_m128i_s64(vld1q_s64(data)); + int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); + int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); + return vreinterpretq_m128i_s32(vcombine_s32(a22, a01)); } -// Returns the __m128i structure with its two 64-bit integer values -// initialized to the values of the two 64-bit integers passed in. -// https://msdn.microsoft.com/en-us/library/dk2sdw0h(v=vs.120).aspx -FORCE_INLINE __m128i _mm_set_epi64(__m64 i1, __m64 i2) +FORCE_INLINE __m128i _mm_shuffle_epi_3332(__m128i a) { - return _mm_set_epi64x((int64_t) i1, (int64_t) i2); + int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); + int32x2_t a33 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 1); + return vreinterpretq_m128i_s32(vcombine_s32(a32, a33)); } -// Set packed double-precision (64-bit) floating-point elements in dst with the -// supplied values. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_set_pd -FORCE_INLINE __m128d _mm_set_pd(double e1, double e0) -{ - double ALIGN_STRUCT(16) data[2] = {e0, e1}; -#if defined(__aarch64__) - return vreinterpretq_m128d_f64(vld1q_f64((float64_t *) data)); +#if defined(__aarch64__) || defined(_M_ARM64) +#define _mm_shuffle_epi32_splat(a, imm) \ + vreinterpretq_m128i_s32(vdupq_laneq_s32(vreinterpretq_s32_m128i(a), (imm))) #else - return vreinterpretq_m128d_f32(vld1q_f32((float32_t *) data)); +#define _mm_shuffle_epi32_splat(a, imm) \ + vreinterpretq_m128i_s32( \ + vdupq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)))) #endif -} -// Stores four single-precision, floating-point values. -// https://msdn.microsoft.com/en-us/library/vstudio/s3h4ay6y(v=vs.100).aspx -FORCE_INLINE void _mm_store_ps(float *p, __m128 a) +// NEON does not support a general purpose permute intrinsic. +// Shuffle single-precision (32-bit) floating-point elements in a using the +// control in imm8, and store the results in dst. +// +// C equivalent: +// __m128 _mm_shuffle_ps_default(__m128 a, __m128 b, +// __constrange(0, 255) int imm) { +// __m128 ret; +// ret[0] = a[imm & 0x3]; ret[1] = a[(imm >> 2) & 0x3]; +// ret[2] = b[(imm >> 4) & 0x03]; ret[3] = b[(imm >> 6) & 0x03]; +// return ret; +// } +// +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_ps +#define _mm_shuffle_ps_default(a, b, imm) \ + vreinterpretq_m128_f32(vsetq_lane_f32( \ + vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 6) & 0x3), \ + vsetq_lane_f32( \ + vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 4) & 0x3), \ + vsetq_lane_f32( \ + vgetq_lane_f32(vreinterpretq_f32_m128(a), ((imm) >> 2) & 0x3), \ + vmovq_n_f32( \ + vgetq_lane_f32(vreinterpretq_f32_m128(a), (imm) & (0x3))), \ + 1), \ + 2), \ + 3)) + +// Shuffle 16-bit integers in the low 64 bits of a using the control in imm8. +// Store the results in the low 64 bits of dst, with the high 64 bits being +// copied from a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shufflelo_epi16 +#define _mm_shufflelo_epi16_function(a, imm) \ + _sse2neon_define1( \ + __m128i, a, int16x8_t ret = vreinterpretq_s16_m128i(_a); \ + int16x4_t lowBits = vget_low_s16(ret); \ + ret = vsetq_lane_s16(vget_lane_s16(lowBits, (imm) & (0x3)), ret, 0); \ + ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 2) & 0x3), ret, \ + 1); \ + ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 4) & 0x3), ret, \ + 2); \ + ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 6) & 0x3), ret, \ + 3); \ + _sse2neon_return(vreinterpretq_m128i_s16(ret));) + +// Shuffle 16-bit integers in the high 64 bits of a using the control in imm8. +// Store the results in the high 64 bits of dst, with the low 64 bits being +// copied from a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shufflehi_epi16 +#define _mm_shufflehi_epi16_function(a, imm) \ + _sse2neon_define1( \ + __m128i, a, int16x8_t ret = vreinterpretq_s16_m128i(_a); \ + int16x4_t highBits = vget_high_s16(ret); \ + ret = vsetq_lane_s16(vget_lane_s16(highBits, (imm) & (0x3)), ret, 4); \ + ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 2) & 0x3), ret, \ + 5); \ + ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 4) & 0x3), ret, \ + 6); \ + ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 6) & 0x3), ret, \ + 7); \ + _sse2neon_return(vreinterpretq_m128i_s16(ret));) + +/* MMX */ + +//_mm_empty is a no-op on arm +FORCE_INLINE void _mm_empty(void) {} + +/* SSE */ + +// Add packed single-precision (32-bit) floating-point elements in a and b, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_ps +FORCE_INLINE __m128 _mm_add_ps(__m128 a, __m128 b) { - vst1q_f32(p, vreinterpretq_f32_m128(a)); + return vreinterpretq_m128_f32( + vaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } -// Stores four single-precision, floating-point values. -// https://msdn.microsoft.com/en-us/library/44e30x22(v=vs.100).aspx -FORCE_INLINE void _mm_storeu_ps(float *p, __m128 a) +// Add the lower single-precision (32-bit) floating-point element in a and b, +// store the result in the lower element of dst, and copy the upper 3 packed +// elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_ss +FORCE_INLINE __m128 _mm_add_ss(__m128 a, __m128 b) { - vst1q_f32(p, vreinterpretq_f32_m128(a)); + float32_t b0 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 0); + float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); + // the upper values in the result must be the remnants of . + return vreinterpretq_m128_f32(vaddq_f32(a, value)); } -// Stores four 32-bit integer values as (as a __m128i value) at the address p. -// https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx -FORCE_INLINE void _mm_store_si128(__m128i *p, __m128i a) +// Compute the bitwise AND of packed single-precision (32-bit) floating-point +// elements in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_and_ps +FORCE_INLINE __m128 _mm_and_ps(__m128 a, __m128 b) { - vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a)); + return vreinterpretq_m128_s32( + vandq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); } -// Stores four 32-bit integer values as (as a __m128i value) at the address p. -// https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx -FORCE_INLINE void _mm_storeu_si128(__m128i *p, __m128i a) +// Compute the bitwise NOT of packed single-precision (32-bit) floating-point +// elements in a and then AND with b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_andnot_ps +FORCE_INLINE __m128 _mm_andnot_ps(__m128 a, __m128 b) { - vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a)); + return vreinterpretq_m128_s32( + vbicq_s32(vreinterpretq_s32_m128(b), + vreinterpretq_s32_m128(a))); // *NOTE* argument swap } -// Stores the lower single - precision, floating - point value. -// https://msdn.microsoft.com/en-us/library/tzz10fbx(v=vs.100).aspx -FORCE_INLINE void _mm_store_ss(float *p, __m128 a) +// Average packed unsigned 16-bit integers in a and b, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_avg_pu16 +FORCE_INLINE __m64 _mm_avg_pu16(__m64 a, __m64 b) { - vst1q_lane_f32(p, vreinterpretq_f32_m128(a), 0); + return vreinterpret_m64_u16( + vrhadd_u16(vreinterpret_u16_m64(a), vreinterpret_u16_m64(b))); } -// Store 128-bits (composed of 2 packed double-precision (64-bit) floating-point -// elements) from a into memory. mem_addr must be aligned on a 16-byte boundary -// or a general-protection exception may be generated. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_store_pd -FORCE_INLINE void _mm_store_pd(double *mem_addr, __m128d a) +// Average packed unsigned 8-bit integers in a and b, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_avg_pu8 +FORCE_INLINE __m64 _mm_avg_pu8(__m64 a, __m64 b) { -#if defined(__aarch64__) - vst1q_f64((float64_t *) mem_addr, vreinterpretq_f64_m128d(a)); -#else - vst1q_f32((float32_t *) mem_addr, vreinterpretq_f32_m128d(a)); -#endif + return vreinterpret_m64_u8( + vrhadd_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))); } -// Store the lower double-precision (64-bit) floating-point element from a into -// 2 contiguous elements in memory. mem_addr must be aligned on a 16-byte -// boundary or a general-protection exception may be generated. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_store_pd1 -FORCE_INLINE void _mm_store_pd1(double *mem_addr, __m128d a) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for equality, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpeq_ps +FORCE_INLINE __m128 _mm_cmpeq_ps(__m128 a, __m128 b) { -#if defined(__aarch64__) - float64x1_t a_low = vget_low_f64(vreinterpretq_f64_m128d(a)); - vst1q_f64((float64_t *) mem_addr, - vreinterpretq_f64_m128d(vcombine_f64(a_low, a_low))); -#else - float32x2_t a_low = vget_low_f32(vreinterpretq_f32_m128d(a)); - vst1q_f32((float32_t *) mem_addr, - vreinterpretq_f32_m128d(vcombine_f32(a_low, a_low))); -#endif + return vreinterpretq_m128_u32( + vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } -// Store the lower double-precision (64-bit) floating-point element from a into -// 2 contiguous elements in memory. mem_addr must be aligned on a 16-byte -// boundary or a general-protection exception may be generated. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#expand=9,526,5601&text=_mm_store1_pd -#define _mm_store1_pd _mm_store_pd1 - -// Store 128-bits (composed of 2 packed double-precision (64-bit) floating-point -// elements) from a into memory. mem_addr does not need to be aligned on any -// particular boundary. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_storeu_pd -FORCE_INLINE void _mm_storeu_pd(double *mem_addr, __m128d a) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for equality, store the result in the lower element of dst, and copy the +// upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpeq_ss +FORCE_INLINE __m128 _mm_cmpeq_ss(__m128 a, __m128 b) { - _mm_store_pd(mem_addr, a); + return _mm_move_ss(a, _mm_cmpeq_ps(a, b)); } -// Reads the lower 64 bits of b and stores them into the lower 64 bits of a. -// https://msdn.microsoft.com/en-us/library/hhwf428f%28v=vs.90%29.aspx -FORCE_INLINE void _mm_storel_epi64(__m128i *a, __m128i b) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for greater-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpge_ps +FORCE_INLINE __m128 _mm_cmpge_ps(__m128 a, __m128 b) { - uint64x1_t hi = vget_high_u64(vreinterpretq_u64_m128i(*a)); - uint64x1_t lo = vget_low_u64(vreinterpretq_u64_m128i(b)); - *a = vreinterpretq_m128i_u64(vcombine_u64(lo, hi)); + return vreinterpretq_m128_u32( + vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } -// Stores the lower two single-precision floating point values of a to the -// address p. -// -// *p0 := a0 -// *p1 := a1 -// -// https://msdn.microsoft.com/en-us/library/h54t98ks(v=vs.90).aspx -FORCE_INLINE void _mm_storel_pi(__m64 *p, __m128 a) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for greater-than-or-equal, store the result in the lower element of dst, +// and copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpge_ss +FORCE_INLINE __m128 _mm_cmpge_ss(__m128 a, __m128 b) { - *p = vreinterpret_m64_f32(vget_low_f32(a)); + return _mm_move_ss(a, _mm_cmpge_ps(a, b)); } -// Stores the upper two single-precision, floating-point values of a to the -// address p. -// -// *p0 := a2 -// *p1 := a3 -// -// https://msdn.microsoft.com/en-us/library/a7525fs8(v%3dvs.90).aspx -FORCE_INLINE void _mm_storeh_pi(__m64 *p, __m128 a) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for greater-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpgt_ps +FORCE_INLINE __m128 _mm_cmpgt_ps(__m128 a, __m128 b) { - *p = vreinterpret_m64_f32(vget_high_f32(a)); + return vreinterpretq_m128_u32( + vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } -// Loads a single single-precision, floating-point value, copying it into all -// four words -// https://msdn.microsoft.com/en-us/library/vstudio/5cdkf716(v=vs.100).aspx -FORCE_INLINE __m128 _mm_load1_ps(const float *p) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for greater-than, store the result in the lower element of dst, and copy +// the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpgt_ss +FORCE_INLINE __m128 _mm_cmpgt_ss(__m128 a, __m128 b) { - return vreinterpretq_m128_f32(vld1q_dup_f32(p)); + return _mm_move_ss(a, _mm_cmpgt_ps(a, b)); } -// Load a single-precision (32-bit) floating-point element from memory into all -// elements of dst. -// -// dst[31:0] := MEM[mem_addr+31:mem_addr] -// dst[63:32] := MEM[mem_addr+31:mem_addr] -// dst[95:64] := MEM[mem_addr+31:mem_addr] -// dst[127:96] := MEM[mem_addr+31:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load_ps1 -#define _mm_load_ps1 _mm_load1_ps - -// Sets the lower two single-precision, floating-point values with 64 -// bits of data loaded from the address p; the upper two values are passed -// through from a. -// -// Return Value -// r0 := *p0 -// r1 := *p1 -// r2 := a2 -// r3 := a3 -// -// https://msdn.microsoft.com/en-us/library/s57cyak2(v=vs.100).aspx -FORCE_INLINE __m128 _mm_loadl_pi(__m128 a, __m64 const *p) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for less-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmple_ps +FORCE_INLINE __m128 _mm_cmple_ps(__m128 a, __m128 b) { - return vreinterpretq_m128_f32( - vcombine_f32(vld1_f32((const float32_t *) p), vget_high_f32(a))); + return vreinterpretq_m128_u32( + vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } -// Load 4 single-precision (32-bit) floating-point elements from memory into dst -// in reverse order. mem_addr must be aligned on a 16-byte boundary or a -// general-protection exception may be generated. -// -// dst[31:0] := MEM[mem_addr+127:mem_addr+96] -// dst[63:32] := MEM[mem_addr+95:mem_addr+64] -// dst[95:64] := MEM[mem_addr+63:mem_addr+32] -// dst[127:96] := MEM[mem_addr+31:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadr_ps -FORCE_INLINE __m128 _mm_loadr_ps(const float *p) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for less-than-or-equal, store the result in the lower element of dst, and +// copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmple_ss +FORCE_INLINE __m128 _mm_cmple_ss(__m128 a, __m128 b) { - float32x4_t v = vrev64q_f32(vld1q_f32(p)); - return vreinterpretq_m128_f32(vextq_f32(v, v, 2)); + return _mm_move_ss(a, _mm_cmple_ps(a, b)); } -// Sets the upper two single-precision, floating-point values with 64 -// bits of data loaded from the address p; the lower two values are passed -// through from a. -// -// r0 := a0 -// r1 := a1 -// r2 := *p0 -// r3 := *p1 -// -// https://msdn.microsoft.com/en-us/library/w92wta0x(v%3dvs.100).aspx -FORCE_INLINE __m128 _mm_loadh_pi(__m128 a, __m64 const *p) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for less-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmplt_ps +FORCE_INLINE __m128 _mm_cmplt_ps(__m128 a, __m128 b) { - return vreinterpretq_m128_f32( - vcombine_f32(vget_low_f32(a), vld1_f32((const float32_t *) p))); + return vreinterpretq_m128_u32( + vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } -// Loads four single-precision, floating-point values. -// https://msdn.microsoft.com/en-us/library/vstudio/zzd50xxt(v=vs.100).aspx -FORCE_INLINE __m128 _mm_load_ps(const float *p) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for less-than, store the result in the lower element of dst, and copy the +// upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmplt_ss +FORCE_INLINE __m128 _mm_cmplt_ss(__m128 a, __m128 b) { - return vreinterpretq_m128_f32(vld1q_f32(p)); + return _mm_move_ss(a, _mm_cmplt_ps(a, b)); } -// Loads four single-precision, floating-point values. -// https://msdn.microsoft.com/en-us/library/x1b16s7z%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_loadu_ps(const float *p) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for not-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpneq_ps +FORCE_INLINE __m128 _mm_cmpneq_ps(__m128 a, __m128 b) { - // for neon, alignment doesn't matter, so _mm_load_ps and _mm_loadu_ps are - // equivalent for neon - return vreinterpretq_m128_f32(vld1q_f32(p)); + return vreinterpretq_m128_u32(vmvnq_u32( + vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)))); } -// Load unaligned 16-bit integer from memory into the first element of dst. -// -// dst[15:0] := MEM[mem_addr+15:mem_addr] -// dst[MAX:16] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadu_si16 -FORCE_INLINE __m128i _mm_loadu_si16(const void *p) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for not-equal, store the result in the lower element of dst, and copy the +// upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpneq_ss +FORCE_INLINE __m128 _mm_cmpneq_ss(__m128 a, __m128 b) { - return vreinterpretq_m128i_s16( - vsetq_lane_s16(*(const int16_t *) p, vdupq_n_s16(0), 0)); + return _mm_move_ss(a, _mm_cmpneq_ps(a, b)); } -// Load unaligned 64-bit integer from memory into the first element of dst. -// -// dst[63:0] := MEM[mem_addr+63:mem_addr] -// dst[MAX:64] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadu_si64 -FORCE_INLINE __m128i _mm_loadu_si64(const void *p) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for not-greater-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnge_ps +FORCE_INLINE __m128 _mm_cmpnge_ps(__m128 a, __m128 b) { - return vreinterpretq_m128i_s64( - vcombine_s64(vld1_s64((const int64_t *) p), vdup_n_s64(0))); + return vreinterpretq_m128_u32(vmvnq_u32( + vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)))); } -// Load a double-precision (64-bit) floating-point element from memory into the -// lower of dst, and zero the upper element. mem_addr does not need to be -// aligned on any particular boundary. -// -// dst[63:0] := MEM[mem_addr+63:mem_addr] -// dst[127:64] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load_sd -FORCE_INLINE __m128d _mm_load_sd(const double *p) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for not-greater-than-or-equal, store the result in the lower element of +// dst, and copy the upper 3 packed elements from a to the upper elements of +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnge_ss +FORCE_INLINE __m128 _mm_cmpnge_ss(__m128 a, __m128 b) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64(vsetq_lane_f64(*p, vdupq_n_f64(0), 0)); -#else - const float *fp = (const float *) p; - float ALIGN_STRUCT(16) data[4] = {fp[0], fp[1], 0, 0}; - return vreinterpretq_m128d_f32(vld1q_f32(data)); -#endif + return _mm_move_ss(a, _mm_cmpnge_ps(a, b)); } -// Loads two double-precision from 16-byte aligned memory, floating-point -// values. -// -// dst[127:0] := MEM[mem_addr+127:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load_pd -FORCE_INLINE __m128d _mm_load_pd(const double *p) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for not-greater-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpngt_ps +FORCE_INLINE __m128 _mm_cmpngt_ps(__m128 a, __m128 b) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64(vld1q_f64(p)); -#else - const float *fp = (const float *) p; - float ALIGN_STRUCT(16) data[4] = {fp[0], fp[1], fp[2], fp[3]}; - return vreinterpretq_m128d_f32(vld1q_f32(data)); -#endif + return vreinterpretq_m128_u32(vmvnq_u32( + vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)))); } -// Loads two double-precision from unaligned memory, floating-point values. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadu_pd -FORCE_INLINE __m128d _mm_loadu_pd(const double *p) -{ - return _mm_load_pd(p); -} - -// Loads an single - precision, floating - point value into the low word and -// clears the upper three words. -// https://msdn.microsoft.com/en-us/library/548bb9h4%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_load_ss(const float *p) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for not-greater-than, store the result in the lower element of dst, and +// copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpngt_ss +FORCE_INLINE __m128 _mm_cmpngt_ss(__m128 a, __m128 b) { - return vreinterpretq_m128_f32(vsetq_lane_f32(*p, vdupq_n_f32(0), 0)); + return _mm_move_ss(a, _mm_cmpngt_ps(a, b)); } -FORCE_INLINE __m128i _mm_loadl_epi64(__m128i const *p) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for not-less-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnle_ps +FORCE_INLINE __m128 _mm_cmpnle_ps(__m128 a, __m128 b) { - /* Load the lower 64 bits of the value pointed to by p into the - * lower 64 bits of the result, zeroing the upper 64 bits of the result. - */ - return vreinterpretq_m128i_s32( - vcombine_s32(vld1_s32((int32_t const *) p), vcreate_s32(0))); + return vreinterpretq_m128_u32(vmvnq_u32( + vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)))); } -// Load a double-precision (64-bit) floating-point element from memory into the -// lower element of dst, and copy the upper element from a to dst. mem_addr does -// not need to be aligned on any particular boundary. -// -// dst[63:0] := MEM[mem_addr+63:mem_addr] -// dst[127:64] := a[127:64] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadl_pd -FORCE_INLINE __m128d _mm_loadl_pd(__m128d a, const double *p) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for not-less-than-or-equal, store the result in the lower element of dst, +// and copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnle_ss +FORCE_INLINE __m128 _mm_cmpnle_ss(__m128 a, __m128 b) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64( - vcombine_f64(vld1_f64(p), vget_high_f64(vreinterpretq_f64_m128d(a)))); -#else - return vreinterpretq_m128d_f32( - vcombine_f32(vld1_f32((const float *) p), - vget_high_f32(vreinterpretq_f32_m128d(a)))); -#endif + return _mm_move_ss(a, _mm_cmpnle_ps(a, b)); } -// Load 2 double-precision (64-bit) floating-point elements from memory into dst -// in reverse order. mem_addr must be aligned on a 16-byte boundary or a -// general-protection exception may be generated. -// -// dst[63:0] := MEM[mem_addr+127:mem_addr+64] -// dst[127:64] := MEM[mem_addr+63:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadr_pd -FORCE_INLINE __m128d _mm_loadr_pd(const double *p) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// for not-less-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnlt_ps +FORCE_INLINE __m128 _mm_cmpnlt_ps(__m128 a, __m128 b) { -#if defined(__aarch64__) - float64x2_t v = vld1q_f64(p); - return vreinterpretq_m128d_f64(vextq_f64(v, v, 1)); -#else - int64x2_t v = vld1q_s64((const int64_t *) p); - return vreinterpretq_m128d_s64(vextq_s64(v, v, 1)); -#endif + return vreinterpretq_m128_u32(vmvnq_u32( + vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)))); } -// Sets the low word to the single-precision, floating-point value of b -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/35hdzazd(v=vs.100) -FORCE_INLINE __m128 _mm_move_ss(__m128 a, __m128 b) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b for not-less-than, store the result in the lower element of dst, and copy +// the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnlt_ss +FORCE_INLINE __m128 _mm_cmpnlt_ss(__m128 a, __m128 b) { - return vreinterpretq_m128_f32( - vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(b), 0), - vreinterpretq_f32_m128(a), 0)); + return _mm_move_ss(a, _mm_cmpnlt_ps(a, b)); } -// Move the lower double-precision (64-bit) floating-point element from b to the -// lower element of dst, and copy the upper element from a to the upper element -// of dst. +// Compare packed single-precision (32-bit) floating-point elements in a and b +// to see if neither is NaN, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpord_ps // -// dst[63:0] := b[63:0] -// dst[127:64] := a[127:64] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_move_sd -FORCE_INLINE __m128d _mm_move_sd(__m128d a, __m128d b) +// See also: +// http://stackoverflow.com/questions/8627331/what-does-ordered-unordered-comparison-mean +// http://stackoverflow.com/questions/29349621/neon-isnanval-intrinsics +FORCE_INLINE __m128 _mm_cmpord_ps(__m128 a, __m128 b) { - return vreinterpretq_m128d_f32( - vcombine_f32(vget_low_f32(vreinterpretq_f32_m128d(b)), - vget_high_f32(vreinterpretq_f32_m128d(a)))); + // Note: NEON does not have ordered compare builtin + // Need to compare a eq a and b eq b to check for NaN + // Do AND of results to get final + uint32x4_t ceqaa = + vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); + uint32x4_t ceqbb = + vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_u32(vandq_u32(ceqaa, ceqbb)); } -// Copy the lower 64-bit integer in a to the lower element of dst, and zero the -// upper element. -// -// dst[63:0] := a[63:0] -// dst[127:64] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_move_epi64 -FORCE_INLINE __m128i _mm_move_epi64(__m128i a) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b to see if neither is NaN, store the result in the lower element of dst, and +// copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpord_ss +FORCE_INLINE __m128 _mm_cmpord_ss(__m128 a, __m128 b) { - return vreinterpretq_m128i_s64( - vsetq_lane_s64(0, vreinterpretq_s64_m128i(a), 1)); + return _mm_move_ss(a, _mm_cmpord_ps(a, b)); } -// Return vector of type __m128 with undefined elements. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_undefined_ps -FORCE_INLINE __m128 _mm_undefined_ps(void) +// Compare packed single-precision (32-bit) floating-point elements in a and b +// to see if either is NaN, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpunord_ps +FORCE_INLINE __m128 _mm_cmpunord_ps(__m128 a, __m128 b) { - __m128 a; - return a; + uint32x4_t f32a = + vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); + uint32x4_t f32b = + vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_u32(vmvnq_u32(vandq_u32(f32a, f32b))); } -/* Logic/Binary operations */ - -// Computes the bitwise AND-NOT of the four single-precision, floating-point -// values of a and b. -// -// r0 := ~a0 & b0 -// r1 := ~a1 & b1 -// r2 := ~a2 & b2 -// r3 := ~a3 & b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/68h7wd02(v=vs.100).aspx -FORCE_INLINE __m128 _mm_andnot_ps(__m128 a, __m128 b) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b to see if either is NaN, store the result in the lower element of dst, and +// copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpunord_ss +FORCE_INLINE __m128 _mm_cmpunord_ss(__m128 a, __m128 b) { - return vreinterpretq_m128_s32( - vbicq_s32(vreinterpretq_s32_m128(b), - vreinterpretq_s32_m128(a))); // *NOTE* argument swap + return _mm_move_ss(a, _mm_cmpunord_ps(a, b)); } -// Compute the bitwise NOT of packed double-precision (64-bit) floating-point -// elements in a and then AND with b, and store the results in dst. -// -// FOR j := 0 to 1 -// i := j*64 -// dst[i+63:i] := ((NOT a[i+63:i]) AND b[i+63:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_andnot_pd -FORCE_INLINE __m128d _mm_andnot_pd(__m128d a, __m128d b) +// Compare the lower single-precision (32-bit) floating-point element in a and b +// for equality, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comieq_ss +FORCE_INLINE int _mm_comieq_ss(__m128 a, __m128 b) { - // *NOTE* argument swap - return vreinterpretq_m128d_s64( - vbicq_s64(vreinterpretq_s64_m128d(b), vreinterpretq_s64_m128d(a))); + uint32x4_t a_eq_b = + vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); + return vgetq_lane_u32(a_eq_b, 0) & 0x1; } -// Computes the bitwise AND of the 128-bit value in b and the bitwise NOT of the -// 128-bit value in a. -// -// r := (~a) & b -// -// https://msdn.microsoft.com/en-us/library/vstudio/1beaceh8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_andnot_si128(__m128i a, __m128i b) +// Compare the lower single-precision (32-bit) floating-point element in a and b +// for greater-than-or-equal, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comige_ss +FORCE_INLINE int _mm_comige_ss(__m128 a, __m128 b) { - return vreinterpretq_m128i_s32( - vbicq_s32(vreinterpretq_s32_m128i(b), - vreinterpretq_s32_m128i(a))); // *NOTE* argument swap + uint32x4_t a_ge_b = + vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); + return vgetq_lane_u32(a_ge_b, 0) & 0x1; } -// Computes the bitwise AND of the 128-bit value in a and the 128-bit value in -// b. -// -// r := a & b -// -// https://msdn.microsoft.com/en-us/library/vstudio/6d1txsa8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_and_si128(__m128i a, __m128i b) +// Compare the lower single-precision (32-bit) floating-point element in a and b +// for greater-than, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comigt_ss +FORCE_INLINE int _mm_comigt_ss(__m128 a, __m128 b) { - return vreinterpretq_m128i_s32( - vandq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); + uint32x4_t a_gt_b = + vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); + return vgetq_lane_u32(a_gt_b, 0) & 0x1; } -// Computes the bitwise AND of the four single-precision, floating-point values -// of a and b. -// -// r0 := a0 & b0 -// r1 := a1 & b1 -// r2 := a2 & b2 -// r3 := a3 & b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/73ck1xc5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_and_ps(__m128 a, __m128 b) +// Compare the lower single-precision (32-bit) floating-point element in a and b +// for less-than-or-equal, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comile_ss +FORCE_INLINE int _mm_comile_ss(__m128 a, __m128 b) { - return vreinterpretq_m128_s32( - vandq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); + uint32x4_t a_le_b = + vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); + return vgetq_lane_u32(a_le_b, 0) & 0x1; } -// Compute the bitwise AND of packed double-precision (64-bit) floating-point -// elements in a and b, and store the results in dst. -// -// FOR j := 0 to 1 -// i := j*64 -// dst[i+63:i] := a[i+63:i] AND b[i+63:i] -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_and_pd -FORCE_INLINE __m128d _mm_and_pd(__m128d a, __m128d b) +// Compare the lower single-precision (32-bit) floating-point element in a and b +// for less-than, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comilt_ss +FORCE_INLINE int _mm_comilt_ss(__m128 a, __m128 b) { - return vreinterpretq_m128d_s64( - vandq_s64(vreinterpretq_s64_m128d(a), vreinterpretq_s64_m128d(b))); + uint32x4_t a_lt_b = + vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); + return vgetq_lane_u32(a_lt_b, 0) & 0x1; } -// Computes the bitwise OR of the four single-precision, floating-point values -// of a and b. -// https://msdn.microsoft.com/en-us/library/vstudio/7ctdsyy0(v=vs.100).aspx -FORCE_INLINE __m128 _mm_or_ps(__m128 a, __m128 b) +// Compare the lower single-precision (32-bit) floating-point element in a and b +// for not-equal, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comineq_ss +FORCE_INLINE int _mm_comineq_ss(__m128 a, __m128 b) { - return vreinterpretq_m128_s32( - vorrq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); + return !_mm_comieq_ss(a, b); } -// Computes bitwise EXOR (exclusive-or) of the four single-precision, -// floating-point values of a and b. -// https://msdn.microsoft.com/en-us/library/ss6k3wk8(v=vs.100).aspx -FORCE_INLINE __m128 _mm_xor_ps(__m128 a, __m128 b) +// Convert packed signed 32-bit integers in b to packed single-precision +// (32-bit) floating-point elements, store the results in the lower 2 elements +// of dst, and copy the upper 2 packed elements from a to the upper elements of +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvt_pi2ps +FORCE_INLINE __m128 _mm_cvt_pi2ps(__m128 a, __m64 b) { - return vreinterpretq_m128_s32( - veorq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); + return vreinterpretq_m128_f32( + vcombine_f32(vcvt_f32_s32(vreinterpret_s32_m64(b)), + vget_high_f32(vreinterpretq_f32_m128(a)))); } -// Compute the bitwise XOR of packed double-precision (64-bit) floating-point -// elements in a and b, and store the results in dst. -// -// FOR j := 0 to 1 -// i := j*64 -// dst[i+63:i] := a[i+63:i] XOR b[i+63:i] -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_xor_pd -FORCE_INLINE __m128d _mm_xor_pd(__m128d a, __m128d b) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 32-bit integers, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvt_ps2pi +FORCE_INLINE __m64 _mm_cvt_ps2pi(__m128 a) { - return vreinterpretq_m128d_s64( - veorq_s64(vreinterpretq_s64_m128d(a), vreinterpretq_s64_m128d(b))); +#if (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_DIRECTED_ROUNDING) + return vreinterpret_m64_s32( + vget_low_s32(vcvtnq_s32_f32(vrndiq_f32(vreinterpretq_f32_m128(a))))); +#else + return vreinterpret_m64_s32(vcvt_s32_f32(vget_low_f32( + vreinterpretq_f32_m128(_mm_round_ps(a, _MM_FROUND_CUR_DIRECTION))))); +#endif } -// Compute the bitwise OR of packed double-precision (64-bit) floating-point -// elements in a and b, and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=mm_or_pd -FORCE_INLINE __m128d _mm_or_pd(__m128d a, __m128d b) +// Convert the signed 32-bit integer b to a single-precision (32-bit) +// floating-point element, store the result in the lower element of dst, and +// copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvt_si2ss +FORCE_INLINE __m128 _mm_cvt_si2ss(__m128 a, int b) { - return vreinterpretq_m128d_s64( - vorrq_s64(vreinterpretq_s64_m128d(a), vreinterpretq_s64_m128d(b))); + return vreinterpretq_m128_f32( + vsetq_lane_f32((float) b, vreinterpretq_f32_m128(a), 0)); } -// Computes the bitwise OR of the 128-bit value in a and the 128-bit value in b. -// -// r := a | b -// -// https://msdn.microsoft.com/en-us/library/vstudio/ew8ty0db(v=vs.100).aspx -FORCE_INLINE __m128i _mm_or_si128(__m128i a, __m128i b) +// Convert the lower single-precision (32-bit) floating-point element in a to a +// 32-bit integer, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvt_ss2si +FORCE_INLINE int _mm_cvt_ss2si(__m128 a) { - return vreinterpretq_m128i_s32( - vorrq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +#if (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_DIRECTED_ROUNDING) + return vgetq_lane_s32(vcvtnq_s32_f32(vrndiq_f32(vreinterpretq_f32_m128(a))), + 0); +#else + float32_t data = vgetq_lane_f32( + vreinterpretq_f32_m128(_mm_round_ps(a, _MM_FROUND_CUR_DIRECTION)), 0); + return (int32_t) data; +#endif } -// Computes the bitwise XOR of the 128-bit value in a and the 128-bit value in -// b. https://msdn.microsoft.com/en-us/library/fzt08www(v=vs.100).aspx -FORCE_INLINE __m128i _mm_xor_si128(__m128i a, __m128i b) +// Convert packed 16-bit integers in a to packed single-precision (32-bit) +// floating-point elements, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpi16_ps +FORCE_INLINE __m128 _mm_cvtpi16_ps(__m64 a) { - return vreinterpretq_m128i_s32( - veorq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); + return vreinterpretq_m128_f32( + vcvtq_f32_s32(vmovl_s16(vreinterpret_s16_m64(a)))); } -// Duplicate odd-indexed single-precision (32-bit) floating-point elements -// from a, and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_movehdup_ps -FORCE_INLINE __m128 _mm_movehdup_ps(__m128 a) +// Convert packed 32-bit integers in b to packed single-precision (32-bit) +// floating-point elements, store the results in the lower 2 elements of dst, +// and copy the upper 2 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpi32_ps +FORCE_INLINE __m128 _mm_cvtpi32_ps(__m128 a, __m64 b) { -#if __has_builtin(__builtin_shufflevector) - return vreinterpretq_m128_f32(__builtin_shufflevector( - vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 1, 1, 3, 3)); -#else - float32_t a1 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 1); - float32_t a3 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 3); - float ALIGN_STRUCT(16) data[4] = {a1, a1, a3, a3}; - return vreinterpretq_m128_f32(vld1q_f32(data)); -#endif + return vreinterpretq_m128_f32( + vcombine_f32(vcvt_f32_s32(vreinterpret_s32_m64(b)), + vget_high_f32(vreinterpretq_f32_m128(a)))); } -// Duplicate even-indexed single-precision (32-bit) floating-point elements -// from a, and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_moveldup_ps -FORCE_INLINE __m128 _mm_moveldup_ps(__m128 a) +// Convert packed signed 32-bit integers in a to packed single-precision +// (32-bit) floating-point elements, store the results in the lower 2 elements +// of dst, then convert the packed signed 32-bit integers in b to +// single-precision (32-bit) floating-point element, and store the results in +// the upper 2 elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpi32x2_ps +FORCE_INLINE __m128 _mm_cvtpi32x2_ps(__m64 a, __m64 b) { -#if __has_builtin(__builtin_shufflevector) - return vreinterpretq_m128_f32(__builtin_shufflevector( - vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 0, 0, 2, 2)); -#else - float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); - float32_t a2 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 2); - float ALIGN_STRUCT(16) data[4] = {a0, a0, a2, a2}; - return vreinterpretq_m128_f32(vld1q_f32(data)); -#endif + return vreinterpretq_m128_f32(vcvtq_f32_s32( + vcombine_s32(vreinterpret_s32_m64(a), vreinterpret_s32_m64(b)))); } -// Moves the upper two values of B into the lower two values of A. -// -// r3 := a3 -// r2 := a2 -// r1 := b3 -// r0 := b2 -FORCE_INLINE __m128 _mm_movehl_ps(__m128 __A, __m128 __B) -{ - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(__A)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(__B)); - return vreinterpretq_m128_f32(vcombine_f32(b32, a32)); +// Convert the lower packed 8-bit integers in a to packed single-precision +// (32-bit) floating-point elements, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpi8_ps +FORCE_INLINE __m128 _mm_cvtpi8_ps(__m64 a) +{ + return vreinterpretq_m128_f32(vcvtq_f32_s32( + vmovl_s16(vget_low_s16(vmovl_s8(vreinterpret_s8_m64(a)))))); } -// Moves the lower two values of B into the upper two values of A. -// -// r3 := b1 -// r2 := b0 -// r1 := a1 -// r0 := a0 -FORCE_INLINE __m128 _mm_movelh_ps(__m128 __A, __m128 __B) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 16-bit integers, and store the results in dst. Note: this intrinsic +// will generate 0x7FFF, rather than 0x8000, for input values between 0x7FFF and +// 0x7FFFFFFF. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtps_pi16 +FORCE_INLINE __m64 _mm_cvtps_pi16(__m128 a) { - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(__A)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(__B)); - return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); + return vreinterpret_m64_s16( + vqmovn_s32(vreinterpretq_s32_m128i(_mm_cvtps_epi32(a)))); } -// Compute the absolute value of packed signed 32-bit integers in a, and store -// the unsigned results in dst. -// -// FOR j := 0 to 3 -// i := j*32 -// dst[i+31:i] := ABS(a[i+31:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_abs_epi32 -FORCE_INLINE __m128i _mm_abs_epi32(__m128i a) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 32-bit integers, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtps_pi32 +#define _mm_cvtps_pi32(a) _mm_cvt_ps2pi(a) + +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 8-bit integers, and store the results in lower 4 elements of dst. +// Note: this intrinsic will generate 0x7F, rather than 0x80, for input values +// between 0x7F and 0x7FFFFFFF. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtps_pi8 +FORCE_INLINE __m64 _mm_cvtps_pi8(__m128 a) { - return vreinterpretq_m128i_s32(vabsq_s32(vreinterpretq_s32_m128i(a))); + return vreinterpret_m64_s8(vqmovn_s16( + vcombine_s16(vreinterpret_s16_m64(_mm_cvtps_pi16(a)), vdup_n_s16(0)))); } -// Compute the absolute value of packed signed 16-bit integers in a, and store -// the unsigned results in dst. -// -// FOR j := 0 to 7 -// i := j*16 -// dst[i+15:i] := ABS(a[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_abs_epi16 -FORCE_INLINE __m128i _mm_abs_epi16(__m128i a) +// Convert packed unsigned 16-bit integers in a to packed single-precision +// (32-bit) floating-point elements, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpu16_ps +FORCE_INLINE __m128 _mm_cvtpu16_ps(__m64 a) { - return vreinterpretq_m128i_s16(vabsq_s16(vreinterpretq_s16_m128i(a))); + return vreinterpretq_m128_f32( + vcvtq_f32_u32(vmovl_u16(vreinterpret_u16_m64(a)))); } -// Compute the absolute value of packed signed 8-bit integers in a, and store -// the unsigned results in dst. -// -// FOR j := 0 to 15 -// i := j*8 -// dst[i+7:i] := ABS(a[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_abs_epi8 -FORCE_INLINE __m128i _mm_abs_epi8(__m128i a) +// Convert the lower packed unsigned 8-bit integers in a to packed +// single-precision (32-bit) floating-point elements, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpu8_ps +FORCE_INLINE __m128 _mm_cvtpu8_ps(__m64 a) { - return vreinterpretq_m128i_s8(vabsq_s8(vreinterpretq_s8_m128i(a))); + return vreinterpretq_m128_f32(vcvtq_f32_u32( + vmovl_u16(vget_low_u16(vmovl_u8(vreinterpret_u8_m64(a)))))); } -// Compute the absolute value of packed signed 32-bit integers in a, and store -// the unsigned results in dst. -// -// FOR j := 0 to 1 -// i := j*32 -// dst[i+31:i] := ABS(a[i+31:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_abs_pi32 -FORCE_INLINE __m64 _mm_abs_pi32(__m64 a) +// Convert the signed 32-bit integer b to a single-precision (32-bit) +// floating-point element, store the result in the lower element of dst, and +// copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi32_ss +#define _mm_cvtsi32_ss(a, b) _mm_cvt_si2ss(a, b) + +// Convert the signed 64-bit integer b to a single-precision (32-bit) +// floating-point element, store the result in the lower element of dst, and +// copy the upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi64_ss +FORCE_INLINE __m128 _mm_cvtsi64_ss(__m128 a, int64_t b) { - return vreinterpret_m64_s32(vabs_s32(vreinterpret_s32_m64(a))); + return vreinterpretq_m128_f32( + vsetq_lane_f32((float) b, vreinterpretq_f32_m128(a), 0)); } -// Compute the absolute value of packed signed 16-bit integers in a, and store -// the unsigned results in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// dst[i+15:i] := ABS(a[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_abs_pi16 -FORCE_INLINE __m64 _mm_abs_pi16(__m64 a) +// Copy the lower single-precision (32-bit) floating-point element of a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtss_f32 +FORCE_INLINE float _mm_cvtss_f32(__m128 a) { - return vreinterpret_m64_s16(vabs_s16(vreinterpret_s16_m64(a))); + return vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); } -// Compute the absolute value of packed signed 8-bit integers in a, and store -// the unsigned results in dst. -// -// FOR j := 0 to 7 -// i := j*8 -// dst[i+7:i] := ABS(a[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_abs_pi8 -FORCE_INLINE __m64 _mm_abs_pi8(__m64 a) +// Convert the lower single-precision (32-bit) floating-point element in a to a +// 32-bit integer, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtss_si32 +#define _mm_cvtss_si32(a) _mm_cvt_ss2si(a) + +// Convert the lower single-precision (32-bit) floating-point element in a to a +// 64-bit integer, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtss_si64 +FORCE_INLINE int64_t _mm_cvtss_si64(__m128 a) { - return vreinterpret_m64_s8(vabs_s8(vreinterpret_s8_m64(a))); +#if (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_DIRECTED_ROUNDING) + return (int64_t) vgetq_lane_f32(vrndiq_f32(vreinterpretq_f32_m128(a)), 0); +#else + float32_t data = vgetq_lane_f32( + vreinterpretq_f32_m128(_mm_round_ps(a, _MM_FROUND_CUR_DIRECTION)), 0); + return (int64_t) data; +#endif } -// Takes the upper 64 bits of a and places it in the low end of the result -// Takes the lower 64 bits of b and places it into the high end of the result. -FORCE_INLINE __m128 _mm_shuffle_ps_1032(__m128 a, __m128 b) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 32-bit integers with truncation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtt_ps2pi +FORCE_INLINE __m64 _mm_cvtt_ps2pi(__m128 a) { - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a32, b10)); + return vreinterpret_m64_s32( + vget_low_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a)))); } -// takes the lower two 32-bit values from a and swaps them and places in high -// end of result takes the higher two 32 bit values from b and swaps them and -// places in low end of result. -FORCE_INLINE __m128 _mm_shuffle_ps_2301(__m128 a, __m128 b) +// Convert the lower single-precision (32-bit) floating-point element in a to a +// 32-bit integer with truncation, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtt_ss2si +FORCE_INLINE int _mm_cvtt_ss2si(__m128 a) { - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b23 = vrev64_f32(vget_high_f32(vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vcombine_f32(a01, b23)); + return vgetq_lane_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a)), 0); } -FORCE_INLINE __m128 _mm_shuffle_ps_0321(__m128 a, __m128 b) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 32-bit integers with truncation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttps_pi32 +#define _mm_cvttps_pi32(a) _mm_cvtt_ps2pi(a) + +// Convert the lower single-precision (32-bit) floating-point element in a to a +// 32-bit integer with truncation, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttss_si32 +#define _mm_cvttss_si32(a) _mm_cvtt_ss2si(a) + +// Convert the lower single-precision (32-bit) floating-point element in a to a +// 64-bit integer with truncation, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttss_si64 +FORCE_INLINE int64_t _mm_cvttss_si64(__m128 a) { - float32x2_t a21 = vget_high_f32( - vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); - float32x2_t b03 = vget_low_f32( - vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); - return vreinterpretq_m128_f32(vcombine_f32(a21, b03)); + return (int64_t) vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); } -FORCE_INLINE __m128 _mm_shuffle_ps_2103(__m128 a, __m128 b) +// Divide packed single-precision (32-bit) floating-point elements in a by +// packed elements in b, and store the results in dst. +// Due to ARMv7-A NEON's lack of a precise division intrinsic, we implement +// division by multiplying a by b's reciprocal before using the Newton-Raphson +// method to approximate the results. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_div_ps +FORCE_INLINE __m128 _mm_div_ps(__m128 a, __m128 b) { - float32x2_t a03 = vget_low_f32( - vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); - float32x2_t b21 = vget_high_f32( - vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); - return vreinterpretq_m128_f32(vcombine_f32(a03, b21)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32( + vdivq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); +#else + float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(b)); + recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(b))); + // Additional Netwon-Raphson iteration for accuracy + recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(b))); + return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), recip)); +#endif } -FORCE_INLINE __m128 _mm_shuffle_ps_1010(__m128 a, __m128 b) +// Divide the lower single-precision (32-bit) floating-point element in a by the +// lower single-precision (32-bit) floating-point element in b, store the result +// in the lower element of dst, and copy the upper 3 packed elements from a to +// the upper elements of dst. +// Warning: ARMv7-A does not produce the same result compared to Intel and not +// IEEE-compliant. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_div_ss +FORCE_INLINE __m128 _mm_div_ss(__m128 a, __m128 b) { - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); + float32_t value = + vgetq_lane_f32(vreinterpretq_f32_m128(_mm_div_ps(a, b)), 0); + return vreinterpretq_m128_f32( + vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); } -FORCE_INLINE __m128 _mm_shuffle_ps_1001(__m128 a, __m128 b) +// Extract a 16-bit integer from a, selected with imm8, and store the result in +// the lower element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_extract_pi16 +#define _mm_extract_pi16(a, imm) \ + (int32_t) vget_lane_u16(vreinterpret_u16_m64(a), (imm)) + +// Free aligned memory that was allocated with _mm_malloc. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_free +#if !defined(SSE2NEON_ALLOC_DEFINED) +FORCE_INLINE void _mm_free(void *addr) { - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a01, b10)); + free(addr); } +#endif -FORCE_INLINE __m128 _mm_shuffle_ps_0101(__m128 a, __m128 b) +FORCE_INLINE uint64_t _sse2neon_get_fpcr(void) { - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vcombine_f32(a01, b01)); + uint64_t value; +#if defined(_MSC_VER) + value = _ReadStatusReg(ARM64_FPCR); +#else + __asm__ __volatile__("mrs %0, FPCR" : "=r"(value)); /* read */ +#endif + return value; } -// keeps the low 64 bits of b in the low and puts the high 64 bits of a in the -// high -FORCE_INLINE __m128 _mm_shuffle_ps_3210(__m128 a, __m128 b) +FORCE_INLINE void _sse2neon_set_fpcr(uint64_t value) { - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a10, b32)); +#if defined(_MSC_VER) + _WriteStatusReg(ARM64_FPCR, value); +#else + __asm__ __volatile__("msr FPCR, %0" ::"r"(value)); /* write */ +#endif } -FORCE_INLINE __m128 _mm_shuffle_ps_0011(__m128 a, __m128 b) +// Macro: Get the flush zero bits from the MXCSR control and status register. +// The flush zero may contain any of the following flags: _MM_FLUSH_ZERO_ON or +// _MM_FLUSH_ZERO_OFF +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_MM_GET_FLUSH_ZERO_MODE +FORCE_INLINE unsigned int _sse2neon_mm_get_flush_zero_mode(void) { - float32x2_t a11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 1); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a11, b00)); + union { + fpcr_bitfield field; +#if defined(__aarch64__) || defined(_M_ARM64) + uint64_t value; +#else + uint32_t value; +#endif + } r; + +#if defined(__aarch64__) || defined(_M_ARM64) + r.value = _sse2neon_get_fpcr(); +#else + __asm__ __volatile__("vmrs %0, FPSCR" : "=r"(r.value)); /* read */ +#endif + + return r.field.bit24 ? _MM_FLUSH_ZERO_ON : _MM_FLUSH_ZERO_OFF; } -FORCE_INLINE __m128 _mm_shuffle_ps_0022(__m128 a, __m128 b) +// Macro: Get the rounding mode bits from the MXCSR control and status register. +// The rounding mode may contain any of the following flags: _MM_ROUND_NEAREST, +// _MM_ROUND_DOWN, _MM_ROUND_UP, _MM_ROUND_TOWARD_ZERO +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_MM_GET_ROUNDING_MODE +FORCE_INLINE unsigned int _MM_GET_ROUNDING_MODE(void) { - float32x2_t a22 = - vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a22, b00)); + union { + fpcr_bitfield field; +#if defined(__aarch64__) || defined(_M_ARM64) + uint64_t value; +#else + uint32_t value; +#endif + } r; + +#if defined(__aarch64__) || defined(_M_ARM64) + r.value = _sse2neon_get_fpcr(); +#else + __asm__ __volatile__("vmrs %0, FPSCR" : "=r"(r.value)); /* read */ +#endif + + if (r.field.bit22) { + return r.field.bit23 ? _MM_ROUND_TOWARD_ZERO : _MM_ROUND_UP; + } else { + return r.field.bit23 ? _MM_ROUND_DOWN : _MM_ROUND_NEAREST; + } } -FORCE_INLINE __m128 _mm_shuffle_ps_2200(__m128 a, __m128 b) +// Copy a to dst, and insert the 16-bit integer i into dst at the location +// specified by imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_insert_pi16 +#define _mm_insert_pi16(a, b, imm) \ + vreinterpret_m64_s16(vset_lane_s16((b), vreinterpret_s16_m64(a), (imm))) + +// Load 128-bits (composed of 4 packed single-precision (32-bit) floating-point +// elements) from memory into dst. mem_addr must be aligned on a 16-byte +// boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load_ps +FORCE_INLINE __m128 _mm_load_ps(const float *p) { - float32x2_t a00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t b22 = - vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a00, b22)); + return vreinterpretq_m128_f32(vld1q_f32(p)); } -FORCE_INLINE __m128 _mm_shuffle_ps_3202(__m128 a, __m128 b) +// Load a single-precision (32-bit) floating-point element from memory into all +// elements of dst. +// +// dst[31:0] := MEM[mem_addr+31:mem_addr] +// dst[63:32] := MEM[mem_addr+31:mem_addr] +// dst[95:64] := MEM[mem_addr+31:mem_addr] +// dst[127:96] := MEM[mem_addr+31:mem_addr] +// +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load_ps1 +#define _mm_load_ps1 _mm_load1_ps + +// Load a single-precision (32-bit) floating-point element from memory into the +// lower of dst, and zero the upper 3 elements. mem_addr does not need to be +// aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load_ss +FORCE_INLINE __m128 _mm_load_ss(const float *p) { - float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); - float32x2_t a22 = - vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t a02 = vset_lane_f32(a0, a22, 1); /* TODO: use vzip ?*/ - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a02, b32)); + return vreinterpretq_m128_f32(vsetq_lane_f32(*p, vdupq_n_f32(0), 0)); } -FORCE_INLINE __m128 _mm_shuffle_ps_1133(__m128 a, __m128 b) +// Load a single-precision (32-bit) floating-point element from memory into all +// elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load1_ps +FORCE_INLINE __m128 _mm_load1_ps(const float *p) { - float32x2_t a33 = - vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 1); - float32x2_t b11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 1); - return vreinterpretq_m128_f32(vcombine_f32(a33, b11)); + return vreinterpretq_m128_f32(vld1q_dup_f32(p)); } -FORCE_INLINE __m128 _mm_shuffle_ps_2010(__m128 a, __m128 b) +// Load 2 single-precision (32-bit) floating-point elements from memory into the +// upper 2 elements of dst, and copy the lower 2 elements from a to dst. +// mem_addr does not need to be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadh_pi +FORCE_INLINE __m128 _mm_loadh_pi(__m128 a, __m64 const *p) { - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32_t b2 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a10, b20)); + return vreinterpretq_m128_f32( + vcombine_f32(vget_low_f32(a), vld1_f32((const float32_t *) p))); } -FORCE_INLINE __m128 _mm_shuffle_ps_2001(__m128 a, __m128 b) +// Load 2 single-precision (32-bit) floating-point elements from memory into the +// lower 2 elements of dst, and copy the upper 2 elements from a to dst. +// mem_addr does not need to be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadl_pi +FORCE_INLINE __m128 _mm_loadl_pi(__m128 a, __m64 const *p) { - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32_t b2 = vgetq_lane_f32(b, 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a01, b20)); + return vreinterpretq_m128_f32( + vcombine_f32(vld1_f32((const float32_t *) p), vget_high_f32(a))); } -FORCE_INLINE __m128 _mm_shuffle_ps_2032(__m128 a, __m128 b) +// Load 4 single-precision (32-bit) floating-point elements from memory into dst +// in reverse order. mem_addr must be aligned on a 16-byte boundary or a +// general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadr_ps +FORCE_INLINE __m128 _mm_loadr_ps(const float *p) { - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32_t b2 = vgetq_lane_f32(b, 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a32, b20)); + float32x4_t v = vrev64q_f32(vld1q_f32(p)); + return vreinterpretq_m128_f32(vextq_f32(v, v, 2)); } -// NEON does not support a general purpose permute intrinsic -// Selects four specific single-precision, floating-point values from a and b, -// based on the mask i. -// -// C equivalent: -// __m128 _mm_shuffle_ps_default(__m128 a, __m128 b, -// __constrange(0, 255) int imm) { -// __m128 ret; -// ret[0] = a[imm & 0x3]; ret[1] = a[(imm >> 2) & 0x3]; -// ret[2] = b[(imm >> 4) & 0x03]; ret[3] = b[(imm >> 6) & 0x03]; -// return ret; -// } -// -// https://msdn.microsoft.com/en-us/library/vstudio/5f0858x0(v=vs.100).aspx -#define _mm_shuffle_ps_default(a, b, imm) \ - __extension__({ \ - float32x4_t ret; \ - ret = vmovq_n_f32( \ - vgetq_lane_f32(vreinterpretq_f32_m128(a), (imm) & (0x3))); \ - ret = vsetq_lane_f32( \ - vgetq_lane_f32(vreinterpretq_f32_m128(a), ((imm) >> 2) & 0x3), \ - ret, 1); \ - ret = vsetq_lane_f32( \ - vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 4) & 0x3), \ - ret, 2); \ - ret = vsetq_lane_f32( \ - vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 6) & 0x3), \ - ret, 3); \ - vreinterpretq_m128_f32(ret); \ - }) +// Load 128-bits (composed of 4 packed single-precision (32-bit) floating-point +// elements) from memory into dst. mem_addr does not need to be aligned on any +// particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadu_ps +FORCE_INLINE __m128 _mm_loadu_ps(const float *p) +{ + // for neon, alignment doesn't matter, so _mm_load_ps and _mm_loadu_ps are + // equivalent for neon + return vreinterpretq_m128_f32(vld1q_f32(p)); +} -// FORCE_INLINE __m128 _mm_shuffle_ps(__m128 a, __m128 b, __constrange(0,255) -// int imm) -#if __has_builtin(__builtin_shufflevector) -#define _mm_shuffle_ps(a, b, imm) \ - __extension__({ \ - float32x4_t _input1 = vreinterpretq_f32_m128(a); \ - float32x4_t _input2 = vreinterpretq_f32_m128(b); \ - float32x4_t _shuf = __builtin_shufflevector( \ - _input1, _input2, (imm) & (0x3), ((imm) >> 2) & 0x3, \ - (((imm) >> 4) & 0x3) + 4, (((imm) >> 6) & 0x3) + 4); \ - vreinterpretq_m128_f32(_shuf); \ - }) -#else // generic -#define _mm_shuffle_ps(a, b, imm) \ - __extension__({ \ - __m128 ret; \ - switch (imm) { \ - case _MM_SHUFFLE(1, 0, 3, 2): \ - ret = _mm_shuffle_ps_1032((a), (b)); \ - break; \ - case _MM_SHUFFLE(2, 3, 0, 1): \ - ret = _mm_shuffle_ps_2301((a), (b)); \ - break; \ - case _MM_SHUFFLE(0, 3, 2, 1): \ - ret = _mm_shuffle_ps_0321((a), (b)); \ - break; \ - case _MM_SHUFFLE(2, 1, 0, 3): \ - ret = _mm_shuffle_ps_2103((a), (b)); \ - break; \ - case _MM_SHUFFLE(1, 0, 1, 0): \ - ret = _mm_movelh_ps((a), (b)); \ - break; \ - case _MM_SHUFFLE(1, 0, 0, 1): \ - ret = _mm_shuffle_ps_1001((a), (b)); \ - break; \ - case _MM_SHUFFLE(0, 1, 0, 1): \ - ret = _mm_shuffle_ps_0101((a), (b)); \ - break; \ - case _MM_SHUFFLE(3, 2, 1, 0): \ - ret = _mm_shuffle_ps_3210((a), (b)); \ - break; \ - case _MM_SHUFFLE(0, 0, 1, 1): \ - ret = _mm_shuffle_ps_0011((a), (b)); \ - break; \ - case _MM_SHUFFLE(0, 0, 2, 2): \ - ret = _mm_shuffle_ps_0022((a), (b)); \ - break; \ - case _MM_SHUFFLE(2, 2, 0, 0): \ - ret = _mm_shuffle_ps_2200((a), (b)); \ - break; \ - case _MM_SHUFFLE(3, 2, 0, 2): \ - ret = _mm_shuffle_ps_3202((a), (b)); \ - break; \ - case _MM_SHUFFLE(3, 2, 3, 2): \ - ret = _mm_movehl_ps((b), (a)); \ - break; \ - case _MM_SHUFFLE(1, 1, 3, 3): \ - ret = _mm_shuffle_ps_1133((a), (b)); \ - break; \ - case _MM_SHUFFLE(2, 0, 1, 0): \ - ret = _mm_shuffle_ps_2010((a), (b)); \ - break; \ - case _MM_SHUFFLE(2, 0, 0, 1): \ - ret = _mm_shuffle_ps_2001((a), (b)); \ - break; \ - case _MM_SHUFFLE(2, 0, 3, 2): \ - ret = _mm_shuffle_ps_2032((a), (b)); \ - break; \ - default: \ - ret = _mm_shuffle_ps_default((a), (b), (imm)); \ - break; \ - } \ - ret; \ - }) +// Load unaligned 16-bit integer from memory into the first element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadu_si16 +FORCE_INLINE __m128i _mm_loadu_si16(const void *p) +{ + return vreinterpretq_m128i_s16( + vsetq_lane_s16(*(const int16_t *) p, vdupq_n_s16(0), 0)); +} + +// Load unaligned 64-bit integer from memory into the first element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadu_si64 +FORCE_INLINE __m128i _mm_loadu_si64(const void *p) +{ + return vreinterpretq_m128i_s64( + vcombine_s64(vld1_s64((const int64_t *) p), vdup_n_s64(0))); +} + +// Allocate size bytes of memory, aligned to the alignment specified in align, +// and return a pointer to the allocated memory. _mm_free should be used to free +// memory that is allocated with _mm_malloc. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_malloc +#if !defined(SSE2NEON_ALLOC_DEFINED) +FORCE_INLINE void *_mm_malloc(size_t size, size_t align) +{ + void *ptr; + if (align == 1) + return malloc(size); + if (align == 2 || (sizeof(void *) == 8 && align == 4)) + align = sizeof(void *); + if (!posix_memalign(&ptr, align, size)) + return ptr; + return NULL; +} #endif -// Takes the upper 64 bits of a and places it in the low end of the result -// Takes the lower 64 bits of a and places it into the high end of the result. -FORCE_INLINE __m128i _mm_shuffle_epi_1032(__m128i a) +// Conditionally store 8-bit integer elements from a into memory using mask +// (elements are not stored when the highest bit is not set in the corresponding +// element) and a non-temporal memory hint. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maskmove_si64 +FORCE_INLINE void _mm_maskmove_si64(__m64 a, __m64 mask, char *mem_addr) { - int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a32, a10)); + int8x8_t shr_mask = vshr_n_s8(vreinterpret_s8_m64(mask), 7); + __m128 b = _mm_load_ps((const float *) mem_addr); + int8x8_t masked = + vbsl_s8(vreinterpret_u8_s8(shr_mask), vreinterpret_s8_m64(a), + vreinterpret_s8_u64(vget_low_u64(vreinterpretq_u64_m128(b)))); + vst1_s8((int8_t *) mem_addr, masked); } -// takes the lower two 32-bit values from a and swaps them and places in low end -// of result takes the higher two 32 bit values from a and swaps them and places -// in high end of result. -FORCE_INLINE __m128i _mm_shuffle_epi_2301(__m128i a) +// Conditionally store 8-bit integer elements from a into memory using mask +// (elements are not stored when the highest bit is not set in the corresponding +// element) and a non-temporal memory hint. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_maskmovq +#define _m_maskmovq(a, mask, mem_addr) _mm_maskmove_si64(a, mask, mem_addr) + +// Compare packed signed 16-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_pi16 +FORCE_INLINE __m64 _mm_max_pi16(__m64 a, __m64 b) { - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - int32x2_t a23 = vrev64_s32(vget_high_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a23)); + return vreinterpret_m64_s16( + vmax_s16(vreinterpret_s16_m64(a), vreinterpret_s16_m64(b))); } -// rotates the least significant 32 bits into the most signficant 32 bits, and -// shifts the rest down -FORCE_INLINE __m128i _mm_shuffle_epi_0321(__m128i a) +// Compare packed single-precision (32-bit) floating-point elements in a and b, +// and store packed maximum values in dst. dst does not follow the IEEE Standard +// for Floating-Point Arithmetic (IEEE 754) maximum value when inputs are NaN or +// signed-zero values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_ps +FORCE_INLINE __m128 _mm_max_ps(__m128 a, __m128 b) { - return vreinterpretq_m128i_s32( - vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 1)); +#if SSE2NEON_PRECISE_MINMAX + float32x4_t _a = vreinterpretq_f32_m128(a); + float32x4_t _b = vreinterpretq_f32_m128(b); + return vreinterpretq_m128_f32(vbslq_f32(vcgtq_f32(_a, _b), _a, _b)); +#else + return vreinterpretq_m128_f32( + vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); +#endif } -// rotates the most significant 32 bits into the least signficant 32 bits, and -// shifts the rest up -FORCE_INLINE __m128i _mm_shuffle_epi_2103(__m128i a) +// Compare packed unsigned 8-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_pu8 +FORCE_INLINE __m64 _mm_max_pu8(__m64 a, __m64 b) { - return vreinterpretq_m128i_s32( - vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 3)); + return vreinterpret_m64_u8( + vmax_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))); } -// gets the lower 64 bits of a, and places it in the upper 64 bits -// gets the lower 64 bits of a and places it in the lower 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_1010(__m128i a) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b, store the maximum value in the lower element of dst, and copy the upper 3 +// packed elements from a to the upper element of dst. dst does not follow the +// IEEE Standard for Floating-Point Arithmetic (IEEE 754) maximum value when +// inputs are NaN or signed-zero values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_ss +FORCE_INLINE __m128 _mm_max_ss(__m128 a, __m128 b) { - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a10, a10)); + float32_t value = vgetq_lane_f32(_mm_max_ps(a, b), 0); + return vreinterpretq_m128_f32( + vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); } -// gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the -// lower 64 bits gets the lower 64 bits of a, and places it in the upper 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_1001(__m128i a) +// Compare packed signed 16-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_pi16 +FORCE_INLINE __m64 _mm_min_pi16(__m64 a, __m64 b) { - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a10)); + return vreinterpret_m64_s16( + vmin_s16(vreinterpret_s16_m64(a), vreinterpret_s16_m64(b))); } -// gets the lower 64 bits of a, swaps the 0 and 1 elements and places it in the -// upper 64 bits gets the lower 64 bits of a, swaps the 0 and 1 elements, and -// places it in the lower 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_0101(__m128i a) +// Compare packed single-precision (32-bit) floating-point elements in a and b, +// and store packed minimum values in dst. dst does not follow the IEEE Standard +// for Floating-Point Arithmetic (IEEE 754) minimum value when inputs are NaN or +// signed-zero values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_ps +FORCE_INLINE __m128 _mm_min_ps(__m128 a, __m128 b) { - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a01)); +#if SSE2NEON_PRECISE_MINMAX + float32x4_t _a = vreinterpretq_f32_m128(a); + float32x4_t _b = vreinterpretq_f32_m128(b); + return vreinterpretq_m128_f32(vbslq_f32(vcltq_f32(_a, _b), _a, _b)); +#else + return vreinterpretq_m128_f32( + vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); +#endif } -FORCE_INLINE __m128i _mm_shuffle_epi_2211(__m128i a) +// Compare packed unsigned 8-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_pu8 +FORCE_INLINE __m64 _mm_min_pu8(__m64 a, __m64 b) { - int32x2_t a11 = vdup_lane_s32(vget_low_s32(vreinterpretq_s32_m128i(a)), 1); - int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); - return vreinterpretq_m128i_s32(vcombine_s32(a11, a22)); + return vreinterpret_m64_u8( + vmin_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))); } -FORCE_INLINE __m128i _mm_shuffle_epi_0122(__m128i a) +// Compare the lower single-precision (32-bit) floating-point elements in a and +// b, store the minimum value in the lower element of dst, and copy the upper 3 +// packed elements from a to the upper element of dst. dst does not follow the +// IEEE Standard for Floating-Point Arithmetic (IEEE 754) minimum value when +// inputs are NaN or signed-zero values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_ss +FORCE_INLINE __m128 _mm_min_ss(__m128 a, __m128 b) { - int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a22, a01)); + float32_t value = vgetq_lane_f32(_mm_min_ps(a, b), 0); + return vreinterpretq_m128_f32( + vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); } -FORCE_INLINE __m128i _mm_shuffle_epi_3332(__m128i a) +// Move the lower single-precision (32-bit) floating-point element from b to the +// lower element of dst, and copy the upper 3 packed elements from a to the +// upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_move_ss +FORCE_INLINE __m128 _mm_move_ss(__m128 a, __m128 b) { - int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t a33 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 1); - return vreinterpretq_m128i_s32(vcombine_s32(a32, a33)); + return vreinterpretq_m128_f32( + vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(b), 0), + vreinterpretq_f32_m128(a), 0)); } -// Shuffle packed 8-bit integers in a according to shuffle control mask in the -// corresponding 8-bit element of b, and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_shuffle_epi8 -FORCE_INLINE __m128i _mm_shuffle_epi8(__m128i a, __m128i b) +// Move the upper 2 single-precision (32-bit) floating-point elements from b to +// the lower 2 elements of dst, and copy the upper 2 elements from a to the +// upper 2 elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movehl_ps +FORCE_INLINE __m128 _mm_movehl_ps(__m128 a, __m128 b) { - int8x16_t tbl = vreinterpretq_s8_m128i(a); // input a - uint8x16_t idx = vreinterpretq_u8_m128i(b); // input b - uint8x16_t idx_masked = - vandq_u8(idx, vdupq_n_u8(0x8F)); // avoid using meaningless bits -#if defined(__aarch64__) - return vreinterpretq_m128i_s8(vqtbl1q_s8(tbl, idx_masked)); -#elif defined(__GNUC__) - int8x16_t ret; - // %e and %f represent the even and odd D registers - // respectively. - __asm__ __volatile__( - "vtbl.8 %e[ret], {%e[tbl], %f[tbl]}, %e[idx]\n" - "vtbl.8 %f[ret], {%e[tbl], %f[tbl]}, %f[idx]\n" - : [ret] "=&w"(ret) - : [tbl] "w"(tbl), [idx] "w"(idx_masked)); - return vreinterpretq_m128i_s8(ret); +#if defined(aarch64__) + return vreinterpretq_m128_u64( + vzip2q_u64(vreinterpretq_u64_m128(b), vreinterpretq_u64_m128(a))); #else - // use this line if testing on aarch64 - int8x8x2_t a_split = {vget_low_s8(tbl), vget_high_s8(tbl)}; - return vreinterpretq_m128i_s8( - vcombine_s8(vtbl2_s8(a_split, vget_low_u8(idx_masked)), - vtbl2_s8(a_split, vget_high_u8(idx_masked)))); + float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); + float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_f32(vcombine_f32(b32, a32)); #endif } -// C equivalent: -// __m128i _mm_shuffle_epi32_default(__m128i a, -// __constrange(0, 255) int imm) { -// __m128i ret; -// ret[0] = a[imm & 0x3]; ret[1] = a[(imm >> 2) & 0x3]; -// ret[2] = a[(imm >> 4) & 0x03]; ret[3] = a[(imm >> 6) & 0x03]; -// return ret; -// } -#define _mm_shuffle_epi32_default(a, imm) \ - __extension__({ \ - int32x4_t ret; \ - ret = vmovq_n_s32( \ - vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm) & (0x3))); \ - ret = vsetq_lane_s32( \ - vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 2) & 0x3), \ - ret, 1); \ - ret = vsetq_lane_s32( \ - vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 4) & 0x3), \ - ret, 2); \ - ret = vsetq_lane_s32( \ - vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 6) & 0x3), \ - ret, 3); \ - vreinterpretq_m128i_s32(ret); \ - }) +// Move the lower 2 single-precision (32-bit) floating-point elements from b to +// the upper 2 elements of dst, and copy the lower 2 elements from a to the +// lower 2 elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movelh_ps +FORCE_INLINE __m128 _mm_movelh_ps(__m128 __A, __m128 __B) +{ + float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(__A)); + float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(__B)); + return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); +} -// FORCE_INLINE __m128i _mm_shuffle_epi32_splat(__m128i a, __constrange(0,255) -// int imm) -#if defined(__aarch64__) -#define _mm_shuffle_epi32_splat(a, imm) \ - __extension__({ \ - vreinterpretq_m128i_s32( \ - vdupq_laneq_s32(vreinterpretq_s32_m128i(a), (imm))); \ - }) +// Create mask from the most significant bit of each 8-bit element in a, and +// store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movemask_pi8 +FORCE_INLINE int _mm_movemask_pi8(__m64 a) +{ + uint8x8_t input = vreinterpret_u8_m64(a); +#if defined(__aarch64__) || defined(_M_ARM64) + static const int8_t shift[8] = {0, 1, 2, 3, 4, 5, 6, 7}; + uint8x8_t tmp = vshr_n_u8(input, 7); + return vaddv_u8(vshl_u8(tmp, vld1_s8(shift))); #else -#define _mm_shuffle_epi32_splat(a, imm) \ - __extension__({ \ - vreinterpretq_m128i_s32( \ - vdupq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)))); \ - }) + // Refer the implementation of `_mm_movemask_epi8` + uint16x4_t high_bits = vreinterpret_u16_u8(vshr_n_u8(input, 7)); + uint32x2_t paired16 = + vreinterpret_u32_u16(vsra_n_u16(high_bits, high_bits, 7)); + uint8x8_t paired32 = + vreinterpret_u8_u32(vsra_n_u32(paired16, paired16, 14)); + return vget_lane_u8(paired32, 0) | ((int) vget_lane_u8(paired32, 4) << 4); #endif +} -// Shuffles the 4 signed or unsigned 32-bit integers in a as specified by imm. -// https://msdn.microsoft.com/en-us/library/56f67xbk%28v=vs.90%29.aspx -// FORCE_INLINE __m128i _mm_shuffle_epi32(__m128i a, -// __constrange(0,255) int imm) -#if __has_builtin(__builtin_shufflevector) -#define _mm_shuffle_epi32(a, imm) \ - __extension__({ \ - int32x4_t _input = vreinterpretq_s32_m128i(a); \ - int32x4_t _shuf = __builtin_shufflevector( \ - _input, _input, (imm) & (0x3), ((imm) >> 2) & 0x3, \ - ((imm) >> 4) & 0x3, ((imm) >> 6) & 0x3); \ - vreinterpretq_m128i_s32(_shuf); \ - }) -#else // generic -#define _mm_shuffle_epi32(a, imm) \ - __extension__({ \ - __m128i ret; \ - switch (imm) { \ - case _MM_SHUFFLE(1, 0, 3, 2): \ - ret = _mm_shuffle_epi_1032((a)); \ - break; \ - case _MM_SHUFFLE(2, 3, 0, 1): \ - ret = _mm_shuffle_epi_2301((a)); \ - break; \ - case _MM_SHUFFLE(0, 3, 2, 1): \ - ret = _mm_shuffle_epi_0321((a)); \ - break; \ - case _MM_SHUFFLE(2, 1, 0, 3): \ - ret = _mm_shuffle_epi_2103((a)); \ - break; \ - case _MM_SHUFFLE(1, 0, 1, 0): \ - ret = _mm_shuffle_epi_1010((a)); \ - break; \ - case _MM_SHUFFLE(1, 0, 0, 1): \ - ret = _mm_shuffle_epi_1001((a)); \ - break; \ - case _MM_SHUFFLE(0, 1, 0, 1): \ - ret = _mm_shuffle_epi_0101((a)); \ - break; \ - case _MM_SHUFFLE(2, 2, 1, 1): \ - ret = _mm_shuffle_epi_2211((a)); \ - break; \ - case _MM_SHUFFLE(0, 1, 2, 2): \ - ret = _mm_shuffle_epi_0122((a)); \ - break; \ - case _MM_SHUFFLE(3, 3, 3, 2): \ - ret = _mm_shuffle_epi_3332((a)); \ - break; \ - case _MM_SHUFFLE(0, 0, 0, 0): \ - ret = _mm_shuffle_epi32_splat((a), 0); \ - break; \ - case _MM_SHUFFLE(1, 1, 1, 1): \ - ret = _mm_shuffle_epi32_splat((a), 1); \ - break; \ - case _MM_SHUFFLE(2, 2, 2, 2): \ - ret = _mm_shuffle_epi32_splat((a), 2); \ - break; \ - case _MM_SHUFFLE(3, 3, 3, 3): \ - ret = _mm_shuffle_epi32_splat((a), 3); \ - break; \ - default: \ - ret = _mm_shuffle_epi32_default((a), (imm)); \ - break; \ - } \ - ret; \ - }) +// Set each bit of mask dst based on the most significant bit of the +// corresponding packed single-precision (32-bit) floating-point element in a. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movemask_ps +FORCE_INLINE int _mm_movemask_ps(__m128 a) +{ + uint32x4_t input = vreinterpretq_u32_m128(a); +#if defined(__aarch64__) || defined(_M_ARM64) + static const int32_t shift[4] = {0, 1, 2, 3}; + uint32x4_t tmp = vshrq_n_u32(input, 31); + return vaddvq_u32(vshlq_u32(tmp, vld1q_s32(shift))); +#else + // Uses the exact same method as _mm_movemask_epi8, see that for details. + // Shift out everything but the sign bits with a 32-bit unsigned shift + // right. + uint64x2_t high_bits = vreinterpretq_u64_u32(vshrq_n_u32(input, 31)); + // Merge the two pairs together with a 64-bit unsigned shift right + add. + uint8x16_t paired = + vreinterpretq_u8_u64(vsraq_n_u64(high_bits, high_bits, 31)); + // Extract the result. + return vgetq_lane_u8(paired, 0) | (vgetq_lane_u8(paired, 8) << 2); #endif +} -// Shuffles the lower 4 signed or unsigned 16-bit integers in a as specified -// by imm. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/y41dkk37(v=vs.100) -// FORCE_INLINE __m128i _mm_shufflelo_epi16_function(__m128i a, -// __constrange(0,255) int -// imm) -#define _mm_shufflelo_epi16_function(a, imm) \ - __extension__({ \ - int16x8_t ret = vreinterpretq_s16_m128i(a); \ - int16x4_t lowBits = vget_low_s16(ret); \ - ret = vsetq_lane_s16(vget_lane_s16(lowBits, (imm) & (0x3)), ret, 0); \ - ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 2) & 0x3), ret, \ - 1); \ - ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 4) & 0x3), ret, \ - 2); \ - ret = vsetq_lane_s16(vget_lane_s16(lowBits, ((imm) >> 6) & 0x3), ret, \ - 3); \ - vreinterpretq_m128i_s16(ret); \ - }) +// Multiply packed single-precision (32-bit) floating-point elements in a and b, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mul_ps +FORCE_INLINE __m128 _mm_mul_ps(__m128 a, __m128 b) +{ + return vreinterpretq_m128_f32( + vmulq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); +} -// FORCE_INLINE __m128i _mm_shufflelo_epi16(__m128i a, -// __constrange(0,255) int imm) -#if __has_builtin(__builtin_shufflevector) -#define _mm_shufflelo_epi16(a, imm) \ - __extension__({ \ - int16x8_t _input = vreinterpretq_s16_m128i(a); \ - int16x8_t _shuf = __builtin_shufflevector( \ - _input, _input, ((imm) & (0x3)), (((imm) >> 2) & 0x3), \ - (((imm) >> 4) & 0x3), (((imm) >> 6) & 0x3), 4, 5, 6, 7); \ - vreinterpretq_m128i_s16(_shuf); \ - }) -#else // generic -#define _mm_shufflelo_epi16(a, imm) _mm_shufflelo_epi16_function((a), (imm)) -#endif +// Multiply the lower single-precision (32-bit) floating-point element in a and +// b, store the result in the lower element of dst, and copy the upper 3 packed +// elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mul_ss +FORCE_INLINE __m128 _mm_mul_ss(__m128 a, __m128 b) +{ + return _mm_move_ss(a, _mm_mul_ps(a, b)); +} -// Shuffles the upper 4 signed or unsigned 16-bit integers in a as specified -// by imm. -// https://msdn.microsoft.com/en-us/library/13ywktbs(v=vs.100).aspx -// FORCE_INLINE __m128i _mm_shufflehi_epi16_function(__m128i a, -// __constrange(0,255) int -// imm) -#define _mm_shufflehi_epi16_function(a, imm) \ - __extension__({ \ - int16x8_t ret = vreinterpretq_s16_m128i(a); \ - int16x4_t highBits = vget_high_s16(ret); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, (imm) & (0x3)), ret, 4); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 2) & 0x3), ret, \ - 5); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 4) & 0x3), ret, \ - 6); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 6) & 0x3), ret, \ - 7); \ - vreinterpretq_m128i_s16(ret); \ - }) +// Multiply the packed unsigned 16-bit integers in a and b, producing +// intermediate 32-bit integers, and store the high 16 bits of the intermediate +// integers in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mulhi_pu16 +FORCE_INLINE __m64 _mm_mulhi_pu16(__m64 a, __m64 b) +{ + return vreinterpret_m64_u16(vshrn_n_u32( + vmull_u16(vreinterpret_u16_m64(a), vreinterpret_u16_m64(b)), 16)); +} -// FORCE_INLINE __m128i _mm_shufflehi_epi16(__m128i a, -// __constrange(0,255) int imm) -#if __has_builtin(__builtin_shufflevector) -#define _mm_shufflehi_epi16(a, imm) \ - __extension__({ \ - int16x8_t _input = vreinterpretq_s16_m128i(a); \ - int16x8_t _shuf = __builtin_shufflevector( \ - _input, _input, 0, 1, 2, 3, ((imm) & (0x3)) + 4, \ - (((imm) >> 2) & 0x3) + 4, (((imm) >> 4) & 0x3) + 4, \ - (((imm) >> 6) & 0x3) + 4); \ - vreinterpretq_m128i_s16(_shuf); \ - }) -#else // generic -#define _mm_shufflehi_epi16(a, imm) _mm_shufflehi_epi16_function((a), (imm)) -#endif +// Compute the bitwise OR of packed single-precision (32-bit) floating-point +// elements in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_or_ps +FORCE_INLINE __m128 _mm_or_ps(__m128 a, __m128 b) +{ + return vreinterpretq_m128_s32( + vorrq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); +} -// Blend packed 16-bit integers from a and b using control mask imm8, and store -// the results in dst. -// -// FOR j := 0 to 7 -// i := j*16 -// IF imm8[j] -// dst[i+15:i] := b[i+15:i] -// ELSE -// dst[i+15:i] := a[i+15:i] -// FI -// ENDFOR -// FORCE_INLINE __m128i _mm_blend_epi16(__m128i a, __m128i b, -// __constrange(0,255) int imm) -#define _mm_blend_epi16(a, b, imm) \ - __extension__({ \ - const uint16_t _mask[8] = {((imm) & (1 << 0)) ? 0xFFFF : 0x0000, \ - ((imm) & (1 << 1)) ? 0xFFFF : 0x0000, \ - ((imm) & (1 << 2)) ? 0xFFFF : 0x0000, \ - ((imm) & (1 << 3)) ? 0xFFFF : 0x0000, \ - ((imm) & (1 << 4)) ? 0xFFFF : 0x0000, \ - ((imm) & (1 << 5)) ? 0xFFFF : 0x0000, \ - ((imm) & (1 << 6)) ? 0xFFFF : 0x0000, \ - ((imm) & (1 << 7)) ? 0xFFFF : 0x0000}; \ - uint16x8_t _mask_vec = vld1q_u16(_mask); \ - uint16x8_t _a = vreinterpretq_u16_m128i(a); \ - uint16x8_t _b = vreinterpretq_u16_m128i(b); \ - vreinterpretq_m128i_u16(vbslq_u16(_mask_vec, _b, _a)); \ - }) +// Average packed unsigned 8-bit integers in a and b, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pavgb +#define _m_pavgb(a, b) _mm_avg_pu8(a, b) -// Blend packed 8-bit integers from a and b using mask, and store the results in +// Average packed unsigned 16-bit integers in a and b, and store the results in // dst. -// -// FOR j := 0 to 15 -// i := j*8 -// IF mask[i+7] -// dst[i+7:i] := b[i+7:i] -// ELSE -// dst[i+7:i] := a[i+7:i] -// FI -// ENDFOR -FORCE_INLINE __m128i _mm_blendv_epi8(__m128i _a, __m128i _b, __m128i _mask) -{ - // Use a signed shift right to create a mask with the sign bit - uint8x16_t mask = - vreinterpretq_u8_s8(vshrq_n_s8(vreinterpretq_s8_m128i(_mask), 7)); - uint8x16_t a = vreinterpretq_u8_m128i(_a); - uint8x16_t b = vreinterpretq_u8_m128i(_b); - return vreinterpretq_m128i_u8(vbslq_u8(mask, b, a)); -} +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pavgw +#define _m_pavgw(a, b) _mm_avg_pu16(a, b) -/* Shifts */ +// Extract a 16-bit integer from a, selected with imm8, and store the result in +// the lower element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pextrw +#define _m_pextrw(a, imm) _mm_extract_pi16(a, imm) +// Copy a to dst, and insert the 16-bit integer i into dst at the location +// specified by imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=m_pinsrw +#define _m_pinsrw(a, i, imm) _mm_insert_pi16(a, i, imm) -// Shift packed 16-bit integers in a right by imm while shifting in sign -// bits, and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_srai_epi16 -FORCE_INLINE __m128i _mm_srai_epi16(__m128i a, int imm) +// Compare packed signed 16-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pmaxsw +#define _m_pmaxsw(a, b) _mm_max_pi16(a, b) + +// Compare packed unsigned 8-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pmaxub +#define _m_pmaxub(a, b) _mm_max_pu8(a, b) + +// Compare packed signed 16-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pminsw +#define _m_pminsw(a, b) _mm_min_pi16(a, b) + +// Compare packed unsigned 8-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pminub +#define _m_pminub(a, b) _mm_min_pu8(a, b) + +// Create mask from the most significant bit of each 8-bit element in a, and +// store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pmovmskb +#define _m_pmovmskb(a) _mm_movemask_pi8(a) + +// Multiply the packed unsigned 16-bit integers in a and b, producing +// intermediate 32-bit integers, and store the high 16 bits of the intermediate +// integers in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pmulhuw +#define _m_pmulhuw(a, b) _mm_mulhi_pu16(a, b) + +// Fetch the line of data from memory that contains address p to a location in +// the cache hierarchy specified by the locality hint i. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_prefetch +FORCE_INLINE void _mm_prefetch(char const *p, int i) { - const int count = (imm & ~15) ? 15 : imm; - return (__m128i) vshlq_s16((int16x8_t) a, vdupq_n_s16(-count)); + (void) i; +#if defined(_MSC_VER) + switch (i) { + case _MM_HINT_NTA: + __prefetch2(p, 1); + break; + case _MM_HINT_T0: + __prefetch2(p, 0); + break; + case _MM_HINT_T1: + __prefetch2(p, 2); + break; + case _MM_HINT_T2: + __prefetch2(p, 4); + break; + } +#else + switch (i) { + case _MM_HINT_NTA: + __builtin_prefetch(p, 0, 0); + break; + case _MM_HINT_T0: + __builtin_prefetch(p, 0, 3); + break; + case _MM_HINT_T1: + __builtin_prefetch(p, 0, 2); + break; + case _MM_HINT_T2: + __builtin_prefetch(p, 0, 1); + break; + } +#endif } -// Shifts the 8 signed or unsigned 16-bit integers in a left by count bits while -// shifting in zeros. -// -// r0 := a0 << count -// r1 := a1 << count -// ... -// r7 := a7 << count -// -// https://msdn.microsoft.com/en-us/library/es73bcsy(v=vs.90).aspx -#define _mm_slli_epi16(a, imm) \ - __extension__({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } else if ((imm) > 15) { \ - ret = _mm_setzero_si128(); \ - } else { \ - ret = vreinterpretq_m128i_s16( \ - vshlq_n_s16(vreinterpretq_s16_m128i(a), (imm))); \ - } \ - ret; \ - }) +// Compute the absolute differences of packed unsigned 8-bit integers in a and +// b, then horizontally sum each consecutive 8 differences to produce four +// unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low +// 16 bits of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=m_psadbw +#define _m_psadbw(a, b) _mm_sad_pu8(a, b) -// Shifts the 4 signed or unsigned 32-bit integers in a left by count bits while -// shifting in zeros. : -// https://msdn.microsoft.com/en-us/library/z2k3bbtb%28v=vs.90%29.aspx -// FORCE_INLINE __m128i _mm_slli_epi32(__m128i a, __constrange(0,255) int imm) -FORCE_INLINE __m128i _mm_slli_epi32(__m128i a, int imm) +// Shuffle 16-bit integers in a using the control in imm8, and store the results +// in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_m_pshufw +#define _m_pshufw(a, imm) _mm_shuffle_pi16(a, imm) + +// Compute the approximate reciprocal of packed single-precision (32-bit) +// floating-point elements in a, and store the results in dst. The maximum +// relative error for this approximation is less than 1.5*2^-12. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_rcp_ps +FORCE_INLINE __m128 _mm_rcp_ps(__m128 in) { - if (imm <= 0) /* TODO: add constant range macro: [0, 255] */ - return a; - if (imm > 31) /* TODO: add unlikely macro */ - return _mm_setzero_si128(); - return vreinterpretq_m128i_s32( - vshlq_s32(vreinterpretq_s32_m128i(a), vdupq_n_s32(imm))); + float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); + recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); + return vreinterpretq_m128_f32(recip); } -// Shift packed 64-bit integers in a left by imm8 while shifting in zeros, and -// store the results in dst. -FORCE_INLINE __m128i _mm_slli_epi64(__m128i a, int imm) +// Compute the approximate reciprocal of the lower single-precision (32-bit) +// floating-point element in a, store the result in the lower element of dst, +// and copy the upper 3 packed elements from a to the upper elements of dst. The +// maximum relative error for this approximation is less than 1.5*2^-12. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_rcp_ss +FORCE_INLINE __m128 _mm_rcp_ss(__m128 a) { - if (imm <= 0) /* TODO: add constant range macro: [0, 255] */ - return a; - if (imm > 63) /* TODO: add unlikely macro */ - return _mm_setzero_si128(); - return vreinterpretq_m128i_s64( - vshlq_s64(vreinterpretq_s64_m128i(a), vdupq_n_s64(imm))); + return _mm_move_ss(a, _mm_rcp_ps(a)); } -// Shift packed 16-bit integers in a right by imm8 while shifting in zeros, and -// store the results in dst. -// -// FOR j := 0 to 7 -// i := j*16 -// IF imm8[7:0] > 15 -// dst[i+15:i] := 0 -// ELSE -// dst[i+15:i] := ZeroExtend16(a[i+15:i] >> imm8[7:0]) -// FI -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_srli_epi16 -#define _mm_srli_epi16(a, imm) \ - __extension__({ \ - __m128i ret; \ - if ((imm) == 0) { \ - ret = a; \ - } else if (0 < (imm) && (imm) < 16) { \ - ret = vreinterpretq_m128i_u16( \ - vshlq_u16(vreinterpretq_u16_m128i(a), vdupq_n_s16(-imm))); \ - } else { \ - ret = _mm_setzero_si128(); \ - } \ - ret; \ - }) - -// Shift packed 32-bit integers in a right by imm8 while shifting in zeros, and -// store the results in dst. -// -// FOR j := 0 to 3 -// i := j*32 -// IF imm8[7:0] > 31 -// dst[i+31:i] := 0 -// ELSE -// dst[i+31:i] := ZeroExtend32(a[i+31:i] >> imm8[7:0]) -// FI -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_srli_epi32 -// FORCE_INLINE __m128i _mm_srli_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_srli_epi32(a, imm) \ - __extension__({ \ - __m128i ret; \ - if ((imm) == 0) { \ - ret = a; \ - } else if (0 < (imm) && (imm) < 32) { \ - ret = vreinterpretq_m128i_u32( \ - vshlq_u32(vreinterpretq_u32_m128i(a), vdupq_n_s32(-imm))); \ - } else { \ - ret = _mm_setzero_si128(); \ - } \ - ret; \ - }) +// Compute the approximate reciprocal square root of packed single-precision +// (32-bit) floating-point elements in a, and store the results in dst. The +// maximum relative error for this approximation is less than 1.5*2^-12. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_rsqrt_ps +FORCE_INLINE __m128 _mm_rsqrt_ps(__m128 in) +{ + float32x4_t out = vrsqrteq_f32(vreinterpretq_f32_m128(in)); -// Shift packed 64-bit integers in a right by imm8 while shifting in zeros, and -// store the results in dst. -// -// FOR j := 0 to 1 -// i := j*64 -// IF imm8[7:0] > 63 -// dst[i+63:i] := 0 -// ELSE -// dst[i+63:i] := ZeroExtend64(a[i+63:i] >> imm8[7:0]) -// FI -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_srli_epi64 -#define _mm_srli_epi64(a, imm) \ - __extension__({ \ - __m128i ret; \ - if ((imm) == 0) { \ - ret = a; \ - } else if (0 < (imm) && (imm) < 64) { \ - ret = vreinterpretq_m128i_u64( \ - vshlq_u64(vreinterpretq_u64_m128i(a), vdupq_n_s64(-imm))); \ - } else { \ - ret = _mm_setzero_si128(); \ - } \ - ret; \ - }) + // Generate masks for detecting whether input has any 0.0f/-0.0f + // (which becomes positive/negative infinity by IEEE-754 arithmetic rules). + const uint32x4_t pos_inf = vdupq_n_u32(0x7F800000); + const uint32x4_t neg_inf = vdupq_n_u32(0xFF800000); + const uint32x4_t has_pos_zero = + vceqq_u32(pos_inf, vreinterpretq_u32_f32(out)); + const uint32x4_t has_neg_zero = + vceqq_u32(neg_inf, vreinterpretq_u32_f32(out)); -// Shift packed 32-bit integers in a right by imm8 while shifting in sign bits, -// and store the results in dst. -// -// FOR j := 0 to 3 -// i := j*32 -// IF imm8[7:0] > 31 -// dst[i+31:i] := (a[i+31] ? 0xFFFFFFFF : 0x0) -// ELSE -// dst[i+31:i] := SignExtend32(a[i+31:i] >> imm8[7:0]) -// FI -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_srai_epi32 -// FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_srai_epi32(a, imm) \ - __extension__({ \ - __m128i ret; \ - if ((imm) == 0) { \ - ret = a; \ - } else if (0 < (imm) && (imm) < 32) { \ - ret = vreinterpretq_m128i_s32( \ - vshlq_s32(vreinterpretq_s32_m128i(a), vdupq_n_s32(-imm))); \ - } else { \ - ret = vreinterpretq_m128i_s32( \ - vshrq_n_s32(vreinterpretq_s32_m128i(a), 31)); \ - } \ - ret; \ - }) + out = vmulq_f32( + out, vrsqrtsq_f32(vmulq_f32(vreinterpretq_f32_m128(in), out), out)); -// Shifts the 128 - bit value in a right by imm bytes while shifting in -// zeros.imm must be an immediate. -// -// r := srl(a, imm*8) -// -// https://msdn.microsoft.com/en-us/library/305w28yz(v=vs.100).aspx -// FORCE_INLINE _mm_srli_si128(__m128i a, __constrange(0,255) int imm) -#define _mm_srli_si128(a, imm) \ - __extension__({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } else if ((imm) > 15) { \ - ret = _mm_setzero_si128(); \ - } else { \ - ret = vreinterpretq_m128i_s8( \ - vextq_s8(vreinterpretq_s8_m128i(a), vdupq_n_s8(0), (imm))); \ - } \ - ret; \ - }) + // Set output vector element to infinity/negative-infinity if + // the corresponding input vector element is 0.0f/-0.0f. + out = vbslq_f32(has_pos_zero, (float32x4_t) pos_inf, out); + out = vbslq_f32(has_neg_zero, (float32x4_t) neg_inf, out); -// Shifts the 128-bit value in a left by imm bytes while shifting in zeros. imm -// must be an immediate. -// -// r := a << (imm * 8) -// -// https://msdn.microsoft.com/en-us/library/34d3k2kt(v=vs.100).aspx -// FORCE_INLINE __m128i _mm_slli_si128(__m128i a, __constrange(0,255) int imm) -#define _mm_slli_si128(a, imm) \ - __extension__({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } else if ((imm) > 15) { \ - ret = _mm_setzero_si128(); \ - } else { \ - ret = vreinterpretq_m128i_s8(vextq_s8( \ - vdupq_n_s8(0), vreinterpretq_s8_m128i(a), 16 - (imm))); \ - } \ - ret; \ - }) + return vreinterpretq_m128_f32(out); +} -// Shifts the 8 signed or unsigned 16-bit integers in a left by count bits while -// shifting in zeros. -// -// r0 := a0 << count -// r1 := a1 << count -// ... -// r7 := a7 << count -// -// https://msdn.microsoft.com/en-us/library/c79w388h(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_sll_epi16(__m128i a, __m128i count) +// Compute the approximate reciprocal square root of the lower single-precision +// (32-bit) floating-point element in a, store the result in the lower element +// of dst, and copy the upper 3 packed elements from a to the upper elements of +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_rsqrt_ss +FORCE_INLINE __m128 _mm_rsqrt_ss(__m128 in) { - uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); - if (c > 15) - return _mm_setzero_si128(); + return vsetq_lane_f32(vgetq_lane_f32(_mm_rsqrt_ps(in), 0), in, 0); +} - int16x8_t vc = vdupq_n_s16((int16_t) c); - return vreinterpretq_m128i_s16(vshlq_s16(vreinterpretq_s16_m128i(a), vc)); +// Compute the absolute differences of packed unsigned 8-bit integers in a and +// b, then horizontally sum each consecutive 8 differences to produce four +// unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low +// 16 bits of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sad_pu8 +FORCE_INLINE __m64 _mm_sad_pu8(__m64 a, __m64 b) +{ + uint64x1_t t = vpaddl_u32(vpaddl_u16( + vpaddl_u8(vabd_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))))); + return vreinterpret_m64_u16( + vset_lane_u16((int) vget_lane_u64(t, 0), vdup_n_u16(0), 0)); } -// Shifts the 4 signed or unsigned 32-bit integers in a left by count bits while -// shifting in zeros. -// -// r0 := a0 << count -// r1 := a1 << count -// r2 := a2 << count -// r3 := a3 << count -// -// https://msdn.microsoft.com/en-us/library/6fe5a6s9(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_sll_epi32(__m128i a, __m128i count) +// Macro: Set the flush zero bits of the MXCSR control and status register to +// the value in unsigned 32-bit integer a. The flush zero may contain any of the +// following flags: _MM_FLUSH_ZERO_ON or _MM_FLUSH_ZERO_OFF +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_MM_SET_FLUSH_ZERO_MODE +FORCE_INLINE void _sse2neon_mm_set_flush_zero_mode(unsigned int flag) { - uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); - if (c > 31) - return _mm_setzero_si128(); + // AArch32 Advanced SIMD arithmetic always uses the Flush-to-zero setting, + // regardless of the value of the FZ bit. + union { + fpcr_bitfield field; +#if defined(__aarch64__) || defined(_M_ARM64) + uint64_t value; +#else + uint32_t value; +#endif + } r; - int32x4_t vc = vdupq_n_s32((int32_t) c); - return vreinterpretq_m128i_s32(vshlq_s32(vreinterpretq_s32_m128i(a), vc)); +#if defined(__aarch64__) || defined(_M_ARM64) + r.value = _sse2neon_get_fpcr(); +#else + __asm__ __volatile__("vmrs %0, FPSCR" : "=r"(r.value)); /* read */ +#endif + + r.field.bit24 = (flag & _MM_FLUSH_ZERO_MASK) == _MM_FLUSH_ZERO_ON; + +#if defined(__aarch64__) || defined(_M_ARM64) + _sse2neon_set_fpcr(r.value); +#else + __asm__ __volatile__("vmsr FPSCR, %0" ::"r"(r)); /* write */ +#endif } -// Shifts the 2 signed or unsigned 64-bit integers in a left by count bits while -// shifting in zeros. -// -// r0 := a0 << count -// r1 := a1 << count -// -// https://msdn.microsoft.com/en-us/library/6ta9dffd(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_sll_epi64(__m128i a, __m128i count) +// Set packed single-precision (32-bit) floating-point elements in dst with the +// supplied values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_ps +FORCE_INLINE __m128 _mm_set_ps(float w, float z, float y, float x) { - uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); - if (c > 63) - return _mm_setzero_si128(); + float ALIGN_STRUCT(16) data[4] = {x, y, z, w}; + return vreinterpretq_m128_f32(vld1q_f32(data)); +} - int64x2_t vc = vdupq_n_s64((int64_t) c); - return vreinterpretq_m128i_s64(vshlq_s64(vreinterpretq_s64_m128i(a), vc)); +// Broadcast single-precision (32-bit) floating-point value a to all elements of +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_ps1 +FORCE_INLINE __m128 _mm_set_ps1(float _w) +{ + return vreinterpretq_m128_f32(vdupq_n_f32(_w)); } -// Shifts the 8 signed or unsigned 16-bit integers in a right by count bits -// while shifting in zeros. -// -// r0 := srl(a0, count) -// r1 := srl(a1, count) -// ... -// r7 := srl(a7, count) -// -// https://msdn.microsoft.com/en-us/library/wd5ax830(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_srl_epi16(__m128i a, __m128i count) +// Macro: Set the rounding mode bits of the MXCSR control and status register to +// the value in unsigned 32-bit integer a. The rounding mode may contain any of +// the following flags: _MM_ROUND_NEAREST, _MM_ROUND_DOWN, _MM_ROUND_UP, +// _MM_ROUND_TOWARD_ZERO +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_MM_SET_ROUNDING_MODE +FORCE_INLINE void _MM_SET_ROUNDING_MODE(int rounding) { - uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); - if (c > 15) - return _mm_setzero_si128(); + union { + fpcr_bitfield field; +#if defined(__aarch64__) || defined(_M_ARM64) + uint64_t value; +#else + uint32_t value; +#endif + } r; - int16x8_t vc = vdupq_n_s16(-(int16_t) c); - return vreinterpretq_m128i_u16(vshlq_u16(vreinterpretq_u16_m128i(a), vc)); +#if defined(__aarch64__) || defined(_M_ARM64) + r.value = _sse2neon_get_fpcr(); +#else + __asm__ __volatile__("vmrs %0, FPSCR" : "=r"(r.value)); /* read */ +#endif + + switch (rounding) { + case _MM_ROUND_TOWARD_ZERO: + r.field.bit22 = 1; + r.field.bit23 = 1; + break; + case _MM_ROUND_DOWN: + r.field.bit22 = 0; + r.field.bit23 = 1; + break; + case _MM_ROUND_UP: + r.field.bit22 = 1; + r.field.bit23 = 0; + break; + default: //_MM_ROUND_NEAREST + r.field.bit22 = 0; + r.field.bit23 = 0; + } + +#if defined(__aarch64__) || defined(_M_ARM64) + _sse2neon_set_fpcr(r.value); +#else + __asm__ __volatile__("vmsr FPSCR, %0" ::"r"(r)); /* write */ +#endif } -// Shifts the 4 signed or unsigned 32-bit integers in a right by count bits -// while shifting in zeros. -// -// r0 := srl(a0, count) -// r1 := srl(a1, count) -// r2 := srl(a2, count) -// r3 := srl(a3, count) -// -// https://msdn.microsoft.com/en-us/library/a9cbttf4(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_srl_epi32(__m128i a, __m128i count) +// Copy single-precision (32-bit) floating-point element a to the lower element +// of dst, and zero the upper 3 elements. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_ss +FORCE_INLINE __m128 _mm_set_ss(float a) { - uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); - if (c > 31) - return _mm_setzero_si128(); + return vreinterpretq_m128_f32(vsetq_lane_f32(a, vdupq_n_f32(0), 0)); +} - int32x4_t vc = vdupq_n_s32(-(int32_t) c); - return vreinterpretq_m128i_u32(vshlq_u32(vreinterpretq_u32_m128i(a), vc)); +// Broadcast single-precision (32-bit) floating-point value a to all elements of +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set1_ps +FORCE_INLINE __m128 _mm_set1_ps(float _w) +{ + return vreinterpretq_m128_f32(vdupq_n_f32(_w)); } -// Shifts the 2 signed or unsigned 64-bit integers in a right by count bits -// while shifting in zeros. -// -// r0 := srl(a0, count) -// r1 := srl(a1, count) -// -// https://msdn.microsoft.com/en-us/library/yf6cf9k8(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_srl_epi64(__m128i a, __m128i count) +// Set the MXCSR control and status register with the value in unsigned 32-bit +// integer a. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setcsr +// FIXME: _mm_setcsr() implementation supports changing the rounding mode only. +FORCE_INLINE void _mm_setcsr(unsigned int a) { - uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); - if (c > 63) - return _mm_setzero_si128(); + _MM_SET_ROUNDING_MODE(a); +} - int64x2_t vc = vdupq_n_s64(-(int64_t) c); - return vreinterpretq_m128i_u64(vshlq_u64(vreinterpretq_u64_m128i(a), vc)); +// Get the unsigned 32-bit value of the MXCSR control and status register. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_getcsr +// FIXME: _mm_getcsr() implementation supports reading the rounding mode only. +FORCE_INLINE unsigned int _mm_getcsr(void) +{ + return _MM_GET_ROUNDING_MODE(); } -// NEON does not provide a version of this function. -// Creates a 16-bit mask from the most significant bits of the 16 signed or -// unsigned 8-bit integers in a and zero extends the upper bits. -// https://msdn.microsoft.com/en-us/library/vstudio/s090c8fk(v=vs.100).aspx -FORCE_INLINE int _mm_movemask_epi8(__m128i a) +// Set packed single-precision (32-bit) floating-point elements in dst with the +// supplied values in reverse order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setr_ps +FORCE_INLINE __m128 _mm_setr_ps(float w, float z, float y, float x) { -#if defined(__aarch64__) - uint8x16_t input = vreinterpretq_u8_m128i(a); - const int8_t ALIGN_STRUCT(16) - xr[16] = {-7, -6, -5, -4, -3, -2, -1, 0, -7, -6, -5, -4, -3, -2, -1, 0}; - const uint8x16_t mask_and = vdupq_n_u8(0x80); - const int8x16_t mask_shift = vld1q_s8(xr); - const uint8x16_t mask_result = - vshlq_u8(vandq_u8(input, mask_and), mask_shift); - uint8x8_t lo = vget_low_u8(mask_result); - uint8x8_t hi = vget_high_u8(mask_result); + float ALIGN_STRUCT(16) data[4] = {w, z, y, x}; + return vreinterpretq_m128_f32(vld1q_f32(data)); +} + +// Return vector of type __m128 with all elements set to zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setzero_ps +FORCE_INLINE __m128 _mm_setzero_ps(void) +{ + return vreinterpretq_m128_f32(vdupq_n_f32(0)); +} - return vaddv_u8(lo) + (vaddv_u8(hi) << 8); +// Shuffle 16-bit integers in a using the control in imm8, and store the results +// in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_pi16 +#ifdef _sse2neon_shuffle +#define _mm_shuffle_pi16(a, imm) \ + vreinterpret_m64_s16(vshuffle_s16( \ + vreinterpret_s16_m64(a), vreinterpret_s16_m64(a), (imm & 0x3), \ + ((imm >> 2) & 0x3), ((imm >> 4) & 0x3), ((imm >> 6) & 0x3))) #else - // Use increasingly wide shifts+adds to collect the sign bits - // together. - // Since the widening shifts would be rather confusing to follow in little - // endian, everything will be illustrated in big endian order instead. This - // has a different result - the bits would actually be reversed on a big - // endian machine. +#define _mm_shuffle_pi16(a, imm) \ + _sse2neon_define1( \ + __m64, a, int16x4_t ret; \ + ret = vmov_n_s16( \ + vget_lane_s16(vreinterpret_s16_m64(_a), (imm) & (0x3))); \ + ret = vset_lane_s16( \ + vget_lane_s16(vreinterpret_s16_m64(_a), ((imm) >> 2) & 0x3), ret, \ + 1); \ + ret = vset_lane_s16( \ + vget_lane_s16(vreinterpret_s16_m64(_a), ((imm) >> 4) & 0x3), ret, \ + 2); \ + ret = vset_lane_s16( \ + vget_lane_s16(vreinterpret_s16_m64(_a), ((imm) >> 6) & 0x3), ret, \ + 3); \ + _sse2neon_return(vreinterpret_m64_s16(ret));) +#endif - // Starting input (only half the elements are shown): - // 89 ff 1d c0 00 10 99 33 - uint8x16_t input = vreinterpretq_u8_m128i(a); - - // Shift out everything but the sign bits with an unsigned shift right. - // - // Bytes of the vector:: - // 89 ff 1d c0 00 10 99 33 - // \ \ \ \ \ \ \ \ high_bits = (uint16x4_t)(input >> 7) - // | | | | | | | | - // 01 01 00 01 00 00 01 00 - // - // Bits of first important lane(s): - // 10001001 (89) - // \______ - // | - // 00000001 (01) - uint16x8_t high_bits = vreinterpretq_u16_u8(vshrq_n_u8(input, 7)); - - // Merge the even lanes together with a 16-bit unsigned shift right + add. - // 'xx' represents garbage data which will be ignored in the final result. - // In the important bytes, the add functions like a binary OR. - // - // 01 01 00 01 00 00 01 00 - // \_ | \_ | \_ | \_ | paired16 = (uint32x4_t)(input + (input >> 7)) - // \| \| \| \| - // xx 03 xx 01 xx 00 xx 02 - // - // 00000001 00000001 (01 01) - // \_______ | - // \| - // xxxxxxxx xxxxxx11 (xx 03) - uint32x4_t paired16 = - vreinterpretq_u32_u16(vsraq_n_u16(high_bits, high_bits, 7)); - - // Repeat with a wider 32-bit shift + add. - // xx 03 xx 01 xx 00 xx 02 - // \____ | \____ | paired32 = (uint64x1_t)(paired16 + (paired16 >> - // 14)) - // \| \| - // xx xx xx 0d xx xx xx 02 - // - // 00000011 00000001 (03 01) - // \\_____ || - // '----.\|| - // xxxxxxxx xxxx1101 (xx 0d) - uint64x2_t paired32 = - vreinterpretq_u64_u32(vsraq_n_u32(paired16, paired16, 14)); - - // Last, an even wider 64-bit shift + add to get our result in the low 8 bit - // lanes. xx xx xx 0d xx xx xx 02 - // \_________ | paired64 = (uint8x8_t)(paired32 + (paired32 >> - // 28)) - // \| - // xx xx xx xx xx xx xx d2 - // - // 00001101 00000010 (0d 02) - // \ \___ | | - // '---. \| | - // xxxxxxxx 11010010 (xx d2) - uint8x16_t paired64 = - vreinterpretq_u8_u64(vsraq_n_u64(paired32, paired32, 28)); - - // Extract the low 8 bits from each 64-bit lane with 2 8-bit extracts. - // xx xx xx xx xx xx xx d2 - // || return paired64[0] - // d2 - // Note: Little endian would return the correct value 4b (01001011) instead. - return vgetq_lane_u8(paired64, 0) | ((int) vgetq_lane_u8(paired64, 8) << 8); -#endif +// Perform a serializing operation on all store-to-memory instructions that were +// issued prior to this instruction. Guarantees that every store instruction +// that precedes, in program order, is globally visible before any store +// instruction which follows the fence in program order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sfence +FORCE_INLINE void _mm_sfence(void) +{ + _sse2neon_smp_mb(); } -// Copy the lower 64-bit integer in a to dst. -// -// dst[63:0] := a[63:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_movepi64_pi64 -FORCE_INLINE __m64 _mm_movepi64_pi64(__m128i a) +// Perform a serializing operation on all load-from-memory and store-to-memory +// instructions that were issued prior to this instruction. Guarantees that +// every memory access that precedes, in program order, the memory fence +// instruction is globally visible before any memory instruction which follows +// the fence in program order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mfence +FORCE_INLINE void _mm_mfence(void) { - return vreinterpret_m64_s64(vget_low_s64(vreinterpretq_s64_m128i(a))); + _sse2neon_smp_mb(); } -// Copy the 64-bit integer a to the lower element of dst, and zero the upper -// element. -// -// dst[63:0] := a[63:0] -// dst[127:64] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_movpi64_epi64 -FORCE_INLINE __m128i _mm_movpi64_epi64(__m64 a) +// Perform a serializing operation on all load-from-memory instructions that +// were issued prior to this instruction. Guarantees that every load instruction +// that precedes, in program order, is globally visible before any load +// instruction which follows the fence in program order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_lfence +FORCE_INLINE void _mm_lfence(void) { - return vreinterpretq_m128i_s64( - vcombine_s64(vreinterpret_s64_m64(a), vdup_n_s64(0))); + _sse2neon_smp_mb(); } -// NEON does not provide this method -// Creates a 4-bit mask from the most significant bits of the four -// single-precision, floating-point values. -// https://msdn.microsoft.com/en-us/library/vstudio/4490ys29(v=vs.100).aspx -FORCE_INLINE int _mm_movemask_ps(__m128 a) +// FORCE_INLINE __m128 _mm_shuffle_ps(__m128 a, __m128 b, __constrange(0,255) +// int imm) +#ifdef _sse2neon_shuffle +#define _mm_shuffle_ps(a, b, imm) \ + __extension__({ \ + float32x4_t _input1 = vreinterpretq_f32_m128(a); \ + float32x4_t _input2 = vreinterpretq_f32_m128(b); \ + float32x4_t _shuf = \ + vshuffleq_s32(_input1, _input2, (imm) & (0x3), ((imm) >> 2) & 0x3, \ + (((imm) >> 4) & 0x3) + 4, (((imm) >> 6) & 0x3) + 4); \ + vreinterpretq_m128_f32(_shuf); \ + }) +#else // generic +#define _mm_shuffle_ps(a, b, imm) \ + _sse2neon_define2( \ + __m128, a, b, __m128 ret; switch (imm) { \ + case _MM_SHUFFLE(1, 0, 3, 2): \ + ret = _mm_shuffle_ps_1032(_a, _b); \ + break; \ + case _MM_SHUFFLE(2, 3, 0, 1): \ + ret = _mm_shuffle_ps_2301(_a, _b); \ + break; \ + case _MM_SHUFFLE(0, 3, 2, 1): \ + ret = _mm_shuffle_ps_0321(_a, _b); \ + break; \ + case _MM_SHUFFLE(2, 1, 0, 3): \ + ret = _mm_shuffle_ps_2103(_a, _b); \ + break; \ + case _MM_SHUFFLE(1, 0, 1, 0): \ + ret = _mm_movelh_ps(_a, _b); \ + break; \ + case _MM_SHUFFLE(1, 0, 0, 1): \ + ret = _mm_shuffle_ps_1001(_a, _b); \ + break; \ + case _MM_SHUFFLE(0, 1, 0, 1): \ + ret = _mm_shuffle_ps_0101(_a, _b); \ + break; \ + case _MM_SHUFFLE(3, 2, 1, 0): \ + ret = _mm_shuffle_ps_3210(_a, _b); \ + break; \ + case _MM_SHUFFLE(0, 0, 1, 1): \ + ret = _mm_shuffle_ps_0011(_a, _b); \ + break; \ + case _MM_SHUFFLE(0, 0, 2, 2): \ + ret = _mm_shuffle_ps_0022(_a, _b); \ + break; \ + case _MM_SHUFFLE(2, 2, 0, 0): \ + ret = _mm_shuffle_ps_2200(_a, _b); \ + break; \ + case _MM_SHUFFLE(3, 2, 0, 2): \ + ret = _mm_shuffle_ps_3202(_a, _b); \ + break; \ + case _MM_SHUFFLE(3, 2, 3, 2): \ + ret = _mm_movehl_ps(_b, _a); \ + break; \ + case _MM_SHUFFLE(1, 1, 3, 3): \ + ret = _mm_shuffle_ps_1133(_a, _b); \ + break; \ + case _MM_SHUFFLE(2, 0, 1, 0): \ + ret = _mm_shuffle_ps_2010(_a, _b); \ + break; \ + case _MM_SHUFFLE(2, 0, 0, 1): \ + ret = _mm_shuffle_ps_2001(_a, _b); \ + break; \ + case _MM_SHUFFLE(2, 0, 3, 2): \ + ret = _mm_shuffle_ps_2032(_a, _b); \ + break; \ + default: \ + ret = _mm_shuffle_ps_default(_a, _b, (imm)); \ + break; \ + } _sse2neon_return(ret);) +#endif + +// Compute the square root of packed single-precision (32-bit) floating-point +// elements in a, and store the results in dst. +// Due to ARMv7-A NEON's lack of a precise square root intrinsic, we implement +// square root by multiplying input in with its reciprocal square root before +// using the Newton-Raphson method to approximate the results. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sqrt_ps +FORCE_INLINE __m128 _mm_sqrt_ps(__m128 in) { - uint32x4_t input = vreinterpretq_u32_m128(a); -#if defined(__aarch64__) - static const int32x4_t shift = {0, 1, 2, 3}; - uint32x4_t tmp = vshrq_n_u32(input, 31); - return vaddvq_u32(vshlq_u32(tmp, shift)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32(vsqrtq_f32(vreinterpretq_f32_m128(in))); #else - // Uses the exact same method as _mm_movemask_epi8, see that for details. - // Shift out everything but the sign bits with a 32-bit unsigned shift - // right. - uint64x2_t high_bits = vreinterpretq_u64_u32(vshrq_n_u32(input, 31)); - // Merge the two pairs together with a 64-bit unsigned shift right + add. - uint8x16_t paired = - vreinterpretq_u8_u64(vsraq_n_u64(high_bits, high_bits, 31)); - // Extract the result. - return vgetq_lane_u8(paired, 0) | (vgetq_lane_u8(paired, 8) << 2); + float32x4_t recip = vrsqrteq_f32(vreinterpretq_f32_m128(in)); + + // Test for vrsqrteq_f32(0) -> positive infinity case. + // Change to zero, so that s * 1/sqrt(s) result is zero too. + const uint32x4_t pos_inf = vdupq_n_u32(0x7F800000); + const uint32x4_t div_by_zero = + vceqq_u32(pos_inf, vreinterpretq_u32_f32(recip)); + recip = vreinterpretq_f32_u32( + vandq_u32(vmvnq_u32(div_by_zero), vreinterpretq_u32_f32(recip))); + + recip = vmulq_f32( + vrsqrtsq_f32(vmulq_f32(recip, recip), vreinterpretq_f32_m128(in)), + recip); + // Additional Netwon-Raphson iteration for accuracy + recip = vmulq_f32( + vrsqrtsq_f32(vmulq_f32(recip, recip), vreinterpretq_f32_m128(in)), + recip); + + // sqrt(s) = s * 1/sqrt(s) + return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(in), recip)); #endif } -// Compute the bitwise NOT of a and then AND with a 128-bit vector containing -// all 1's, and return 1 if the result is zero, otherwise return 0. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_test_all_ones -FORCE_INLINE int _mm_test_all_ones(__m128i a) +// Compute the square root of the lower single-precision (32-bit) floating-point +// element in a, store the result in the lower element of dst, and copy the +// upper 3 packed elements from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sqrt_ss +FORCE_INLINE __m128 _mm_sqrt_ss(__m128 in) { - return (uint64_t)(vgetq_lane_s64(a, 0) & vgetq_lane_s64(a, 1)) == - ~(uint64_t) 0; + float32_t value = + vgetq_lane_f32(vreinterpretq_f32_m128(_mm_sqrt_ps(in)), 0); + return vreinterpretq_m128_f32( + vsetq_lane_f32(value, vreinterpretq_f32_m128(in), 0)); } -// Compute the bitwise AND of 128 bits (representing integer data) in a and -// mask, and return 1 if the result is zero, otherwise return 0. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_test_all_zeros -FORCE_INLINE int _mm_test_all_zeros(__m128i a, __m128i mask) +// Store 128-bits (composed of 4 packed single-precision (32-bit) floating-point +// elements) from a into memory. mem_addr must be aligned on a 16-byte boundary +// or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_store_ps +FORCE_INLINE void _mm_store_ps(float *p, __m128 a) { - int64x2_t a_and_mask = - vandq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(mask)); - return (vgetq_lane_s64(a_and_mask, 0) | vgetq_lane_s64(a_and_mask, 1)) ? 0 - : 1; + vst1q_f32(p, vreinterpretq_f32_m128(a)); } -/* Math operations */ - -// Subtracts the four single-precision, floating-point values of a and b. -// -// r0 := a0 - b0 -// r1 := a1 - b1 -// r2 := a2 - b2 -// r3 := a3 - b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/1zad2k61(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sub_ps(__m128 a, __m128 b) +// Store the lower single-precision (32-bit) floating-point element from a into +// 4 contiguous elements in memory. mem_addr must be aligned on a 16-byte +// boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_store_ps1 +FORCE_INLINE void _mm_store_ps1(float *p, __m128 a) { - return vreinterpretq_m128_f32( - vsubq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); + vst1q_f32(p, vdupq_n_f32(a0)); } -// Subtract the lower single-precision (32-bit) floating-point element in b from -// the lower single-precision (32-bit) floating-point element in a, store the -// result in the lower element of dst, and copy the upper 3 packed elements from -// a to the upper elements of dst. -// -// dst[31:0] := a[31:0] - b[31:0] -// dst[127:32] := a[127:32] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_sub_ss -FORCE_INLINE __m128 _mm_sub_ss(__m128 a, __m128 b) +// Store the lower single-precision (32-bit) floating-point element from a into +// memory. mem_addr does not need to be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_store_ss +FORCE_INLINE void _mm_store_ss(float *p, __m128 a) { - return _mm_move_ss(a, _mm_sub_ps(a, b)); + vst1q_lane_f32(p, vreinterpretq_f32_m128(a), 0); } -// Subtract 2 packed 64-bit integers in b from 2 packed 64-bit integers in a, -// and store the results in dst. -// r0 := a0 - b0 -// r1 := a1 - b1 -FORCE_INLINE __m128i _mm_sub_epi64(__m128i a, __m128i b) +// Store the lower single-precision (32-bit) floating-point element from a into +// 4 contiguous elements in memory. mem_addr must be aligned on a 16-byte +// boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_store1_ps +#define _mm_store1_ps _mm_store_ps1 + +// Store the upper 2 single-precision (32-bit) floating-point elements from a +// into memory. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeh_pi +FORCE_INLINE void _mm_storeh_pi(__m64 *p, __m128 a) { - return vreinterpretq_m128i_s64( - vsubq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); + *p = vreinterpret_m64_f32(vget_high_f32(a)); } -// Subtracts the 4 signed or unsigned 32-bit integers of b from the 4 signed or -// unsigned 32-bit integers of a. -// -// r0 := a0 - b0 -// r1 := a1 - b1 -// r2 := a2 - b2 -// r3 := a3 - b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/fhh866h0(v=vs.100).aspx -FORCE_INLINE __m128i _mm_sub_epi32(__m128i a, __m128i b) +// Store the lower 2 single-precision (32-bit) floating-point elements from a +// into memory. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storel_pi +FORCE_INLINE void _mm_storel_pi(__m64 *p, __m128 a) { - return vreinterpretq_m128i_s32( - vsubq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); + *p = vreinterpret_m64_f32(vget_low_f32(a)); } -FORCE_INLINE __m128i _mm_sub_epi16(__m128i a, __m128i b) +// Store 4 single-precision (32-bit) floating-point elements from a into memory +// in reverse order. mem_addr must be aligned on a 16-byte boundary or a +// general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storer_ps +FORCE_INLINE void _mm_storer_ps(float *p, __m128 a) { - return vreinterpretq_m128i_s16( - vsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); + float32x4_t tmp = vrev64q_f32(vreinterpretq_f32_m128(a)); + float32x4_t rev = vextq_f32(tmp, tmp, 2); + vst1q_f32(p, rev); } -FORCE_INLINE __m128i _mm_sub_epi8(__m128i a, __m128i b) +// Store 128-bits (composed of 4 packed single-precision (32-bit) floating-point +// elements) from a into memory. mem_addr does not need to be aligned on any +// particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeu_ps +FORCE_INLINE void _mm_storeu_ps(float *p, __m128 a) { - return vreinterpretq_m128i_s8( - vsubq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); + vst1q_f32(p, vreinterpretq_f32_m128(a)); } -// Subtract 64-bit integer b from 64-bit integer a, and store the result in dst. -// -// dst[63:0] := a[63:0] - b[63:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_sub_si64 -FORCE_INLINE __m64 _mm_sub_si64(__m64 a, __m64 b) +// Stores 16-bits of integer data a at the address p. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeu_si16 +FORCE_INLINE void _mm_storeu_si16(void *p, __m128i a) { - return vreinterpret_m64_s64( - vsub_s64(vreinterpret_s64_m64(a), vreinterpret_s64_m64(b))); + vst1q_lane_s16((int16_t *) p, vreinterpretq_s16_m128i(a), 0); } -// Subtracts the 8 unsigned 16-bit integers of bfrom the 8 unsigned 16-bit -// integers of a and saturates.. -// https://technet.microsoft.com/en-us/subscriptions/index/f44y0s19(v=vs.90).aspx -FORCE_INLINE __m128i _mm_subs_epu16(__m128i a, __m128i b) +// Stores 64-bits of integer data a at the address p. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeu_si64 +FORCE_INLINE void _mm_storeu_si64(void *p, __m128i a) { - return vreinterpretq_m128i_u16( - vqsubq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); + vst1q_lane_s64((int64_t *) p, vreinterpretq_s64_m128i(a), 0); } -// Subtracts the 16 unsigned 8-bit integers of b from the 16 unsigned 8-bit -// integers of a and saturates. -// -// r0 := UnsignedSaturate(a0 - b0) -// r1 := UnsignedSaturate(a1 - b1) -// ... -// r15 := UnsignedSaturate(a15 - b15) -// -// https://technet.microsoft.com/en-us/subscriptions/yadkxc18(v=vs.90) -FORCE_INLINE __m128i _mm_subs_epu8(__m128i a, __m128i b) +// Store 64-bits of integer data from a into memory using a non-temporal memory +// hint. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_stream_pi +FORCE_INLINE void _mm_stream_pi(__m64 *p, __m64 a) { - return vreinterpretq_m128i_u8( - vqsubq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); + vst1_s64((int64_t *) p, vreinterpret_s64_m64(a)); } -// Subtracts the 16 signed 8-bit integers of b from the 16 signed 8-bit integers -// of a and saturates. -// -// r0 := SignedSaturate(a0 - b0) -// r1 := SignedSaturate(a1 - b1) -// ... -// r15 := SignedSaturate(a15 - b15) -// -// https://technet.microsoft.com/en-us/subscriptions/by7kzks1(v=vs.90) -FORCE_INLINE __m128i _mm_subs_epi8(__m128i a, __m128i b) +// Store 128-bits (composed of 4 packed single-precision (32-bit) floating- +// point elements) from a into memory using a non-temporal memory hint. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_stream_ps +FORCE_INLINE void _mm_stream_ps(float *p, __m128 a) { - return vreinterpretq_m128i_s8( - vqsubq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +#if __has_builtin(__builtin_nontemporal_store) + __builtin_nontemporal_store(a, (float32x4_t *) p); +#else + vst1q_f32(p, vreinterpretq_f32_m128(a)); +#endif } -// Subtracts the 8 signed 16-bit integers of b from the 8 signed 16-bit integers -// of a and saturates. -// -// r0 := SignedSaturate(a0 - b0) -// r1 := SignedSaturate(a1 - b1) -// ... -// r7 := SignedSaturate(a7 - b7) -// -// https://technet.microsoft.com/en-us/subscriptions/3247z5b8(v=vs.90) -FORCE_INLINE __m128i _mm_subs_epi16(__m128i a, __m128i b) +// Subtract packed single-precision (32-bit) floating-point elements in b from +// packed single-precision (32-bit) floating-point elements in a, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_ps +FORCE_INLINE __m128 _mm_sub_ps(__m128 a, __m128 b) { - return vreinterpretq_m128i_s16( - vqsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); + return vreinterpretq_m128_f32( + vsubq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); } -FORCE_INLINE __m128i _mm_adds_epu16(__m128i a, __m128i b) +// Subtract the lower single-precision (32-bit) floating-point element in b from +// the lower single-precision (32-bit) floating-point element in a, store the +// result in the lower element of dst, and copy the upper 3 packed elements from +// a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_ss +FORCE_INLINE __m128 _mm_sub_ss(__m128 a, __m128 b) { - return vreinterpretq_m128i_u16( - vqaddq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); + return _mm_move_ss(a, _mm_sub_ps(a, b)); } -// Negate packed 8-bit integers in a when the corresponding signed -// 8-bit integer in b is negative, and store the results in dst. -// Element in dst are zeroed out when the corresponding element -// in b is zero. -// -// for i in 0..15 -// if b[i] < 0 -// r[i] := -a[i] -// else if b[i] == 0 -// r[i] := 0 -// else -// r[i] := a[i] -// fi -// done -FORCE_INLINE __m128i _mm_sign_epi8(__m128i _a, __m128i _b) -{ - int8x16_t a = vreinterpretq_s8_m128i(_a); - int8x16_t b = vreinterpretq_s8_m128i(_b); +// Macro: Transpose the 4x4 matrix formed by the 4 rows of single-precision +// (32-bit) floating-point elements in row0, row1, row2, and row3, and store the +// transposed matrix in these vectors (row0 now contains column 0, etc.). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=MM_TRANSPOSE4_PS +#define _MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ + do { \ + float32x4x2_t ROW01 = vtrnq_f32(row0, row1); \ + float32x4x2_t ROW23 = vtrnq_f32(row2, row3); \ + row0 = vcombine_f32(vget_low_f32(ROW01.val[0]), \ + vget_low_f32(ROW23.val[0])); \ + row1 = vcombine_f32(vget_low_f32(ROW01.val[1]), \ + vget_low_f32(ROW23.val[1])); \ + row2 = vcombine_f32(vget_high_f32(ROW01.val[0]), \ + vget_high_f32(ROW23.val[0])); \ + row3 = vcombine_f32(vget_high_f32(ROW01.val[1]), \ + vget_high_f32(ROW23.val[1])); \ + } while (0) - // signed shift right: faster than vclt - // (b < 0) ? 0xFF : 0 - uint8x16_t ltMask = vreinterpretq_u8_s8(vshrq_n_s8(b, 7)); +// according to the documentation, these intrinsics behave the same as the +// non-'u' versions. We'll just alias them here. +#define _mm_ucomieq_ss _mm_comieq_ss +#define _mm_ucomige_ss _mm_comige_ss +#define _mm_ucomigt_ss _mm_comigt_ss +#define _mm_ucomile_ss _mm_comile_ss +#define _mm_ucomilt_ss _mm_comilt_ss +#define _mm_ucomineq_ss _mm_comineq_ss - // (b == 0) ? 0xFF : 0 -#if defined(__aarch64__) - int8x16_t zeroMask = vreinterpretq_s8_u8(vceqzq_s8(b)); -#else - int8x16_t zeroMask = vreinterpretq_s8_u8(vceqq_s8(b, vdupq_n_s8(0))); -#endif - - // bitwise select either a or nagative 'a' (vnegq_s8(a) return nagative 'a') - // based on ltMask - int8x16_t masked = vbslq_s8(ltMask, vnegq_s8(a), a); - // res = masked & (~zeroMask) - int8x16_t res = vbicq_s8(masked, zeroMask); - - return vreinterpretq_m128i_s8(res); -} - -// Negate packed 16-bit integers in a when the corresponding signed -// 16-bit integer in b is negative, and store the results in dst. -// Element in dst are zeroed out when the corresponding element -// in b is zero. -// -// for i in 0..7 -// if b[i] < 0 -// r[i] := -a[i] -// else if b[i] == 0 -// r[i] := 0 -// else -// r[i] := a[i] -// fi -// done -FORCE_INLINE __m128i _mm_sign_epi16(__m128i _a, __m128i _b) +// Return vector of type __m128i with undefined elements. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=mm_undefined_si128 +FORCE_INLINE __m128i _mm_undefined_si128(void) { - int16x8_t a = vreinterpretq_s16_m128i(_a); - int16x8_t b = vreinterpretq_s16_m128i(_b); - - // signed shift right: faster than vclt - // (b < 0) ? 0xFFFF : 0 - uint16x8_t ltMask = vreinterpretq_u16_s16(vshrq_n_s16(b, 15)); - // (b == 0) ? 0xFFFF : 0 -#if defined(__aarch64__) - int16x8_t zeroMask = vreinterpretq_s16_u16(vceqzq_s16(b)); -#else - int16x8_t zeroMask = vreinterpretq_s16_u16(vceqq_s16(b, vdupq_n_s16(0))); +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuninitialized" #endif - - // bitwise select either a or negative 'a' (vnegq_s16(a) equals to negative - // 'a') based on ltMask - int16x8_t masked = vbslq_s16(ltMask, vnegq_s16(a), a); - // res = masked & (~zeroMask) - int16x8_t res = vbicq_s16(masked, zeroMask); - return vreinterpretq_m128i_s16(res); -} - -// Negate packed 32-bit integers in a when the corresponding signed -// 32-bit integer in b is negative, and store the results in dst. -// Element in dst are zeroed out when the corresponding element -// in b is zero. -// -// for i in 0..3 -// if b[i] < 0 -// r[i] := -a[i] -// else if b[i] == 0 -// r[i] := 0 -// else -// r[i] := a[i] -// fi -// done -FORCE_INLINE __m128i _mm_sign_epi32(__m128i _a, __m128i _b) -{ - int32x4_t a = vreinterpretq_s32_m128i(_a); - int32x4_t b = vreinterpretq_s32_m128i(_b); - - // signed shift right: faster than vclt - // (b < 0) ? 0xFFFFFFFF : 0 - uint32x4_t ltMask = vreinterpretq_u32_s32(vshrq_n_s32(b, 31)); - - // (b == 0) ? 0xFFFFFFFF : 0 -#if defined(__aarch64__) - int32x4_t zeroMask = vreinterpretq_s32_u32(vceqzq_s32(b)); -#else - int32x4_t zeroMask = vreinterpretq_s32_u32(vceqq_s32(b, vdupq_n_s32(0))); + __m128i a; +#if defined(_MSC_VER) + a = _mm_setzero_si128(); +#endif + return a; +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop #endif - - // bitwise select either a or negative 'a' (vnegq_s32(a) equals to negative - // 'a') based on ltMask - int32x4_t masked = vbslq_s32(ltMask, vnegq_s32(a), a); - // res = masked & (~zeroMask) - int32x4_t res = vbicq_s32(masked, zeroMask); - return vreinterpretq_m128i_s32(res); } -// Negate packed 16-bit integers in a when the corresponding signed 16-bit -// integer in b is negative, and store the results in dst. Element in dst are -// zeroed out when the corresponding element in b is zero. -// -// FOR j := 0 to 3 -// i := j*16 -// IF b[i+15:i] < 0 -// dst[i+15:i] := -(a[i+15:i]) -// ELSE IF b[i+15:i] == 0 -// dst[i+15:i] := 0 -// ELSE -// dst[i+15:i] := a[i+15:i] -// FI -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_sign_pi16 -FORCE_INLINE __m64 _mm_sign_pi16(__m64 _a, __m64 _b) +// Return vector of type __m128 with undefined elements. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_undefined_ps +FORCE_INLINE __m128 _mm_undefined_ps(void) { - int16x4_t a = vreinterpret_s16_m64(_a); - int16x4_t b = vreinterpret_s16_m64(_b); - - // signed shift right: faster than vclt - // (b < 0) ? 0xFFFF : 0 - uint16x4_t ltMask = vreinterpret_u16_s16(vshr_n_s16(b, 15)); - - // (b == 0) ? 0xFFFF : 0 -#if defined(__aarch64__) - int16x4_t zeroMask = vreinterpret_s16_u16(vceqz_s16(b)); -#else - int16x4_t zeroMask = vreinterpret_s16_u16(vceq_s16(b, vdup_n_s16(0))); +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuninitialized" +#endif + __m128 a; +#if defined(_MSC_VER) + a = _mm_setzero_ps(); +#endif + return a; +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop #endif - - // bitwise select either a or nagative 'a' (vneg_s16(a) return nagative 'a') - // based on ltMask - int16x4_t masked = vbsl_s16(ltMask, vneg_s16(a), a); - // res = masked & (~zeroMask) - int16x4_t res = vbic_s16(masked, zeroMask); - - return vreinterpret_m64_s16(res); } -// Negate packed 32-bit integers in a when the corresponding signed 32-bit -// integer in b is negative, and store the results in dst. Element in dst are -// zeroed out when the corresponding element in b is zero. -// -// FOR j := 0 to 1 -// i := j*32 -// IF b[i+31:i] < 0 -// dst[i+31:i] := -(a[i+31:i]) -// ELSE IF b[i+31:i] == 0 -// dst[i+31:i] := 0 -// ELSE -// dst[i+31:i] := a[i+31:i] -// FI -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_sign_pi32 -FORCE_INLINE __m64 _mm_sign_pi32(__m64 _a, __m64 _b) +// Unpack and interleave single-precision (32-bit) floating-point elements from +// the high half a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpackhi_ps +FORCE_INLINE __m128 _mm_unpackhi_ps(__m128 a, __m128 b) { - int32x2_t a = vreinterpret_s32_m64(_a); - int32x2_t b = vreinterpret_s32_m64(_b); - - // signed shift right: faster than vclt - // (b < 0) ? 0xFFFFFFFF : 0 - uint32x2_t ltMask = vreinterpret_u32_s32(vshr_n_s32(b, 31)); - - // (b == 0) ? 0xFFFFFFFF : 0 -#if defined(__aarch64__) - int32x2_t zeroMask = vreinterpret_s32_u32(vceqz_s32(b)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32( + vzip2q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); #else - int32x2_t zeroMask = vreinterpret_s32_u32(vceq_s32(b, vdup_n_s32(0))); + float32x2_t a1 = vget_high_f32(vreinterpretq_f32_m128(a)); + float32x2_t b1 = vget_high_f32(vreinterpretq_f32_m128(b)); + float32x2x2_t result = vzip_f32(a1, b1); + return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); #endif - - // bitwise select either a or nagative 'a' (vneg_s32(a) return nagative 'a') - // based on ltMask - int32x2_t masked = vbsl_s32(ltMask, vneg_s32(a), a); - // res = masked & (~zeroMask) - int32x2_t res = vbic_s32(masked, zeroMask); - - return vreinterpret_m64_s32(res); } -// Negate packed 8-bit integers in a when the corresponding signed 8-bit integer -// in b is negative, and store the results in dst. Element in dst are zeroed out -// when the corresponding element in b is zero. -// -// FOR j := 0 to 7 -// i := j*8 -// IF b[i+7:i] < 0 -// dst[i+7:i] := -(a[i+7:i]) -// ELSE IF b[i+7:i] == 0 -// dst[i+7:i] := 0 -// ELSE -// dst[i+7:i] := a[i+7:i] -// FI -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_sign_pi8 -FORCE_INLINE __m64 _mm_sign_pi8(__m64 _a, __m64 _b) +// Unpack and interleave single-precision (32-bit) floating-point elements from +// the low half of a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpacklo_ps +FORCE_INLINE __m128 _mm_unpacklo_ps(__m128 a, __m128 b) { - int8x8_t a = vreinterpret_s8_m64(_a); - int8x8_t b = vreinterpret_s8_m64(_b); - - // signed shift right: faster than vclt - // (b < 0) ? 0xFF : 0 - uint8x8_t ltMask = vreinterpret_u8_s8(vshr_n_s8(b, 7)); - - // (b == 0) ? 0xFF : 0 -#if defined(__aarch64__) - int8x8_t zeroMask = vreinterpret_s8_u8(vceqz_s8(b)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32( + vzip1q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); #else - int8x8_t zeroMask = vreinterpret_s8_u8(vceq_s8(b, vdup_n_s8(0))); + float32x2_t a1 = vget_low_f32(vreinterpretq_f32_m128(a)); + float32x2_t b1 = vget_low_f32(vreinterpretq_f32_m128(b)); + float32x2x2_t result = vzip_f32(a1, b1); + return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); #endif - - // bitwise select either a or nagative 'a' (vneg_s8(a) return nagative 'a') - // based on ltMask - int8x8_t masked = vbsl_s8(ltMask, vneg_s8(a), a); - // res = masked & (~zeroMask) - int8x8_t res = vbic_s8(masked, zeroMask); - - return vreinterpret_m64_s8(res); } -// Average packed unsigned 16-bit integers in a and b, and store the results in -// dst. -// -// FOR j := 0 to 3 -// i := j*16 -// dst[i+15:i] := (a[i+15:i] + b[i+15:i] + 1) >> 1 -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_avg_pu16 -FORCE_INLINE __m64 _mm_avg_pu16(__m64 a, __m64 b) +// Compute the bitwise XOR of packed single-precision (32-bit) floating-point +// elements in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_xor_ps +FORCE_INLINE __m128 _mm_xor_ps(__m128 a, __m128 b) { - return vreinterpret_m64_u16( - vrhadd_u16(vreinterpret_u16_m64(a), vreinterpret_u16_m64(b))); + return vreinterpretq_m128_s32( + veorq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b))); } -// Average packed unsigned 8-bit integers in a and b, and store the results in -// dst. -// -// FOR j := 0 to 7 -// i := j*8 -// dst[i+7:i] := (a[i+7:i] + b[i+7:i] + 1) >> 1 -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_avg_pu8 -FORCE_INLINE __m64 _mm_avg_pu8(__m64 a, __m64 b) +/* SSE2 */ + +// Add packed 16-bit integers in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_epi16 +FORCE_INLINE __m128i _mm_add_epi16(__m128i a, __m128i b) { - return vreinterpret_m64_u8( - vrhadd_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))); + return vreinterpretq_m128i_s16( + vaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } -// Average packed unsigned 8-bit integers in a and b, and store the results in -// dst. -// -// FOR j := 0 to 7 -// i := j*8 -// dst[i+7:i] := (a[i+7:i] + b[i+7:i] + 1) >> 1 -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_m_pavgb -#define _m_pavgb(a, b) _mm_avg_pu8(a, b) - -// Average packed unsigned 16-bit integers in a and b, and store the results in -// dst. -// -// FOR j := 0 to 3 -// i := j*16 -// dst[i+15:i] := (a[i+15:i] + b[i+15:i] + 1) >> 1 -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_m_pavgw -#define _m_pavgw(a, b) _mm_avg_pu16(a, b) - -// Computes the average of the 16 unsigned 8-bit integers in a and the 16 -// unsigned 8-bit integers in b and rounds. -// -// r0 := (a0 + b0) / 2 -// r1 := (a1 + b1) / 2 -// ... -// r15 := (a15 + b15) / 2 -// -// https://msdn.microsoft.com/en-us/library/vstudio/8zwh554a(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_avg_epu8(__m128i a, __m128i b) +// Add packed 32-bit integers in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_epi32 +FORCE_INLINE __m128i _mm_add_epi32(__m128i a, __m128i b) { - return vreinterpretq_m128i_u8( - vrhaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); + return vreinterpretq_m128i_s32( + vaddq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } -// Computes the average of the 8 unsigned 16-bit integers in a and the 8 -// unsigned 16-bit integers in b and rounds. -// -// r0 := (a0 + b0) / 2 -// r1 := (a1 + b1) / 2 -// ... -// r7 := (a7 + b7) / 2 -// -// https://msdn.microsoft.com/en-us/library/vstudio/y13ca3c8(v=vs.90).aspx -FORCE_INLINE __m128i _mm_avg_epu16(__m128i a, __m128i b) +// Add packed 64-bit integers in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_epi64 +FORCE_INLINE __m128i _mm_add_epi64(__m128i a, __m128i b) { - return (__m128i) vrhaddq_u16(vreinterpretq_u16_m128i(a), - vreinterpretq_u16_m128i(b)); + return vreinterpretq_m128i_s64( + vaddq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); } -// Adds the four single-precision, floating-point values of a and b. -// -// r0 := a0 + b0 -// r1 := a1 + b1 -// r2 := a2 + b2 -// r3 := a3 + b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/c9848chc(v=vs.100).aspx -FORCE_INLINE __m128 _mm_add_ps(__m128 a, __m128 b) +// Add packed 8-bit integers in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_epi8 +FORCE_INLINE __m128i _mm_add_epi8(__m128i a, __m128i b) { - return vreinterpretq_m128_f32( - vaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + return vreinterpretq_m128i_s8( + vaddq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } // Add packed double-precision (64-bit) floating-point elements in a and b, and // store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_add_pd +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_pd FORCE_INLINE __m128d _mm_add_pd(__m128d a, __m128d b) { -#if defined(__aarch64__) +#if defined(__aarch64__) || defined(_M_ARM64) return vreinterpretq_m128d_f64( vaddq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); #else @@ -3010,2570 +2957,4298 @@ FORCE_INLINE __m128d _mm_add_pd(__m128d a, __m128d b) #endif } +// Add the lower double-precision (64-bit) floating-point element in a and b, +// store the result in the lower element of dst, and copy the upper element from +// a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_sd +FORCE_INLINE __m128d _mm_add_sd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_add_pd(a, b)); +#else + double *da = (double *) &a; + double *db = (double *) &b; + double c[2]; + c[0] = da[0] + db[0]; + c[1] = da[1]; + return vld1q_f32((float32_t *) c); +#endif +} + // Add 64-bit integers a and b, and store the result in dst. -// -// dst[63:0] := a[63:0] + b[63:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_add_si64 +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_add_si64 FORCE_INLINE __m64 _mm_add_si64(__m64 a, __m64 b) { return vreinterpret_m64_s64( vadd_s64(vreinterpret_s64_m64(a), vreinterpret_s64_m64(b))); } -// adds the scalar single-precision floating point values of a and b. -// https://msdn.microsoft.com/en-us/library/be94x2y6(v=vs.100).aspx -FORCE_INLINE __m128 _mm_add_ss(__m128 a, __m128 b) +// Add packed signed 16-bit integers in a and b using saturation, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_adds_epi16 +FORCE_INLINE __m128i _mm_adds_epi16(__m128i a, __m128i b) { - float32_t b0 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 0); - float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); - // the upper values in the result must be the remnants of . - return vreinterpretq_m128_f32(vaddq_f32(a, value)); + return vreinterpretq_m128i_s16( + vqaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } -// Adds the 4 signed or unsigned 64-bit integers in a to the 4 signed or -// unsigned 32-bit integers in b. -// https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx -FORCE_INLINE __m128i _mm_add_epi64(__m128i a, __m128i b) +// Add packed signed 8-bit integers in a and b using saturation, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_adds_epi8 +FORCE_INLINE __m128i _mm_adds_epi8(__m128i a, __m128i b) { - return vreinterpretq_m128i_s64( - vaddq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); + return vreinterpretq_m128i_s8( + vqaddq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } -// Adds the 4 signed or unsigned 32-bit integers in a to the 4 signed or -// unsigned 32-bit integers in b. -// -// r0 := a0 + b0 -// r1 := a1 + b1 -// r2 := a2 + b2 -// r3 := a3 + b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx -FORCE_INLINE __m128i _mm_add_epi32(__m128i a, __m128i b) +// Add packed unsigned 16-bit integers in a and b using saturation, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_adds_epu16 +FORCE_INLINE __m128i _mm_adds_epu16(__m128i a, __m128i b) { - return vreinterpretq_m128i_s32( - vaddq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} + return vreinterpretq_m128i_u16( + vqaddq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); +} -// Adds the 8 signed or unsigned 16-bit integers in a to the 8 signed or -// unsigned 16-bit integers in b. -// https://msdn.microsoft.com/en-us/library/fceha5k4(v=vs.100).aspx -FORCE_INLINE __m128i _mm_add_epi16(__m128i a, __m128i b) +// Add packed unsigned 8-bit integers in a and b using saturation, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_adds_epu8 +FORCE_INLINE __m128i _mm_adds_epu8(__m128i a, __m128i b) { - return vreinterpretq_m128i_s16( - vaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); + return vreinterpretq_m128i_u8( + vqaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } -// Adds the 16 signed or unsigned 8-bit integers in a to the 16 signed or -// unsigned 8-bit integers in b. -// https://technet.microsoft.com/en-us/subscriptions/yc7tcyzs(v=vs.90) -FORCE_INLINE __m128i _mm_add_epi8(__m128i a, __m128i b) +// Compute the bitwise AND of packed double-precision (64-bit) floating-point +// elements in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_and_pd +FORCE_INLINE __m128d _mm_and_pd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s8( - vaddq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); + return vreinterpretq_m128d_s64( + vandq_s64(vreinterpretq_s64_m128d(a), vreinterpretq_s64_m128d(b))); } -// Adds the 8 signed 16-bit integers in a to the 8 signed 16-bit integers in b -// and saturates. -// -// r0 := SignedSaturate(a0 + b0) -// r1 := SignedSaturate(a1 + b1) -// ... -// r7 := SignedSaturate(a7 + b7) -// -// https://msdn.microsoft.com/en-us/library/1a306ef8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_adds_epi16(__m128i a, __m128i b) +// Compute the bitwise AND of 128 bits (representing integer data) in a and b, +// and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_and_si128 +FORCE_INLINE __m128i _mm_and_si128(__m128i a, __m128i b) { - return vreinterpretq_m128i_s16( - vqaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); + return vreinterpretq_m128i_s32( + vandq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } -// Add packed signed 8-bit integers in a and b using saturation, and store the -// results in dst. -// -// FOR j := 0 to 15 -// i := j*8 -// dst[i+7:i] := Saturate8( a[i+7:i] + b[i+7:i] ) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_adds_epi8 -FORCE_INLINE __m128i _mm_adds_epi8(__m128i a, __m128i b) +// Compute the bitwise NOT of packed double-precision (64-bit) floating-point +// elements in a and then AND with b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_andnot_pd +FORCE_INLINE __m128d _mm_andnot_pd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s8( - vqaddq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); + // *NOTE* argument swap + return vreinterpretq_m128d_s64( + vbicq_s64(vreinterpretq_s64_m128d(b), vreinterpretq_s64_m128d(a))); } -// Adds the 16 unsigned 8-bit integers in a to the 16 unsigned 8-bit integers in -// b and saturates.. -// https://msdn.microsoft.com/en-us/library/9hahyddy(v=vs.100).aspx -FORCE_INLINE __m128i _mm_adds_epu8(__m128i a, __m128i b) +// Compute the bitwise NOT of 128 bits (representing integer data) in a and then +// AND with b, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_andnot_si128 +FORCE_INLINE __m128i _mm_andnot_si128(__m128i a, __m128i b) { - return vreinterpretq_m128i_u8( - vqaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); + return vreinterpretq_m128i_s32( + vbicq_s32(vreinterpretq_s32_m128i(b), + vreinterpretq_s32_m128i(a))); // *NOTE* argument swap } -// Multiplies the 8 signed or unsigned 16-bit integers from a by the 8 signed or -// unsigned 16-bit integers from b. -// -// r0 := (a0 * b0)[15:0] -// r1 := (a1 * b1)[15:0] -// ... -// r7 := (a7 * b7)[15:0] -// -// https://msdn.microsoft.com/en-us/library/vstudio/9ks1472s(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mullo_epi16(__m128i a, __m128i b) +// Average packed unsigned 16-bit integers in a and b, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_avg_epu16 +FORCE_INLINE __m128i _mm_avg_epu16(__m128i a, __m128i b) { - return vreinterpretq_m128i_s16( - vmulq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); + return (__m128i) vrhaddq_u16(vreinterpretq_u16_m128i(a), + vreinterpretq_u16_m128i(b)); } -// Multiplies the 4 signed or unsigned 32-bit integers from a by the 4 signed or -// unsigned 32-bit integers from b. -// https://msdn.microsoft.com/en-us/library/vstudio/bb531409(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mullo_epi32(__m128i a, __m128i b) +// Average packed unsigned 8-bit integers in a and b, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_avg_epu8 +FORCE_INLINE __m128i _mm_avg_epu8(__m128i a, __m128i b) { - return vreinterpretq_m128i_s32( - vmulq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); + return vreinterpretq_m128i_u8( + vrhaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } -// Multiply the packed unsigned 16-bit integers in a and b, producing -// intermediate 32-bit integers, and store the high 16 bits of the intermediate -// integers in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// tmp[31:0] := a[i+15:i] * b[i+15:i] -// dst[i+15:i] := tmp[31:16] -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_m_pmulhuw -#define _m_pmulhuw(a, b) _mm_mulhi_pu16(a, b) +// Shift a left by imm8 bytes while shifting in zeros, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_bslli_si128 +#define _mm_bslli_si128(a, imm) _mm_slli_si128(a, imm) -// Multiplies the four single-precision, floating-point values of a and b. -// -// r0 := a0 * b0 -// r1 := a1 * b1 -// r2 := a2 * b2 -// r3 := a3 * b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/22kbk6t9(v=vs.100).aspx -FORCE_INLINE __m128 _mm_mul_ps(__m128 a, __m128 b) +// Shift a right by imm8 bytes while shifting in zeros, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_bsrli_si128 +#define _mm_bsrli_si128(a, imm) _mm_srli_si128(a, imm) + +// Cast vector of type __m128d to type __m128. This intrinsic is only used for +// compilation and does not generate any instructions, thus it has zero latency. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_castpd_ps +FORCE_INLINE __m128 _mm_castpd_ps(__m128d a) { - return vreinterpretq_m128_f32( - vmulq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + return vreinterpretq_m128_s64(vreinterpretq_s64_m128d(a)); } -// Multiply packed double-precision (64-bit) floating-point elements in a and b, -// and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_mul_pd -FORCE_INLINE __m128d _mm_mul_pd(__m128d a, __m128d b) +// Cast vector of type __m128d to type __m128i. This intrinsic is only used for +// compilation and does not generate any instructions, thus it has zero latency. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_castpd_si128 +FORCE_INLINE __m128i _mm_castpd_si128(__m128d a) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64( - vmulq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); -#else - double *da = (double *) &a; - double *db = (double *) &b; - double c[2]; - c[0] = da[0] * db[0]; - c[1] = da[1] * db[1]; - return vld1q_f32((float32_t *) c); -#endif + return vreinterpretq_m128i_s64(vreinterpretq_s64_m128d(a)); } -// Multiply the lower single-precision (32-bit) floating-point element in a and -// b, store the result in the lower element of dst, and copy the upper 3 packed -// elements from a to the upper elements of dst. -// -// dst[31:0] := a[31:0] * b[31:0] -// dst[127:32] := a[127:32] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_mul_ss -FORCE_INLINE __m128 _mm_mul_ss(__m128 a, __m128 b) +// Cast vector of type __m128 to type __m128d. This intrinsic is only used for +// compilation and does not generate any instructions, thus it has zero latency. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_castps_pd +FORCE_INLINE __m128d _mm_castps_pd(__m128 a) { - return _mm_move_ss(a, _mm_mul_ps(a, b)); + return vreinterpretq_m128d_s32(vreinterpretq_s32_m128(a)); } -// Multiply the low unsigned 32-bit integers from each packed 64-bit element in -// a and b, and store the unsigned 64-bit results in dst. -// -// r0 := (a0 & 0xFFFFFFFF) * (b0 & 0xFFFFFFFF) -// r1 := (a2 & 0xFFFFFFFF) * (b2 & 0xFFFFFFFF) -FORCE_INLINE __m128i _mm_mul_epu32(__m128i a, __m128i b) +// Cast vector of type __m128 to type __m128i. This intrinsic is only used for +// compilation and does not generate any instructions, thus it has zero latency. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_castps_si128 +FORCE_INLINE __m128i _mm_castps_si128(__m128 a) { - // vmull_u32 upcasts instead of masking, so we downcast. - uint32x2_t a_lo = vmovn_u64(vreinterpretq_u64_m128i(a)); - uint32x2_t b_lo = vmovn_u64(vreinterpretq_u64_m128i(b)); - return vreinterpretq_m128i_u64(vmull_u32(a_lo, b_lo)); + return vreinterpretq_m128i_s32(vreinterpretq_s32_m128(a)); } -// Multiply the low unsigned 32-bit integers from a and b, and store the -// unsigned 64-bit result in dst. -// -// dst[63:0] := a[31:0] * b[31:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_mul_su32 -FORCE_INLINE __m64 _mm_mul_su32(__m64 a, __m64 b) +// Cast vector of type __m128i to type __m128d. This intrinsic is only used for +// compilation and does not generate any instructions, thus it has zero latency. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_castsi128_pd +FORCE_INLINE __m128d _mm_castsi128_pd(__m128i a) { - return vreinterpret_m64_u64(vget_low_u64( - vmull_u32(vreinterpret_u32_m64(a), vreinterpret_u32_m64(b)))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vreinterpretq_f64_m128i(a)); +#else + return vreinterpretq_m128d_f32(vreinterpretq_f32_m128i(a)); +#endif } -// Multiply the low signed 32-bit integers from each packed 64-bit element in -// a and b, and store the signed 64-bit results in dst. -// -// r0 := (int64_t)(int32_t)a0 * (int64_t)(int32_t)b0 -// r1 := (int64_t)(int32_t)a2 * (int64_t)(int32_t)b2 -FORCE_INLINE __m128i _mm_mul_epi32(__m128i a, __m128i b) +// Cast vector of type __m128i to type __m128. This intrinsic is only used for +// compilation and does not generate any instructions, thus it has zero latency. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_castsi128_ps +FORCE_INLINE __m128 _mm_castsi128_ps(__m128i a) { - // vmull_s32 upcasts instead of masking, so we downcast. - int32x2_t a_lo = vmovn_s64(vreinterpretq_s64_m128i(a)); - int32x2_t b_lo = vmovn_s64(vreinterpretq_s64_m128i(b)); - return vreinterpretq_m128i_s64(vmull_s32(a_lo, b_lo)); + return vreinterpretq_m128_s32(vreinterpretq_s32_m128i(a)); } -// Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit -// integers from b. -// -// r0 := (a0 * b0) + (a1 * b1) -// r1 := (a2 * b2) + (a3 * b3) -// r2 := (a4 * b4) + (a5 * b5) -// r3 := (a6 * b6) + (a7 * b7) -// https://msdn.microsoft.com/en-us/library/yht36sa6(v=vs.90).aspx -FORCE_INLINE __m128i _mm_madd_epi16(__m128i a, __m128i b) +// Invalidate and flush the cache line that contains p from all levels of the +// cache hierarchy. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_clflush +#if defined(__APPLE__) +#include +#endif +FORCE_INLINE void _mm_clflush(void const *p) { - int32x4_t low = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)), - vget_low_s16(vreinterpretq_s16_m128i(b))); - int32x4_t high = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)), - vget_high_s16(vreinterpretq_s16_m128i(b))); - - int32x2_t low_sum = vpadd_s32(vget_low_s32(low), vget_high_s32(low)); - int32x2_t high_sum = vpadd_s32(vget_low_s32(high), vget_high_s32(high)); + (void) p; - return vreinterpretq_m128i_s32(vcombine_s32(low_sum, high_sum)); + /* sys_icache_invalidate is supported since macOS 10.5. + * However, it does not work on non-jailbroken iOS devices, although the + * compilation is successful. + */ +#if defined(__APPLE__) + sys_icache_invalidate((void *) (uintptr_t) p, SSE2NEON_CACHELINE_SIZE); +#elif defined(__GNUC__) || defined(__clang__) + uintptr_t ptr = (uintptr_t) p; + __builtin___clear_cache((char *) ptr, + (char *) ptr + SSE2NEON_CACHELINE_SIZE); +#elif (_MSC_VER) && SSE2NEON_INCLUDE_WINDOWS_H + FlushInstructionCache(GetCurrentProcess(), p, SSE2NEON_CACHELINE_SIZE); +#endif } -// Multiply packed signed 16-bit integers in a and b, producing intermediate -// signed 32-bit integers. Shift right by 15 bits while rounding up, and store -// the packed 16-bit integers in dst. -// -// r0 := Round(((int32_t)a0 * (int32_t)b0) >> 15) -// r1 := Round(((int32_t)a1 * (int32_t)b1) >> 15) -// r2 := Round(((int32_t)a2 * (int32_t)b2) >> 15) -// ... -// r7 := Round(((int32_t)a7 * (int32_t)b7) >> 15) -FORCE_INLINE __m128i _mm_mulhrs_epi16(__m128i a, __m128i b) +// Compare packed 16-bit integers in a and b for equality, and store the results +// in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpeq_epi16 +FORCE_INLINE __m128i _mm_cmpeq_epi16(__m128i a, __m128i b) { - // Has issues due to saturation - // return vreinterpretq_m128i_s16(vqrdmulhq_s16(a, b)); - - // Multiply - int32x4_t mul_lo = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)), - vget_low_s16(vreinterpretq_s16_m128i(b))); - int32x4_t mul_hi = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)), - vget_high_s16(vreinterpretq_s16_m128i(b))); + return vreinterpretq_m128i_u16( + vceqq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +} - // Rounding narrowing shift right - // narrow = (int16_t)((mul + 16384) >> 15); - int16x4_t narrow_lo = vrshrn_n_s32(mul_lo, 15); - int16x4_t narrow_hi = vrshrn_n_s32(mul_hi, 15); +// Compare packed 32-bit integers in a and b for equality, and store the results +// in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpeq_epi32 +FORCE_INLINE __m128i _mm_cmpeq_epi32(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_u32( + vceqq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +} - // Join together - return vreinterpretq_m128i_s16(vcombine_s16(narrow_lo, narrow_hi)); +// Compare packed 8-bit integers in a and b for equality, and store the results +// in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpeq_epi8 +FORCE_INLINE __m128i _mm_cmpeq_epi8(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_u8( + vceqq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } -// Vertically multiply each unsigned 8-bit integer from a with the corresponding -// signed 8-bit integer from b, producing intermediate signed 16-bit integers. -// Horizontally add adjacent pairs of intermediate signed 16-bit integers, -// and pack the saturated results in dst. -// -// FOR j := 0 to 7 -// i := j*16 -// dst[i+15:i] := Saturate_To_Int16( a[i+15:i+8]*b[i+15:i+8] + -// a[i+7:i]*b[i+7:i] ) -// ENDFOR -FORCE_INLINE __m128i _mm_maddubs_epi16(__m128i _a, __m128i _b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for equality, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpeq_pd +FORCE_INLINE __m128d _mm_cmpeq_pd(__m128d a, __m128d b) { -#if defined(__aarch64__) - uint8x16_t a = vreinterpretq_u8_m128i(_a); - int8x16_t b = vreinterpretq_s8_m128i(_b); - int16x8_t tl = vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(a))), - vmovl_s8(vget_low_s8(b))); - int16x8_t th = vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(a))), - vmovl_s8(vget_high_s8(b))); - return vreinterpretq_m128i_s16( - vqaddq_s16(vuzp1q_s16(tl, th), vuzp2q_s16(tl, th))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64( + vceqq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); #else - // This would be much simpler if x86 would choose to zero extend OR sign - // extend, not both. This could probably be optimized better. - uint16x8_t a = vreinterpretq_u16_m128i(_a); - int16x8_t b = vreinterpretq_s16_m128i(_b); - - // Zero extend a - int16x8_t a_odd = vreinterpretq_s16_u16(vshrq_n_u16(a, 8)); - int16x8_t a_even = vreinterpretq_s16_u16(vbicq_u16(a, vdupq_n_u16(0xff00))); - - // Sign extend by shifting left then shifting right. - int16x8_t b_even = vshrq_n_s16(vshlq_n_s16(b, 8), 8); - int16x8_t b_odd = vshrq_n_s16(b, 8); + // (a == b) -> (a_lo == b_lo) && (a_hi == b_hi) + uint32x4_t cmp = + vceqq_u32(vreinterpretq_u32_m128d(a), vreinterpretq_u32_m128d(b)); + uint32x4_t swapped = vrev64q_u32(cmp); + return vreinterpretq_m128d_u32(vandq_u32(cmp, swapped)); +#endif +} - // multiply - int16x8_t prod1 = vmulq_s16(a_even, b_even); - int16x8_t prod2 = vmulq_s16(a_odd, b_odd); +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for equality, store the result in the lower element of dst, and copy the +// upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpeq_sd +FORCE_INLINE __m128d _mm_cmpeq_sd(__m128d a, __m128d b) +{ + return _mm_move_sd(a, _mm_cmpeq_pd(a, b)); +} - // saturated add - return vreinterpretq_m128i_s16(vqaddq_s16(prod1, prod2)); +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for greater-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpge_pd +FORCE_INLINE __m128d _mm_cmpge_pd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64( + vcgeq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) >= (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = (*(double *) &a1) >= (*(double *) &b1) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); #endif } -// Computes the fused multiple add product of 32-bit floating point numbers. -// -// Return Value -// Multiplies A and B, and adds C to the temporary result before returning it. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_fmadd -FORCE_INLINE __m128 _mm_fmadd_ps(__m128 a, __m128 b, __m128 c) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for greater-than-or-equal, store the result in the lower element of dst, +// and copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpge_sd +FORCE_INLINE __m128d _mm_cmpge_sd(__m128d a, __m128d b) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32(vfmaq_f32(vreinterpretq_f32_m128(c), - vreinterpretq_f32_m128(b), - vreinterpretq_f32_m128(a))); +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_cmpge_pd(a, b)); #else - return _mm_add_ps(_mm_mul_ps(a, b), c); + // expand "_mm_cmpge_pd()" to reduce unnecessary operations + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) >= (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = a1; + + return vreinterpretq_m128d_u64(vld1q_u64(d)); #endif } -// Alternatively add and subtract packed single-precision (32-bit) -// floating-point elements in a to/from packed elements in b, and store the -// results in dst. -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=addsub_ps -FORCE_INLINE __m128 _mm_addsub_ps(__m128 a, __m128 b) +// Compare packed signed 16-bit integers in a and b for greater-than, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpgt_epi16 +FORCE_INLINE __m128i _mm_cmpgt_epi16(__m128i a, __m128i b) { - __m128 mask = {-1.0f, 1.0f, -1.0f, 1.0f}; - return _mm_fmadd_ps(b, mask, a); + return vreinterpretq_m128i_u16( + vcgtq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } -// Compute the absolute differences of packed unsigned 8-bit integers in a and -// b, then horizontally sum each consecutive 8 differences to produce two -// unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low -// 16 bits of 64-bit elements in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_sad_epu8 -FORCE_INLINE __m128i _mm_sad_epu8(__m128i a, __m128i b) +// Compare packed signed 32-bit integers in a and b for greater-than, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpgt_epi32 +FORCE_INLINE __m128i _mm_cmpgt_epi32(__m128i a, __m128i b) { - uint16x8_t t = vpaddlq_u8(vabdq_u8((uint8x16_t) a, (uint8x16_t) b)); - uint16_t r0 = t[0] + t[1] + t[2] + t[3]; - uint16_t r4 = t[4] + t[5] + t[6] + t[7]; - uint16x8_t r = vsetq_lane_u16(r0, vdupq_n_u16(0), 0); - return (__m128i) vsetq_lane_u16(r4, r, 4); + return vreinterpretq_m128i_u32( + vcgtq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } -// Compute the absolute differences of packed unsigned 8-bit integers in a and -// b, then horizontally sum each consecutive 8 differences to produce four -// unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low -// 16 bits of dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_sad_pu8 -FORCE_INLINE __m64 _mm_sad_pu8(__m64 a, __m64 b) +// Compare packed signed 8-bit integers in a and b for greater-than, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpgt_epi8 +FORCE_INLINE __m128i _mm_cmpgt_epi8(__m128i a, __m128i b) { - uint16x4_t t = - vpaddl_u8(vabd_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))); - uint16_t r0 = t[0] + t[1] + t[2] + t[3]; - return vreinterpret_m64_u16(vset_lane_u16(r0, vdup_n_u16(0), 0)); + return vreinterpretq_m128i_u8( + vcgtq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } -// Compute the absolute differences of packed unsigned 8-bit integers in a and -// b, then horizontally sum each consecutive 8 differences to produce four -// unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low -// 16 bits of dst. -// -// FOR j := 0 to 7 -// i := j*8 -// tmp[i+7:i] := ABS(a[i+7:i] - b[i+7:i]) -// ENDFOR -// dst[15:0] := tmp[7:0] + tmp[15:8] + tmp[23:16] + tmp[31:24] + tmp[39:32] + -// tmp[47:40] + tmp[55:48] + tmp[63:56] dst[63:16] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_m_psadbw -#define _m_psadbw(a, b) _mm_sad_pu8(a, b) - -// Divides the four single-precision, floating-point values of a and b. -// -// r0 := a0 / b0 -// r1 := a1 / b1 -// r2 := a2 / b2 -// r3 := a3 / b3 -// -// https://msdn.microsoft.com/en-us/library/edaw8147(v=vs.100).aspx -FORCE_INLINE __m128 _mm_div_ps(__m128 a, __m128 b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for greater-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpgt_pd +FORCE_INLINE __m128d _mm_cmpgt_pd(__m128d a, __m128d b) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32( - vdivq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64( + vcgtq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); #else - float32x4_t recip0 = vrecpeq_f32(vreinterpretq_f32_m128(b)); - float32x4_t recip1 = - vmulq_f32(recip0, vrecpsq_f32(recip0, vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), recip1)); + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) > (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = (*(double *) &a1) > (*(double *) &b1) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); #endif } -// Divides the scalar single-precision floating point value of a by b. -// https://msdn.microsoft.com/en-us/library/4y73xa49(v=vs.100).aspx -FORCE_INLINE __m128 _mm_div_ss(__m128 a, __m128 b) -{ - float32_t value = - vgetq_lane_f32(vreinterpretq_f32_m128(_mm_div_ps(a, b)), 0); - return vreinterpretq_m128_f32( - vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); -} - -// Compute the approximate reciprocal of packed single-precision (32-bit) -// floating-point elements in a, and store the results in dst. The maximum -// relative error for this approximation is less than 1.5*2^-12. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_rcp_ps -FORCE_INLINE __m128 _mm_rcp_ps(__m128 in) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for greater-than, store the result in the lower element of dst, and copy +// the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpgt_sd +FORCE_INLINE __m128d _mm_cmpgt_sd(__m128d a, __m128d b) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32( - vdivq_f32(vdupq_n_f32(1.0f), vreinterpretq_f32_m128(in))); +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_cmpgt_pd(a, b)); #else - float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); - recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); - return vreinterpretq_m128_f32(recip); + // expand "_mm_cmpge_pd()" to reduce unnecessary operations + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) > (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = a1; + + return vreinterpretq_m128d_u64(vld1q_u64(d)); #endif } -// Compute the approximate reciprocal of the lower single-precision (32-bit) -// floating-point element in a, store the result in the lower element of dst, -// and copy the upper 3 packed elements from a to the upper elements of dst. The -// maximum relative error for this approximation is less than 1.5*2^-12. -// -// dst[31:0] := (1.0 / a[31:0]) -// dst[127:32] := a[127:32] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_rcp_ss -FORCE_INLINE __m128 _mm_rcp_ss(__m128 a) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for less-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmple_pd +FORCE_INLINE __m128d _mm_cmple_pd(__m128d a, __m128d b) { - return _mm_move_ss(a, _mm_rcp_ps(a)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64( + vcleq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) <= (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = (*(double *) &a1) <= (*(double *) &b1) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Computes the approximations of square roots of the four single-precision, -// floating-point values of a. First computes reciprocal square roots and then -// reciprocals of the four values. -// -// r0 := sqrt(a0) -// r1 := sqrt(a1) -// r2 := sqrt(a2) -// r3 := sqrt(a3) -// -// https://msdn.microsoft.com/en-us/library/vstudio/8z67bwwk(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sqrt_ps(__m128 in) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for less-than-or-equal, store the result in the lower element of dst, and +// copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmple_sd +FORCE_INLINE __m128d _mm_cmple_sd(__m128d a, __m128d b) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32(vsqrtq_f32(vreinterpretq_f32_m128(in))); +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_cmple_pd(a, b)); #else - float32x4_t recipsq = vrsqrteq_f32(vreinterpretq_f32_m128(in)); - float32x4_t sq = vrecpeq_f32(recipsq); - // ??? use step versions of both sqrt and recip for better accuracy? - return vreinterpretq_m128_f32(sq); + // expand "_mm_cmpge_pd()" to reduce unnecessary operations + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) <= (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = a1; + + return vreinterpretq_m128d_u64(vld1q_u64(d)); #endif } -// Computes the approximation of the square root of the scalar single-precision -// floating point value of in. -// https://msdn.microsoft.com/en-us/library/ahfsc22d(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sqrt_ss(__m128 in) +// Compare packed signed 16-bit integers in a and b for less-than, and store the +// results in dst. Note: This intrinsic emits the pcmpgtw instruction with the +// order of the operands switched. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmplt_epi16 +FORCE_INLINE __m128i _mm_cmplt_epi16(__m128i a, __m128i b) { - float32_t value = - vgetq_lane_f32(vreinterpretq_f32_m128(_mm_sqrt_ps(in)), 0); - return vreinterpretq_m128_f32( - vsetq_lane_f32(value, vreinterpretq_f32_m128(in), 0)); + return vreinterpretq_m128i_u16( + vcltq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } -// Computes the approximations of the reciprocal square roots of the four -// single-precision floating point values of in. -// https://msdn.microsoft.com/en-us/library/22hfsh53(v=vs.100).aspx -FORCE_INLINE __m128 _mm_rsqrt_ps(__m128 in) +// Compare packed signed 32-bit integers in a and b for less-than, and store the +// results in dst. Note: This intrinsic emits the pcmpgtd instruction with the +// order of the operands switched. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmplt_epi32 +FORCE_INLINE __m128i _mm_cmplt_epi32(__m128i a, __m128i b) { - return vreinterpretq_m128_f32(vrsqrteq_f32(vreinterpretq_f32_m128(in))); + return vreinterpretq_m128i_u32( + vcltq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } -// Compute the approximate reciprocal square root of the lower single-precision -// (32-bit) floating-point element in a, store the result in the lower element -// of dst, and copy the upper 3 packed elements from a to the upper elements of -// dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_rsqrt_ss -FORCE_INLINE __m128 _mm_rsqrt_ss(__m128 in) +// Compare packed signed 8-bit integers in a and b for less-than, and store the +// results in dst. Note: This intrinsic emits the pcmpgtb instruction with the +// order of the operands switched. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmplt_epi8 +FORCE_INLINE __m128i _mm_cmplt_epi8(__m128i a, __m128i b) { - return vsetq_lane_f32(vgetq_lane_f32(_mm_rsqrt_ps(in), 0), in, 0); + return vreinterpretq_m128i_u8( + vcltq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } -// Compare packed signed 16-bit integers in a and b, and store packed maximum -// values in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// dst[i+15:i] := MAX(a[i+15:i], b[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_pi16 -FORCE_INLINE __m64 _mm_max_pi16(__m64 a, __m64 b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for less-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmplt_pd +FORCE_INLINE __m128d _mm_cmplt_pd(__m128d a, __m128d b) { - return vreinterpret_m64_s16( - vmax_s16(vreinterpret_s16_m64(a), vreinterpret_s16_m64(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64( + vcltq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) < (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = (*(double *) &a1) < (*(double *) &b1) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Compare packed signed 16-bit integers in a and b, and store packed maximum -// values in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// dst[i+15:i] := MAX(a[i+15:i], b[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_pi16 -#define _m_pmaxsw(a, b) _mm_max_pi16(a, b) - -// Computes the maximums of the four single-precision, floating-point values of -// a and b. -// https://msdn.microsoft.com/en-us/library/vstudio/ff5d607a(v=vs.100).aspx -FORCE_INLINE __m128 _mm_max_ps(__m128 a, __m128 b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for less-than, store the result in the lower element of dst, and copy the +// upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmplt_sd +FORCE_INLINE __m128d _mm_cmplt_sd(__m128d a, __m128d b) { -#if SSE2NEON_PRECISE_MINMAX - float32x4_t _a = vreinterpretq_f32_m128(a); - float32x4_t _b = vreinterpretq_f32_m128(b); - return vbslq_f32(vcltq_f32(_b, _a), _a, _b); +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_cmplt_pd(a, b)); #else - return vreinterpretq_m128_f32( - vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) < (*(double *) &b0) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = a1; + + return vreinterpretq_m128d_u64(vld1q_u64(d)); #endif } -// Compare packed unsigned 8-bit integers in a and b, and store packed maximum -// values in dst. -// -// FOR j := 0 to 7 -// i := j*8 -// dst[i+7:i] := MAX(a[i+7:i], b[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_pu8 -FORCE_INLINE __m64 _mm_max_pu8(__m64 a, __m64 b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for not-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpneq_pd +FORCE_INLINE __m128d _mm_cmpneq_pd(__m128d a, __m128d b) { - return vreinterpret_m64_u8( - vmax_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_s32(vmvnq_s32(vreinterpretq_s32_u64( + vceqq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))))); +#else + // (a == b) -> (a_lo == b_lo) && (a_hi == b_hi) + uint32x4_t cmp = + vceqq_u32(vreinterpretq_u32_m128d(a), vreinterpretq_u32_m128d(b)); + uint32x4_t swapped = vrev64q_u32(cmp); + return vreinterpretq_m128d_u32(vmvnq_u32(vandq_u32(cmp, swapped))); +#endif } -// Compare packed unsigned 8-bit integers in a and b, and store packed maximum -// values in dst. -// -// FOR j := 0 to 7 -// i := j*8 -// dst[i+7:i] := MAX(a[i+7:i], b[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_pu8 -#define _m_pmaxub(a, b) _mm_max_pu8(a, b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for not-equal, store the result in the lower element of dst, and copy the +// upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpneq_sd +FORCE_INLINE __m128d _mm_cmpneq_sd(__m128d a, __m128d b) +{ + return _mm_move_sd(a, _mm_cmpneq_pd(a, b)); +} -// Compare packed signed 16-bit integers in a and b, and store packed minimum -// values in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// dst[i+15:i] := MIN(a[i+15:i], b[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_min_pi16 -FORCE_INLINE __m64 _mm_min_pi16(__m64 a, __m64 b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for not-greater-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnge_pd +FORCE_INLINE __m128d _mm_cmpnge_pd(__m128d a, __m128d b) { - return vreinterpret_m64_s16( - vmin_s16(vreinterpret_s16_m64(a), vreinterpret_s16_m64(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64(veorq_u64( + vcgeq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b)), + vdupq_n_u64(UINT64_MAX))); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = + !((*(double *) &a0) >= (*(double *) &b0)) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = + !((*(double *) &a1) >= (*(double *) &b1)) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Compare packed signed 16-bit integers in a and b, and store packed minimum -// values in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// dst[i+15:i] := MIN(a[i+15:i], b[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_min_pi16 -#define _m_pminsw(a, b) _mm_min_pi16(a, b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for not-greater-than-or-equal, store the result in the lower element of +// dst, and copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnge_sd +FORCE_INLINE __m128d _mm_cmpnge_sd(__m128d a, __m128d b) +{ + return _mm_move_sd(a, _mm_cmpnge_pd(a, b)); +} -// Computes the minima of the four single-precision, floating-point values of a -// and b. -// https://msdn.microsoft.com/en-us/library/vstudio/wh13kadz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_min_ps(__m128 a, __m128 b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for not-greater-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_cmpngt_pd +FORCE_INLINE __m128d _mm_cmpngt_pd(__m128d a, __m128d b) { -#if SSE2NEON_PRECISE_MINMAX - float32x4_t _a = vreinterpretq_f32_m128(a); - float32x4_t _b = vreinterpretq_f32_m128(b); - return vbslq_f32(vcltq_f32(_a, _b), _a, _b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64(veorq_u64( + vcgtq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b)), + vdupq_n_u64(UINT64_MAX))); #else - return vreinterpretq_m128_f32( - vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = + !((*(double *) &a0) > (*(double *) &b0)) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = + !((*(double *) &a1) > (*(double *) &b1)) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); #endif } -// Compare packed unsigned 8-bit integers in a and b, and store packed minimum -// values in dst. -// -// FOR j := 0 to 7 -// i := j*8 -// dst[i+7:i] := MIN(a[i+7:i], b[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_min_pu8 -FORCE_INLINE __m64 _mm_min_pu8(__m64 a, __m64 b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for not-greater-than, store the result in the lower element of dst, and +// copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpngt_sd +FORCE_INLINE __m128d _mm_cmpngt_sd(__m128d a, __m128d b) { - return vreinterpret_m64_u8( - vmin_u8(vreinterpret_u8_m64(a), vreinterpret_u8_m64(b))); + return _mm_move_sd(a, _mm_cmpngt_pd(a, b)); } -// Compare packed unsigned 8-bit integers in a and b, and store packed minimum -// values in dst. -// -// FOR j := 0 to 7 -// i := j*8 -// dst[i+7:i] := MIN(a[i+7:i], b[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_min_pu8 -#define _m_pminub(a, b) _mm_min_pu8(a, b) - -// Computes the maximum of the two lower scalar single-precision floating point -// values of a and b. -// https://msdn.microsoft.com/en-us/library/s6db5esz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_max_ss(__m128 a, __m128 b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for not-less-than-or-equal, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnle_pd +FORCE_INLINE __m128d _mm_cmpnle_pd(__m128d a, __m128d b) { - float32_t value = vgetq_lane_f32(_mm_max_ps(a, b), 0); - return vreinterpretq_m128_f32( - vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64(veorq_u64( + vcleq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b)), + vdupq_n_u64(UINT64_MAX))); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = + !((*(double *) &a0) <= (*(double *) &b0)) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = + !((*(double *) &a1) <= (*(double *) &b1)) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Computes the minimum of the two lower scalar single-precision floating point -// values of a and b. -// https://msdn.microsoft.com/en-us/library/0a9y7xaa(v=vs.100).aspx -FORCE_INLINE __m128 _mm_min_ss(__m128 a, __m128 b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for not-less-than-or-equal, store the result in the lower element of dst, +// and copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnle_sd +FORCE_INLINE __m128d _mm_cmpnle_sd(__m128d a, __m128d b) { - float32_t value = vgetq_lane_f32(_mm_min_ps(a, b), 0); - return vreinterpretq_m128_f32( - vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); + return _mm_move_sd(a, _mm_cmpnle_pd(a, b)); } -// Computes the pairwise maxima of the 16 unsigned 8-bit integers from a and the -// 16 unsigned 8-bit integers from b. -// https://msdn.microsoft.com/en-us/library/st6634za(v=vs.100).aspx -FORCE_INLINE __m128i _mm_max_epu8(__m128i a, __m128i b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// for not-less-than, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnlt_pd +FORCE_INLINE __m128d _mm_cmpnlt_pd(__m128d a, __m128d b) { - return vreinterpretq_m128i_u8( - vmaxq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_u64(veorq_u64( + vcltq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b)), + vdupq_n_u64(UINT64_MAX))); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = + !((*(double *) &a0) < (*(double *) &b0)) ? ~UINT64_C(0) : UINT64_C(0); + d[1] = + !((*(double *) &a1) < (*(double *) &b1)) ? ~UINT64_C(0) : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Computes the pairwise minima of the 16 unsigned 8-bit integers from a and the -// 16 unsigned 8-bit integers from b. -// https://msdn.microsoft.com/ko-kr/library/17k8cf58(v=vs.100).aspxx -FORCE_INLINE __m128i _mm_min_epu8(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b for not-less-than, store the result in the lower element of dst, and copy +// the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpnlt_sd +FORCE_INLINE __m128d _mm_cmpnlt_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_u8( - vminq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); + return _mm_move_sd(a, _mm_cmpnlt_pd(a, b)); } -// Computes the pairwise minima of the 8 signed 16-bit integers from a and the 8 -// signed 16-bit integers from b. -// https://msdn.microsoft.com/en-us/library/vstudio/6te997ew(v=vs.100).aspx -FORCE_INLINE __m128i _mm_min_epi16(__m128i a, __m128i b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// to see if neither is NaN, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpord_pd +FORCE_INLINE __m128d _mm_cmpord_pd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s16( - vminq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + // Excluding NaNs, any two floating point numbers can be compared. + uint64x2_t not_nan_a = + vceqq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(a)); + uint64x2_t not_nan_b = + vceqq_f64(vreinterpretq_f64_m128d(b), vreinterpretq_f64_m128d(b)); + return vreinterpretq_m128d_u64(vandq_u64(not_nan_a, not_nan_b)); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = ((*(double *) &a0) == (*(double *) &a0) && + (*(double *) &b0) == (*(double *) &b0)) + ? ~UINT64_C(0) + : UINT64_C(0); + d[1] = ((*(double *) &a1) == (*(double *) &a1) && + (*(double *) &b1) == (*(double *) &b1)) + ? ~UINT64_C(0) + : UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Compare packed signed 8-bit integers in a and b, and store packed maximum -// values in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_epi8 -FORCE_INLINE __m128i _mm_max_epi8(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b to see if neither is NaN, store the result in the lower element of dst, and +// copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpord_sd +FORCE_INLINE __m128d _mm_cmpord_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s8( - vmaxq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_cmpord_pd(a, b)); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t d[2]; + d[0] = ((*(double *) &a0) == (*(double *) &a0) && + (*(double *) &b0) == (*(double *) &b0)) + ? ~UINT64_C(0) + : UINT64_C(0); + d[1] = a1; + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Compare packed unsigned 16-bit integers in a and b, and store packed maximum -// values in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_epu16 -FORCE_INLINE __m128i _mm_max_epu16(__m128i a, __m128i b) +// Compare packed double-precision (64-bit) floating-point elements in a and b +// to see if either is NaN, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpunord_pd +FORCE_INLINE __m128d _mm_cmpunord_pd(__m128d a, __m128d b) { - return vreinterpretq_m128i_u16( - vmaxq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + // Two NaNs are not equal in comparison operation. + uint64x2_t not_nan_a = + vceqq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(a)); + uint64x2_t not_nan_b = + vceqq_f64(vreinterpretq_f64_m128d(b), vreinterpretq_f64_m128d(b)); + return vreinterpretq_m128d_s32( + vmvnq_s32(vreinterpretq_s32_u64(vandq_u64(not_nan_a, not_nan_b)))); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = ((*(double *) &a0) == (*(double *) &a0) && + (*(double *) &b0) == (*(double *) &b0)) + ? UINT64_C(0) + : ~UINT64_C(0); + d[1] = ((*(double *) &a1) == (*(double *) &a1) && + (*(double *) &b1) == (*(double *) &b1)) + ? UINT64_C(0) + : ~UINT64_C(0); + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Compare packed signed 8-bit integers in a and b, and store packed minimum -// values in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_min_epi8 -FORCE_INLINE __m128i _mm_min_epi8(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b to see if either is NaN, store the result in the lower element of dst, and +// copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpunord_sd +FORCE_INLINE __m128d _mm_cmpunord_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s8( - vminq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_cmpunord_pd(a, b)); +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t d[2]; + d[0] = ((*(double *) &a0) == (*(double *) &a0) && + (*(double *) &b0) == (*(double *) &b0)) + ? UINT64_C(0) + : ~UINT64_C(0); + d[1] = a1; + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Compare packed unsigned 16-bit integers in a and b, and store packed minimum -// values in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_min_epu16 -FORCE_INLINE __m128i _mm_min_epu16(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point element in a and b +// for greater-than-or-equal, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comige_sd +FORCE_INLINE int _mm_comige_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_u16( - vminq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vgetq_lane_u64(vcgeq_f64(a, b), 0) & 0x1; +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + + return (*(double *) &a0 >= *(double *) &b0); +#endif } -// Computes the pairwise maxima of the 8 signed 16-bit integers from a and the 8 -// signed 16-bit integers from b. -// https://msdn.microsoft.com/en-us/LIBRary/3x060h7c(v=vs.100).aspx -FORCE_INLINE __m128i _mm_max_epi16(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point element in a and b +// for greater-than, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comigt_sd +FORCE_INLINE int _mm_comigt_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s16( - vmaxq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vgetq_lane_u64(vcgtq_f64(a, b), 0) & 0x1; +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + + return (*(double *) &a0 > *(double *) &b0); +#endif } -// epi versions of min/max -// Computes the pariwise maximums of the four signed 32-bit integer values of a -// and b. -// -// A 128-bit parameter that can be defined with the following equations: -// r0 := (a0 > b0) ? a0 : b0 -// r1 := (a1 > b1) ? a1 : b1 -// r2 := (a2 > b2) ? a2 : b2 -// r3 := (a3 > b3) ? a3 : b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/bb514055(v=vs.100).aspx -FORCE_INLINE __m128i _mm_max_epi32(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point element in a and b +// for less-than-or-equal, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comile_sd +FORCE_INLINE int _mm_comile_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s32( - vmaxq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vgetq_lane_u64(vcleq_f64(a, b), 0) & 0x1; +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + + return (*(double *) &a0 <= *(double *) &b0); +#endif } -// Computes the pariwise minima of the four signed 32-bit integer values of a -// and b. -// -// A 128-bit parameter that can be defined with the following equations: -// r0 := (a0 < b0) ? a0 : b0 -// r1 := (a1 < b1) ? a1 : b1 -// r2 := (a2 < b2) ? a2 : b2 -// r3 := (a3 < b3) ? a3 : b3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/bb531476(v=vs.100).aspx -FORCE_INLINE __m128i _mm_min_epi32(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point element in a and b +// for less-than, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comilt_sd +FORCE_INLINE int _mm_comilt_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_s32( - vminq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vgetq_lane_u64(vcltq_f64(a, b), 0) & 0x1; +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + + return (*(double *) &a0 < *(double *) &b0); +#endif } -// Compare packed unsigned 32-bit integers in a and b, and store packed maximum -// values in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_epu32 -FORCE_INLINE __m128i _mm_max_epu32(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point element in a and b +// for equality, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comieq_sd +FORCE_INLINE int _mm_comieq_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_u32( - vmaxq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vgetq_lane_u64(vceqq_f64(a, b), 0) & 0x1; +#else + uint32x4_t a_not_nan = + vceqq_u32(vreinterpretq_u32_m128d(a), vreinterpretq_u32_m128d(a)); + uint32x4_t b_not_nan = + vceqq_u32(vreinterpretq_u32_m128d(b), vreinterpretq_u32_m128d(b)); + uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); + uint32x4_t a_eq_b = + vceqq_u32(vreinterpretq_u32_m128d(a), vreinterpretq_u32_m128d(b)); + uint64x2_t and_results = vandq_u64(vreinterpretq_u64_u32(a_and_b_not_nan), + vreinterpretq_u64_u32(a_eq_b)); + return vgetq_lane_u64(and_results, 0) & 0x1; +#endif } -// Compare packed unsigned 32-bit integers in a and b, and store packed minimum -// values in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_max_epu32 -FORCE_INLINE __m128i _mm_min_epu32(__m128i a, __m128i b) +// Compare the lower double-precision (64-bit) floating-point element in a and b +// for not-equal, and return the boolean result (0 or 1). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_comineq_sd +FORCE_INLINE int _mm_comineq_sd(__m128d a, __m128d b) { - return vreinterpretq_m128i_u32( - vminq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b))); + return !_mm_comieq_sd(a, b); } -// Multiply the packed unsigned 16-bit integers in a and b, producing -// intermediate 32-bit integers, and store the high 16 bits of the intermediate -// integers in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_mulhi_pu16 -FORCE_INLINE __m64 _mm_mulhi_pu16(__m64 a, __m64 b) +// Convert packed signed 32-bit integers in a to packed double-precision +// (64-bit) floating-point elements, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi32_pd +FORCE_INLINE __m128d _mm_cvtepi32_pd(__m128i a) { - return vreinterpret_m64_u16(vshrn_n_u32( - vmull_u16(vreinterpret_u16_m64(a), vreinterpret_u16_m64(b)), 16)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vcvtq_f64_s64(vmovl_s32(vget_low_s32(vreinterpretq_s32_m128i(a))))); +#else + double a0 = (double) vgetq_lane_s32(vreinterpretq_s32_m128i(a), 0); + double a1 = (double) vgetq_lane_s32(vreinterpretq_s32_m128i(a), 1); + return _mm_set_pd(a1, a0); +#endif } -// Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit -// integers from b. -// -// r0 := (a0 * b0)[31:16] -// r1 := (a1 * b1)[31:16] -// ... -// r7 := (a7 * b7)[31:16] -// -// https://msdn.microsoft.com/en-us/library/vstudio/59hddw1d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mulhi_epi16(__m128i a, __m128i b) +// Convert packed signed 32-bit integers in a to packed single-precision +// (32-bit) floating-point elements, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi32_ps +FORCE_INLINE __m128 _mm_cvtepi32_ps(__m128i a) { - /* FIXME: issue with large values because of result saturation */ - // int16x8_t ret = vqdmulhq_s16(vreinterpretq_s16_m128i(a), - // vreinterpretq_s16_m128i(b)); /* =2*a*b */ return - // vreinterpretq_m128i_s16(vshrq_n_s16(ret, 1)); - int16x4_t a3210 = vget_low_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b3210 = vget_low_s16(vreinterpretq_s16_m128i(b)); - int32x4_t ab3210 = vmull_s16(a3210, b3210); /* 3333222211110000 */ - int16x4_t a7654 = vget_high_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b7654 = vget_high_s16(vreinterpretq_s16_m128i(b)); - int32x4_t ab7654 = vmull_s16(a7654, b7654); /* 7777666655554444 */ - uint16x8x2_t r = - vuzpq_u16(vreinterpretq_u16_s32(ab3210), vreinterpretq_u16_s32(ab7654)); - return vreinterpretq_m128i_u16(r.val[1]); + return vreinterpretq_m128_f32(vcvtq_f32_s32(vreinterpretq_s32_m128i(a))); } -// Multiply the packed unsigned 16-bit integers in a and b, producing -// intermediate 32-bit integers, and store the high 16 bits of the intermediate -// integers in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_mulhi_epu16 -FORCE_INLINE __m128i _mm_mulhi_epu16(__m128i a, __m128i b) +// Convert packed double-precision (64-bit) floating-point elements in a to +// packed 32-bit integers, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpd_epi32 +FORCE_INLINE __m128i _mm_cvtpd_epi32(__m128d a) { - uint16x4_t a3210 = vget_low_u16(vreinterpretq_u16_m128i(a)); - uint16x4_t b3210 = vget_low_u16(vreinterpretq_u16_m128i(b)); - uint32x4_t ab3210 = vmull_u16(a3210, b3210); -#if defined(__aarch64__) - uint32x4_t ab7654 = - vmull_high_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b)); - uint16x8_t r = vuzp2q_u16(vreinterpretq_u16_u32(ab3210), - vreinterpretq_u16_u32(ab7654)); - return vreinterpretq_m128i_u16(r); +// vrnd32xq_f64 not supported on clang +#if defined(__ARM_FEATURE_FRINT) && !defined(__clang__) + float64x2_t rounded = vrnd32xq_f64(vreinterpretq_f64_m128d(a)); + int64x2_t integers = vcvtq_s64_f64(rounded); + return vreinterpretq_m128i_s32( + vcombine_s32(vmovn_s64(integers), vdup_n_s32(0))); #else - uint16x4_t a7654 = vget_high_u16(vreinterpretq_u16_m128i(a)); - uint16x4_t b7654 = vget_high_u16(vreinterpretq_u16_m128i(b)); - uint32x4_t ab7654 = vmull_u16(a7654, b7654); - uint16x8x2_t r = - vuzpq_u16(vreinterpretq_u16_u32(ab3210), vreinterpretq_u16_u32(ab7654)); - return vreinterpretq_m128i_u16(r.val[1]); + __m128d rnd = _mm_round_pd(a, _MM_FROUND_CUR_DIRECTION); + double d0 = ((double *) &rnd)[0]; + double d1 = ((double *) &rnd)[1]; + return _mm_set_epi32(0, 0, (int32_t) d1, (int32_t) d0); #endif } -// Computes pairwise add of each argument as single-precision, floating-point -// values a and b. -// https://msdn.microsoft.com/en-us/library/yd9wecaa.aspx -FORCE_INLINE __m128 _mm_hadd_ps(__m128 a, __m128 b) +// Convert packed double-precision (64-bit) floating-point elements in a to +// packed 32-bit integers, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpd_pi32 +FORCE_INLINE __m64 _mm_cvtpd_pi32(__m128d a) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32( - vpaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -#else - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32( - vcombine_f32(vpadd_f32(a10, a32), vpadd_f32(b10, b32))); -#endif + __m128d rnd = _mm_round_pd(a, _MM_FROUND_CUR_DIRECTION); + double d0 = ((double *) &rnd)[0]; + double d1 = ((double *) &rnd)[1]; + int32_t ALIGN_STRUCT(16) data[2] = {(int32_t) d0, (int32_t) d1}; + return vreinterpret_m64_s32(vld1_s32(data)); } -// Computes pairwise add of each argument as a 16-bit signed or unsigned integer -// values a and b. -FORCE_INLINE __m128i _mm_hadd_epi16(__m128i _a, __m128i _b) +// Convert packed double-precision (64-bit) floating-point elements in a to +// packed single-precision (32-bit) floating-point elements, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpd_ps +FORCE_INLINE __m128 _mm_cvtpd_ps(__m128d a) { - int16x8_t a = vreinterpretq_s16_m128i(_a); - int16x8_t b = vreinterpretq_s16_m128i(_b); -#if defined(__aarch64__) - return vreinterpretq_m128i_s16(vpaddq_s16(a, b)); +#if defined(__aarch64__) || defined(_M_ARM64) + float32x2_t tmp = vcvt_f32_f64(vreinterpretq_f64_m128d(a)); + return vreinterpretq_m128_f32(vcombine_f32(tmp, vdup_n_f32(0))); #else - return vreinterpretq_m128i_s16( - vcombine_s16(vpadd_s16(vget_low_s16(a), vget_high_s16(a)), - vpadd_s16(vget_low_s16(b), vget_high_s16(b)))); + float a0 = (float) ((double *) &a)[0]; + float a1 = (float) ((double *) &a)[1]; + return _mm_set_ps(0, 0, a1, a0); #endif } -// Horizontally substract adjacent pairs of single-precision (32-bit) -// floating-point elements in a and b, and pack the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_hsub_ps -FORCE_INLINE __m128 _mm_hsub_ps(__m128 _a, __m128 _b) +// Convert packed signed 32-bit integers in a to packed double-precision +// (64-bit) floating-point elements, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtpi32_pd +FORCE_INLINE __m128d _mm_cvtpi32_pd(__m64 a) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32(vsubq_f32( - vuzp1q_f32(vreinterpretq_f32_m128(_a), vreinterpretq_f32_m128(_b)), - vuzp2q_f32(vreinterpretq_f32_m128(_a), vreinterpretq_f32_m128(_b)))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vcvtq_f64_s64(vmovl_s32(vreinterpret_s32_m64(a)))); #else - float32x4x2_t c = - vuzpq_f32(vreinterpretq_f32_m128(_a), vreinterpretq_f32_m128(_b)); - return vreinterpretq_m128_f32(vsubq_f32(c.val[0], c.val[1])); + double a0 = (double) vget_lane_s32(vreinterpret_s32_m64(a), 0); + double a1 = (double) vget_lane_s32(vreinterpret_s32_m64(a), 1); + return _mm_set_pd(a1, a0); #endif } -// Horizontally add adjacent pairs of 16-bit integers in a and b, and pack the -// signed 16-bit results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_hadd_pi16 -FORCE_INLINE __m64 _mm_hadd_pi16(__m64 a, __m64 b) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 32-bit integers, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtps_epi32 +// *NOTE*. The default rounding mode on SSE is 'round to even', which ARMv7-A +// does not support! It is supported on ARMv8-A however. +FORCE_INLINE __m128i _mm_cvtps_epi32(__m128 a) { - return vreinterpret_m64_s16( - vpadd_s16(vreinterpret_s16_m64(a), vreinterpret_s16_m64(b))); +#if defined(__ARM_FEATURE_FRINT) + return vreinterpretq_m128i_s32(vcvtq_s32_f32(vrnd32xq_f32(a))); +#elif (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_DIRECTED_ROUNDING) + switch (_MM_GET_ROUNDING_MODE()) { + case _MM_ROUND_NEAREST: + return vreinterpretq_m128i_s32(vcvtnq_s32_f32(a)); + case _MM_ROUND_DOWN: + return vreinterpretq_m128i_s32(vcvtmq_s32_f32(a)); + case _MM_ROUND_UP: + return vreinterpretq_m128i_s32(vcvtpq_s32_f32(a)); + default: // _MM_ROUND_TOWARD_ZERO + return vreinterpretq_m128i_s32(vcvtq_s32_f32(a)); + } +#else + float *f = (float *) &a; + switch (_MM_GET_ROUNDING_MODE()) { + case _MM_ROUND_NEAREST: { + uint32x4_t signmask = vdupq_n_u32(0x80000000); + float32x4_t half = vbslq_f32(signmask, vreinterpretq_f32_m128(a), + vdupq_n_f32(0.5f)); /* +/- 0.5 */ + int32x4_t r_normal = vcvtq_s32_f32(vaddq_f32( + vreinterpretq_f32_m128(a), half)); /* round to integer: [a + 0.5]*/ + int32x4_t r_trunc = vcvtq_s32_f32( + vreinterpretq_f32_m128(a)); /* truncate to integer: [a] */ + int32x4_t plusone = vreinterpretq_s32_u32(vshrq_n_u32( + vreinterpretq_u32_s32(vnegq_s32(r_trunc)), 31)); /* 1 or 0 */ + int32x4_t r_even = vbicq_s32(vaddq_s32(r_trunc, plusone), + vdupq_n_s32(1)); /* ([a] + {0,1}) & ~1 */ + float32x4_t delta = vsubq_f32( + vreinterpretq_f32_m128(a), + vcvtq_f32_s32(r_trunc)); /* compute delta: delta = (a - [a]) */ + uint32x4_t is_delta_half = + vceqq_f32(delta, half); /* delta == +/- 0.5 */ + return vreinterpretq_m128i_s32( + vbslq_s32(is_delta_half, r_even, r_normal)); + } + case _MM_ROUND_DOWN: + return _mm_set_epi32(floorf(f[3]), floorf(f[2]), floorf(f[1]), + floorf(f[0])); + case _MM_ROUND_UP: + return _mm_set_epi32(ceilf(f[3]), ceilf(f[2]), ceilf(f[1]), + ceilf(f[0])); + default: // _MM_ROUND_TOWARD_ZERO + return _mm_set_epi32((int32_t) f[3], (int32_t) f[2], (int32_t) f[1], + (int32_t) f[0]); + } +#endif } -// Horizontally add adjacent pairs of 32-bit integers in a and b, and pack the -// signed 32-bit results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_hadd_pi32 -FORCE_INLINE __m64 _mm_hadd_pi32(__m64 a, __m64 b) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed double-precision (64-bit) floating-point elements, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtps_pd +FORCE_INLINE __m128d _mm_cvtps_pd(__m128 a) { - return vreinterpret_m64_s32( - vpadd_s32(vreinterpret_s32_m64(a), vreinterpret_s32_m64(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vcvt_f64_f32(vget_low_f32(vreinterpretq_f32_m128(a)))); +#else + double a0 = (double) vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); + double a1 = (double) vgetq_lane_f32(vreinterpretq_f32_m128(a), 1); + return _mm_set_pd(a1, a0); +#endif } -// Computes pairwise difference of each argument as a 16-bit signed or unsigned -// integer values a and b. -FORCE_INLINE __m128i _mm_hsub_epi16(__m128i _a, __m128i _b) +// Copy the lower double-precision (64-bit) floating-point element of a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsd_f64 +FORCE_INLINE double _mm_cvtsd_f64(__m128d a) { - int32x4_t a = vreinterpretq_s32_m128i(_a); - int32x4_t b = vreinterpretq_s32_m128i(_b); - // Interleave using vshrn/vmovn - // [a0|a2|a4|a6|b0|b2|b4|b6] - // [a1|a3|a5|a7|b1|b3|b5|b7] - int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b)); - int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16)); - // Subtract - return vreinterpretq_m128i_s16(vsubq_s16(ab0246, ab1357)); +#if defined(__aarch64__) || defined(_M_ARM64) + return (double) vgetq_lane_f64(vreinterpretq_f64_m128d(a), 0); +#else + return ((double *) &a)[0]; +#endif } -// Computes saturated pairwise sub of each argument as a 16-bit signed -// integer values a and b. -FORCE_INLINE __m128i _mm_hadds_epi16(__m128i _a, __m128i _b) +// Convert the lower double-precision (64-bit) floating-point element in a to a +// 32-bit integer, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsd_si32 +FORCE_INLINE int32_t _mm_cvtsd_si32(__m128d a) { -#if defined(__aarch64__) - int16x8_t a = vreinterpretq_s16_m128i(_a); - int16x8_t b = vreinterpretq_s16_m128i(_b); - return vreinterpretq_s64_s16( - vqaddq_s16(vuzp1q_s16(a, b), vuzp2q_s16(a, b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return (int32_t) vgetq_lane_f64(vrndiq_f64(vreinterpretq_f64_m128d(a)), 0); #else - int32x4_t a = vreinterpretq_s32_m128i(_a); - int32x4_t b = vreinterpretq_s32_m128i(_b); - // Interleave using vshrn/vmovn - // [a0|a2|a4|a6|b0|b2|b4|b6] - // [a1|a3|a5|a7|b1|b3|b5|b7] - int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b)); - int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16)); - // Saturated add - return vreinterpretq_m128i_s16(vqaddq_s16(ab0246, ab1357)); + __m128d rnd = _mm_round_pd(a, _MM_FROUND_CUR_DIRECTION); + double ret = ((double *) &rnd)[0]; + return (int32_t) ret; #endif } -// Computes saturated pairwise difference of each argument as a 16-bit signed -// integer values a and b. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_hsubs_epi16 -FORCE_INLINE __m128i _mm_hsubs_epi16(__m128i _a, __m128i _b) +// Convert the lower double-precision (64-bit) floating-point element in a to a +// 64-bit integer, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsd_si64 +FORCE_INLINE int64_t _mm_cvtsd_si64(__m128d a) { -#if defined(__aarch64__) - int16x8_t a = vreinterpretq_s16_m128i(_a); - int16x8_t b = vreinterpretq_s16_m128i(_b); - return vreinterpretq_s64_s16( - vqsubq_s16(vuzp1q_s16(a, b), vuzp2q_s16(a, b))); +#if defined(__aarch64__) || defined(_M_ARM64) + return (int64_t) vgetq_lane_f64(vrndiq_f64(vreinterpretq_f64_m128d(a)), 0); #else - int32x4_t a = vreinterpretq_s32_m128i(_a); - int32x4_t b = vreinterpretq_s32_m128i(_b); - // Interleave using vshrn/vmovn - // [a0|a2|a4|a6|b0|b2|b4|b6] - // [a1|a3|a5|a7|b1|b3|b5|b7] - int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b)); - int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16)); - // Saturated subtract - return vreinterpretq_m128i_s16(vqsubq_s16(ab0246, ab1357)); + __m128d rnd = _mm_round_pd(a, _MM_FROUND_CUR_DIRECTION); + double ret = ((double *) &rnd)[0]; + return (int64_t) ret; #endif } -// Computes pairwise add of each argument as a 32-bit signed or unsigned integer -// values a and b. -FORCE_INLINE __m128i _mm_hadd_epi32(__m128i _a, __m128i _b) -{ - int32x4_t a = vreinterpretq_s32_m128i(_a); - int32x4_t b = vreinterpretq_s32_m128i(_b); - return vreinterpretq_m128i_s32( - vcombine_s32(vpadd_s32(vget_low_s32(a), vget_high_s32(a)), - vpadd_s32(vget_low_s32(b), vget_high_s32(b)))); +// Convert the lower double-precision (64-bit) floating-point element in a to a +// 64-bit integer, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsd_si64x +#define _mm_cvtsd_si64x _mm_cvtsd_si64 + +// Convert the lower double-precision (64-bit) floating-point element in b to a +// single-precision (32-bit) floating-point element, store the result in the +// lower element of dst, and copy the upper 3 packed elements from a to the +// upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsd_ss +FORCE_INLINE __m128 _mm_cvtsd_ss(__m128 a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32(vsetq_lane_f32( + vget_lane_f32(vcvt_f32_f64(vreinterpretq_f64_m128d(b)), 0), + vreinterpretq_f32_m128(a), 0)); +#else + return vreinterpretq_m128_f32(vsetq_lane_f32((float) ((double *) &b)[0], + vreinterpretq_f32_m128(a), 0)); +#endif } -// Computes pairwise difference of each argument as a 32-bit signed or unsigned -// integer values a and b. -FORCE_INLINE __m128i _mm_hsub_epi32(__m128i _a, __m128i _b) +// Copy the lower 32-bit integer in a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi128_si32 +FORCE_INLINE int _mm_cvtsi128_si32(__m128i a) { - int64x2_t a = vreinterpretq_s64_m128i(_a); - int64x2_t b = vreinterpretq_s64_m128i(_b); - // Interleave using vshrn/vmovn - // [a0|a2|b0|b2] - // [a1|a2|b1|b3] - int32x4_t ab02 = vcombine_s32(vmovn_s64(a), vmovn_s64(b)); - int32x4_t ab13 = vcombine_s32(vshrn_n_s64(a, 32), vshrn_n_s64(b, 32)); - // Subtract - return vreinterpretq_m128i_s32(vsubq_s32(ab02, ab13)); + return vgetq_lane_s32(vreinterpretq_s32_m128i(a), 0); } -// Kahan summation for accurate summation of floating-point numbers. -// http://blog.zachbjornson.com/2019/08/11/fast-float-summation.html -FORCE_INLINE void sse2neon_kadd_f32(float *sum, float *c, float y) +// Copy the lower 64-bit integer in a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi128_si64 +FORCE_INLINE int64_t _mm_cvtsi128_si64(__m128i a) { - y -= *c; - float t = *sum + y; - *c = (t - *sum) - y; - *sum = t; + return vgetq_lane_s64(vreinterpretq_s64_m128i(a), 0); } -// Conditionally multiply the packed single-precision (32-bit) floating-point -// elements in a and b using the high 4 bits in imm8, sum the four products, -// and conditionally store the sum in dst using the low 4 bits of imm. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_dp_ps -FORCE_INLINE __m128 _mm_dp_ps(__m128 a, __m128 b, const int imm) +// Copy the lower 64-bit integer in a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi128_si64x +#define _mm_cvtsi128_si64x(a) _mm_cvtsi128_si64(a) + +// Convert the signed 32-bit integer b to a double-precision (64-bit) +// floating-point element, store the result in the lower element of dst, and +// copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi32_sd +FORCE_INLINE __m128d _mm_cvtsi32_sd(__m128d a, int32_t b) { -#if defined(__aarch64__) - /* shortcuts */ - if (imm == 0xFF) { - return _mm_set1_ps(vaddvq_f32(_mm_mul_ps(a, b))); - } - if (imm == 0x7F) { - float32x4_t m = _mm_mul_ps(a, b); - m[3] = 0; - return _mm_set1_ps(vaddvq_f32(m)); - } +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vsetq_lane_f64((double) b, vreinterpretq_f64_m128d(a), 0)); +#else + double bf = (double) b; + return vreinterpretq_m128d_s64( + vsetq_lane_s64(*(int64_t *) &bf, vreinterpretq_s64_m128d(a), 0)); #endif - - float s = 0, c = 0; - float32x4_t f32a = vreinterpretq_f32_m128(a); - float32x4_t f32b = vreinterpretq_f32_m128(b); - - /* To improve the accuracy of floating-point summation, Kahan algorithm - * is used for each operation. - */ - if (imm & (1 << 4)) - sse2neon_kadd_f32(&s, &c, f32a[0] * f32b[0]); - if (imm & (1 << 5)) - sse2neon_kadd_f32(&s, &c, f32a[1] * f32b[1]); - if (imm & (1 << 6)) - sse2neon_kadd_f32(&s, &c, f32a[2] * f32b[2]); - if (imm & (1 << 7)) - sse2neon_kadd_f32(&s, &c, f32a[3] * f32b[3]); - s += c; - - float32x4_t res = { - (imm & 0x1) ? s : 0, - (imm & 0x2) ? s : 0, - (imm & 0x4) ? s : 0, - (imm & 0x8) ? s : 0, - }; - return vreinterpretq_m128_f32(res); } -/* Compare operations */ +// Copy the lower 64-bit integer in a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi128_si64x +#define _mm_cvtsi128_si64x(a) _mm_cvtsi128_si64(a) -// Compares for less than -// https://msdn.microsoft.com/en-us/library/vstudio/f330yhc8(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmplt_ps(__m128 a, __m128 b) +// Copy 32-bit integer a to the lower elements of dst, and zero the upper +// elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi32_si128 +FORCE_INLINE __m128i _mm_cvtsi32_si128(int a) { - return vreinterpretq_m128_u32( - vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + return vreinterpretq_m128i_s32(vsetq_lane_s32(a, vdupq_n_s32(0), 0)); } -// Compares for less than -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/fy94wye7(v=vs.100) -FORCE_INLINE __m128 _mm_cmplt_ss(__m128 a, __m128 b) +// Convert the signed 64-bit integer b to a double-precision (64-bit) +// floating-point element, store the result in the lower element of dst, and +// copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi64_sd +FORCE_INLINE __m128d _mm_cvtsi64_sd(__m128d a, int64_t b) { - return _mm_move_ss(a, _mm_cmplt_ps(a, b)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vsetq_lane_f64((double) b, vreinterpretq_f64_m128d(a), 0)); +#else + double bf = (double) b; + return vreinterpretq_m128d_s64( + vsetq_lane_s64(*(int64_t *) &bf, vreinterpretq_s64_m128d(a), 0)); +#endif } -// Compares for greater than. -// -// r0 := (a0 > b0) ? 0xffffffff : 0x0 -// r1 := (a1 > b1) ? 0xffffffff : 0x0 -// r2 := (a2 > b2) ? 0xffffffff : 0x0 -// r3 := (a3 > b3) ? 0xffffffff : 0x0 -// -// https://msdn.microsoft.com/en-us/library/vstudio/11dy102s(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpgt_ps(__m128 a, __m128 b) +// Copy 64-bit integer a to the lower element of dst, and zero the upper +// element. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi64_si128 +FORCE_INLINE __m128i _mm_cvtsi64_si128(int64_t a) { - return vreinterpretq_m128_u32( - vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + return vreinterpretq_m128i_s64(vsetq_lane_s64(a, vdupq_n_s64(0), 0)); } -// Compares for greater than. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/1xyyyy9e(v=vs.100) -FORCE_INLINE __m128 _mm_cmpgt_ss(__m128 a, __m128 b) -{ - return _mm_move_ss(a, _mm_cmpgt_ps(a, b)); -} +// Copy 64-bit integer a to the lower element of dst, and zero the upper +// element. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi64x_si128 +#define _mm_cvtsi64x_si128(a) _mm_cvtsi64_si128(a) -// Compares for greater than or equal. -// https://msdn.microsoft.com/en-us/library/vstudio/fs813y2t(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpge_ps(__m128 a, __m128 b) +// Convert the signed 64-bit integer b to a double-precision (64-bit) +// floating-point element, store the result in the lower element of dst, and +// copy the upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtsi64x_sd +#define _mm_cvtsi64x_sd(a, b) _mm_cvtsi64_sd(a, b) + +// Convert the lower single-precision (32-bit) floating-point element in b to a +// double-precision (64-bit) floating-point element, store the result in the +// lower element of dst, and copy the upper element from a to the upper element +// of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtss_sd +FORCE_INLINE __m128d _mm_cvtss_sd(__m128d a, __m128 b) { - return vreinterpretq_m128_u32( - vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + double d = (double) vgetq_lane_f32(vreinterpretq_f32_m128(b), 0); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vsetq_lane_f64(d, vreinterpretq_f64_m128d(a), 0)); +#else + return vreinterpretq_m128d_s64( + vsetq_lane_s64(*(int64_t *) &d, vreinterpretq_s64_m128d(a), 0)); +#endif } -// Compares for greater than or equal. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/kesh3ddc(v=vs.100) -FORCE_INLINE __m128 _mm_cmpge_ss(__m128 a, __m128 b) +// Convert packed double-precision (64-bit) floating-point elements in a to +// packed 32-bit integers with truncation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttpd_epi32 +FORCE_INLINE __m128i _mm_cvttpd_epi32(__m128d a) { - return _mm_move_ss(a, _mm_cmpge_ps(a, b)); + double a0 = ((double *) &a)[0]; + double a1 = ((double *) &a)[1]; + return _mm_set_epi32(0, 0, (int32_t) a1, (int32_t) a0); } -// Compares for less than or equal. -// -// r0 := (a0 <= b0) ? 0xffffffff : 0x0 -// r1 := (a1 <= b1) ? 0xffffffff : 0x0 -// r2 := (a2 <= b2) ? 0xffffffff : 0x0 -// r3 := (a3 <= b3) ? 0xffffffff : 0x0 -// -// https://msdn.microsoft.com/en-us/library/vstudio/1s75w83z(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmple_ps(__m128 a, __m128 b) +// Convert packed double-precision (64-bit) floating-point elements in a to +// packed 32-bit integers with truncation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttpd_pi32 +FORCE_INLINE __m64 _mm_cvttpd_pi32(__m128d a) { - return vreinterpretq_m128_u32( - vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + double a0 = ((double *) &a)[0]; + double a1 = ((double *) &a)[1]; + int32_t ALIGN_STRUCT(16) data[2] = {(int32_t) a0, (int32_t) a1}; + return vreinterpret_m64_s32(vld1_s32(data)); } -// Compares for less than or equal. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/a7x0hbhw(v=vs.100) -FORCE_INLINE __m128 _mm_cmple_ss(__m128 a, __m128 b) +// Convert packed single-precision (32-bit) floating-point elements in a to +// packed 32-bit integers with truncation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttps_epi32 +FORCE_INLINE __m128i _mm_cvttps_epi32(__m128 a) { - return _mm_move_ss(a, _mm_cmple_ps(a, b)); + return vreinterpretq_m128i_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a))); } -// Compares for equality. -// https://msdn.microsoft.com/en-us/library/vstudio/36aectz5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpeq_ps(__m128 a, __m128 b) +// Convert the lower double-precision (64-bit) floating-point element in a to a +// 32-bit integer with truncation, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttsd_si32 +FORCE_INLINE int32_t _mm_cvttsd_si32(__m128d a) { - return vreinterpretq_m128_u32( - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); + double ret = *((double *) &a); + return (int32_t) ret; } -// Compares for equality. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/k423z28e(v=vs.100) -FORCE_INLINE __m128 _mm_cmpeq_ss(__m128 a, __m128 b) +// Convert the lower double-precision (64-bit) floating-point element in a to a +// 64-bit integer with truncation, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttsd_si64 +FORCE_INLINE int64_t _mm_cvttsd_si64(__m128d a) { - return _mm_move_ss(a, _mm_cmpeq_ps(a, b)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vgetq_lane_s64(vcvtq_s64_f64(vreinterpretq_f64_m128d(a)), 0); +#else + double ret = *((double *) &a); + return (int64_t) ret; +#endif } -// Compares for inequality. -// https://msdn.microsoft.com/en-us/library/sf44thbx(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpneq_ps(__m128 a, __m128 b) +// Convert the lower double-precision (64-bit) floating-point element in a to a +// 64-bit integer with truncation, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvttsd_si64x +#define _mm_cvttsd_si64x(a) _mm_cvttsd_si64(a) + +// Divide packed double-precision (64-bit) floating-point elements in a by +// packed elements in b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_div_pd +FORCE_INLINE __m128d _mm_div_pd(__m128d a, __m128d b) { - return vreinterpretq_m128_u32(vmvnq_u32( - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vdivq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + double *da = (double *) &a; + double *db = (double *) &b; + double c[2]; + c[0] = da[0] / db[0]; + c[1] = da[1] / db[1]; + return vld1q_f32((float32_t *) c); +#endif } -// Compares for inequality. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ekya8fh4(v=vs.100) -FORCE_INLINE __m128 _mm_cmpneq_ss(__m128 a, __m128 b) +// Divide the lower double-precision (64-bit) floating-point element in a by the +// lower double-precision (64-bit) floating-point element in b, store the result +// in the lower element of dst, and copy the upper element from a to the upper +// element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_div_sd +FORCE_INLINE __m128d _mm_div_sd(__m128d a, __m128d b) { - return _mm_move_ss(a, _mm_cmpneq_ps(a, b)); +#if defined(__aarch64__) || defined(_M_ARM64) + float64x2_t tmp = + vdivq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b)); + return vreinterpretq_m128d_f64( + vsetq_lane_f64(vgetq_lane_f64(vreinterpretq_f64_m128d(a), 1), tmp, 1)); +#else + return _mm_move_sd(a, _mm_div_pd(a, b)); +#endif } -// Compares for not greater than or equal. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/wsexys62(v=vs.100) -FORCE_INLINE __m128 _mm_cmpnge_ps(__m128 a, __m128 b) +// Extract a 16-bit integer from a, selected with imm8, and store the result in +// the lower element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_extract_epi16 +// FORCE_INLINE int _mm_extract_epi16(__m128i a, __constrange(0,8) int imm) +#define _mm_extract_epi16(a, imm) \ + vgetq_lane_u16(vreinterpretq_u16_m128i(a), (imm)) + +// Copy a to dst, and insert the 16-bit integer i into dst at the location +// specified by imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_insert_epi16 +// FORCE_INLINE __m128i _mm_insert_epi16(__m128i a, int b, +// __constrange(0,8) int imm) +#define _mm_insert_epi16(a, b, imm) \ + vreinterpretq_m128i_s16( \ + vsetq_lane_s16((b), vreinterpretq_s16_m128i(a), (imm))) + +// Load 128-bits (composed of 2 packed double-precision (64-bit) floating-point +// elements) from memory into dst. mem_addr must be aligned on a 16-byte +// boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load_pd +FORCE_INLINE __m128d _mm_load_pd(const double *p) { - return _mm_cmplt_ps(a, b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vld1q_f64(p)); +#else + const float *fp = (const float *) p; + float ALIGN_STRUCT(16) data[4] = {fp[0], fp[1], fp[2], fp[3]}; + return vreinterpretq_m128d_f32(vld1q_f32(data)); +#endif } -// Compares for not greater than or equal. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/fk2y80s8(v=vs.100) -FORCE_INLINE __m128 _mm_cmpnge_ss(__m128 a, __m128 b) +// Load a double-precision (64-bit) floating-point element from memory into both +// elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load_pd1 +#define _mm_load_pd1 _mm_load1_pd + +// Load a double-precision (64-bit) floating-point element from memory into the +// lower of dst, and zero the upper element. mem_addr does not need to be +// aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load_sd +FORCE_INLINE __m128d _mm_load_sd(const double *p) { - return _mm_cmplt_ss(a, b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vsetq_lane_f64(*p, vdupq_n_f64(0), 0)); +#else + const float *fp = (const float *) p; + float ALIGN_STRUCT(16) data[4] = {fp[0], fp[1], 0, 0}; + return vreinterpretq_m128d_f32(vld1q_f32(data)); +#endif } -// Compares for not greater than. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/d0xh7w0s(v=vs.100) -FORCE_INLINE __m128 _mm_cmpngt_ps(__m128 a, __m128 b) +// Load 128-bits of integer data from memory into dst. mem_addr must be aligned +// on a 16-byte boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load_si128 +FORCE_INLINE __m128i _mm_load_si128(const __m128i *p) { - return _mm_cmple_ps(a, b); + return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p)); } -// Compares for not greater than. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/z7x9ydwh(v=vs.100) -FORCE_INLINE __m128 _mm_cmpngt_ss(__m128 a, __m128 b) +// Load a double-precision (64-bit) floating-point element from memory into both +// elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_load1_pd +FORCE_INLINE __m128d _mm_load1_pd(const double *p) { - return _mm_cmple_ss(a, b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vld1q_dup_f64(p)); +#else + return vreinterpretq_m128d_s64(vdupq_n_s64(*(const int64_t *) p)); +#endif } -// Compares for not less than or equal. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/6a330kxw(v=vs.100) -FORCE_INLINE __m128 _mm_cmpnle_ps(__m128 a, __m128 b) +// Load a double-precision (64-bit) floating-point element from memory into the +// upper element of dst, and copy the lower element from a to dst. mem_addr does +// not need to be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadh_pd +FORCE_INLINE __m128d _mm_loadh_pd(__m128d a, const double *p) { - return _mm_cmpgt_ps(a, b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vcombine_f64(vget_low_f64(vreinterpretq_f64_m128d(a)), vld1_f64(p))); +#else + return vreinterpretq_m128d_f32(vcombine_f32( + vget_low_f32(vreinterpretq_f32_m128d(a)), vld1_f32((const float *) p))); +#endif } -// Compares for not less than or equal. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/z7x9ydwh(v=vs.100) -FORCE_INLINE __m128 _mm_cmpnle_ss(__m128 a, __m128 b) +// Load 64-bit integer from memory into the first element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadl_epi64 +FORCE_INLINE __m128i _mm_loadl_epi64(__m128i const *p) { - return _mm_cmpgt_ss(a, b); + /* Load the lower 64 bits of the value pointed to by p into the + * lower 64 bits of the result, zeroing the upper 64 bits of the result. + */ + return vreinterpretq_m128i_s32( + vcombine_s32(vld1_s32((int32_t const *) p), vcreate_s32(0))); } -// Compares for not less than. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/4686bbdw(v=vs.100) -FORCE_INLINE __m128 _mm_cmpnlt_ps(__m128 a, __m128 b) +// Load a double-precision (64-bit) floating-point element from memory into the +// lower element of dst, and copy the upper element from a to dst. mem_addr does +// not need to be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadl_pd +FORCE_INLINE __m128d _mm_loadl_pd(__m128d a, const double *p) { - return _mm_cmpge_ps(a, b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vcombine_f64(vld1_f64(p), vget_high_f64(vreinterpretq_f64_m128d(a)))); +#else + return vreinterpretq_m128d_f32( + vcombine_f32(vld1_f32((const float *) p), + vget_high_f32(vreinterpretq_f32_m128d(a)))); +#endif } -// Compares for not less than. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/56b9z2wf(v=vs.100) -FORCE_INLINE __m128 _mm_cmpnlt_ss(__m128 a, __m128 b) +// Load 2 double-precision (64-bit) floating-point elements from memory into dst +// in reverse order. mem_addr must be aligned on a 16-byte boundary or a +// general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadr_pd +FORCE_INLINE __m128d _mm_loadr_pd(const double *p) { - return _mm_cmpge_ss(a, b); +#if defined(__aarch64__) || defined(_M_ARM64) + float64x2_t v = vld1q_f64(p); + return vreinterpretq_m128d_f64(vextq_f64(v, v, 1)); +#else + int64x2_t v = vld1q_s64((const int64_t *) p); + return vreinterpretq_m128d_s64(vextq_s64(v, v, 1)); +#endif } -// Compares the 16 signed or unsigned 8-bit integers in a and the 16 signed or -// unsigned 8-bit integers in b for equality. -// https://msdn.microsoft.com/en-us/library/windows/desktop/bz5xk21a(v=vs.90).aspx -FORCE_INLINE __m128i _mm_cmpeq_epi8(__m128i a, __m128i b) +// Loads two double-precision from unaligned memory, floating-point values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadu_pd +FORCE_INLINE __m128d _mm_loadu_pd(const double *p) { - return vreinterpretq_m128i_u8( - vceqq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); + return _mm_load_pd(p); } -// Compares the 8 signed or unsigned 16-bit integers in a and the 8 signed or -// unsigned 16-bit integers in b for equality. -// https://msdn.microsoft.com/en-us/library/2ay060te(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpeq_epi16(__m128i a, __m128i b) +// Load 128-bits of integer data from memory into dst. mem_addr does not need to +// be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadu_si128 +FORCE_INLINE __m128i _mm_loadu_si128(const __m128i *p) { - return vreinterpretq_m128i_u16( - vceqq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); + return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p)); } -// Compare packed 32-bit integers in a and b for equality, and store the results -// in dst -FORCE_INLINE __m128i _mm_cmpeq_epi32(__m128i a, __m128i b) +// Load unaligned 32-bit integer from memory into the first element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loadu_si32 +FORCE_INLINE __m128i _mm_loadu_si32(const void *p) { - return vreinterpretq_m128i_u32( - vceqq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); + return vreinterpretq_m128i_s32( + vsetq_lane_s32(*(const int32_t *) p, vdupq_n_s32(0), 0)); } -// Compare packed 64-bit integers in a and b for equality, and store the results -// in dst -FORCE_INLINE __m128i _mm_cmpeq_epi64(__m128i a, __m128i b) +// Multiply packed signed 16-bit integers in a and b, producing intermediate +// signed 32-bit integers. Horizontally add adjacent pairs of intermediate +// 32-bit integers, and pack the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_madd_epi16 +FORCE_INLINE __m128i _mm_madd_epi16(__m128i a, __m128i b) { -#if defined(__aarch64__) - return vreinterpretq_m128i_u64( - vceqq_u64(vreinterpretq_u64_m128i(a), vreinterpretq_u64_m128i(b))); + int32x4_t low = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)), + vget_low_s16(vreinterpretq_s16_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) + int32x4_t high = + vmull_high_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)); + + return vreinterpretq_m128i_s32(vpaddq_s32(low, high)); #else - // ARMv7 lacks vceqq_u64 - // (a == b) -> (a_lo == b_lo) && (a_hi == b_hi) - uint32x4_t cmp = - vceqq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b)); - uint32x4_t swapped = vrev64q_u32(cmp); - return vreinterpretq_m128i_u32(vandq_u32(cmp, swapped)); + int32x4_t high = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)), + vget_high_s16(vreinterpretq_s16_m128i(b))); + + int32x2_t low_sum = vpadd_s32(vget_low_s32(low), vget_high_s32(low)); + int32x2_t high_sum = vpadd_s32(vget_low_s32(high), vget_high_s32(high)); + + return vreinterpretq_m128i_s32(vcombine_s32(low_sum, high_sum)); #endif } -// Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers -// in b for lesser than. -// https://msdn.microsoft.com/en-us/library/windows/desktop/9s46csht(v=vs.90).aspx -FORCE_INLINE __m128i _mm_cmplt_epi8(__m128i a, __m128i b) +// Conditionally store 8-bit integer elements from a into memory using mask +// (elements are not stored when the highest bit is not set in the corresponding +// element) and a non-temporal memory hint. mem_addr does not need to be aligned +// on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maskmoveu_si128 +FORCE_INLINE void _mm_maskmoveu_si128(__m128i a, __m128i mask, char *mem_addr) { - return vreinterpretq_m128i_u8( - vcltq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); + int8x16_t shr_mask = vshrq_n_s8(vreinterpretq_s8_m128i(mask), 7); + __m128 b = _mm_load_ps((const float *) mem_addr); + int8x16_t masked = + vbslq_s8(vreinterpretq_u8_s8(shr_mask), vreinterpretq_s8_m128i(a), + vreinterpretq_s8_m128(b)); + vst1q_s8((int8_t *) mem_addr, masked); } -// Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers -// in b for greater than. -// -// r0 := (a0 > b0) ? 0xff : 0x0 -// r1 := (a1 > b1) ? 0xff : 0x0 -// ... -// r15 := (a15 > b15) ? 0xff : 0x0 -// -// https://msdn.microsoft.com/zh-tw/library/wf45zt2b(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpgt_epi8(__m128i a, __m128i b) +// Compare packed signed 16-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_epi16 +FORCE_INLINE __m128i _mm_max_epi16(__m128i a, __m128i b) { - return vreinterpretq_m128i_u8( - vcgtq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); + return vreinterpretq_m128i_s16( + vmaxq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } -// Compares the 8 signed 16-bit integers in a and the 8 signed 16-bit integers -// in b for less than. -// -// r0 := (a0 < b0) ? 0xffff : 0x0 -// r1 := (a1 < b1) ? 0xffff : 0x0 -// ... -// r7 := (a7 < b7) ? 0xffff : 0x0 -// -// https://technet.microsoft.com/en-us/library/t863edb2(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmplt_epi16(__m128i a, __m128i b) +// Compare packed unsigned 8-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_epu8 +FORCE_INLINE __m128i _mm_max_epu8(__m128i a, __m128i b) { - return vreinterpretq_m128i_u16( - vcltq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); + return vreinterpretq_m128i_u8( + vmaxq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } -// Compares the 8 signed 16-bit integers in a and the 8 signed 16-bit integers -// in b for greater than. -// -// r0 := (a0 > b0) ? 0xffff : 0x0 -// r1 := (a1 > b1) ? 0xffff : 0x0 -// ... -// r7 := (a7 > b7) ? 0xffff : 0x0 -// -// https://technet.microsoft.com/en-us/library/xd43yfsa(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpgt_epi16(__m128i a, __m128i b) +// Compare packed double-precision (64-bit) floating-point elements in a and b, +// and store packed maximum values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_pd +FORCE_INLINE __m128d _mm_max_pd(__m128d a, __m128d b) { - return vreinterpretq_m128i_u16( - vcgtq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) +#if SSE2NEON_PRECISE_MINMAX + float64x2_t _a = vreinterpretq_f64_m128d(a); + float64x2_t _b = vreinterpretq_f64_m128d(b); + return vreinterpretq_m128d_f64(vbslq_f64(vcgtq_f64(_a, _b), _a, _b)); +#else + return vreinterpretq_m128d_f64( + vmaxq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#endif +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) > (*(double *) &b0) ? a0 : b0; + d[1] = (*(double *) &a1) > (*(double *) &b1) ? a1 : b1; + + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b, store the maximum value in the lower element of dst, and copy the upper +// element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_sd +FORCE_INLINE __m128d _mm_max_sd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_max_pd(a, b)); +#else + double *da = (double *) &a; + double *db = (double *) &b; + double c[2] = {da[0] > db[0] ? da[0] : db[0], da[1]}; + return vreinterpretq_m128d_f32(vld1q_f32((float32_t *) c)); +#endif +} -// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers -// in b for less than. -// https://msdn.microsoft.com/en-us/library/vstudio/4ak0bf5d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmplt_epi32(__m128i a, __m128i b) +// Compare packed signed 16-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_epi16 +FORCE_INLINE __m128i _mm_min_epi16(__m128i a, __m128i b) { - return vreinterpretq_m128i_u32( - vcltq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); + return vreinterpretq_m128i_s16( + vminq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); } -// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers -// in b for greater than. -// https://msdn.microsoft.com/en-us/library/vstudio/1s9f2z0y(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpgt_epi32(__m128i a, __m128i b) +// Compare packed unsigned 8-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_epu8 +FORCE_INLINE __m128i _mm_min_epu8(__m128i a, __m128i b) { - return vreinterpretq_m128i_u32( - vcgtq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); + return vreinterpretq_m128i_u8( + vminq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); } -// Compares the 2 signed 64-bit integers in a and the 2 signed 64-bit integers -// in b for greater than. -FORCE_INLINE __m128i _mm_cmpgt_epi64(__m128i a, __m128i b) +// Compare packed double-precision (64-bit) floating-point elements in a and b, +// and store packed minimum values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_pd +FORCE_INLINE __m128d _mm_min_pd(__m128d a, __m128d b) { -#if defined(__aarch64__) - return vreinterpretq_m128i_u64( - vcgtq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); +#if defined(__aarch64__) || defined(_M_ARM64) +#if SSE2NEON_PRECISE_MINMAX + float64x2_t _a = vreinterpretq_f64_m128d(a); + float64x2_t _b = vreinterpretq_f64_m128d(b); + return vreinterpretq_m128d_f64(vbslq_f64(vcltq_f64(_a, _b), _a, _b)); #else - // ARMv7 lacks vcgtq_s64. - // This is based off of Clang's SSE2 polyfill: - // (a > b) -> ((a_hi > b_hi) || (a_lo > b_lo && a_hi == b_hi)) - - // Mask the sign bit out since we need a signed AND an unsigned comparison - // and it is ugly to try and split them. - int32x4_t mask = vreinterpretq_s32_s64(vdupq_n_s64(0x80000000ull)); - int32x4_t a_mask = veorq_s32(vreinterpretq_s32_m128i(a), mask); - int32x4_t b_mask = veorq_s32(vreinterpretq_s32_m128i(b), mask); - // Check if a > b - int64x2_t greater = vreinterpretq_s64_u32(vcgtq_s32(a_mask, b_mask)); - // Copy upper mask to lower mask - // a_hi > b_hi - int64x2_t gt_hi = vshrq_n_s64(greater, 63); - // Copy lower mask to upper mask - // a_lo > b_lo - int64x2_t gt_lo = vsliq_n_s64(greater, greater, 32); - // Compare for equality - int64x2_t equal = vreinterpretq_s64_u32(vceqq_s32(a_mask, b_mask)); - // Copy upper mask to lower mask - // a_hi == b_hi - int64x2_t eq_hi = vshrq_n_s64(equal, 63); - // a_hi > b_hi || (a_lo > b_lo && a_hi == b_hi) - int64x2_t ret = vorrq_s64(gt_hi, vandq_s64(gt_lo, eq_hi)); - return vreinterpretq_m128i_s64(ret); -#endif -} - -// Compares the four 32-bit floats in a and b to check if any values are NaN. -// Ordered compare between each value returns true for "orderable" and false for -// "not orderable" (NaN). -// https://msdn.microsoft.com/en-us/library/vstudio/0h9w00fx(v=vs.100).aspx see -// also: -// http://stackoverflow.com/questions/8627331/what-does-ordered-unordered-comparison-mean -// http://stackoverflow.com/questions/29349621/neon-isnanval-intrinsics -FORCE_INLINE __m128 _mm_cmpord_ps(__m128 a, __m128 b) -{ - // Note: NEON does not have ordered compare builtin - // Need to compare a eq a and b eq b to check for NaN - // Do AND of results to get final - uint32x4_t ceqaa = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t ceqbb = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_u32(vandq_u32(ceqaa, ceqbb)); + return vreinterpretq_m128d_f64( + vminq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#endif +#else + uint64_t a0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(a)); + uint64_t a1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(a)); + uint64_t b0 = (uint64_t) vget_low_u64(vreinterpretq_u64_m128d(b)); + uint64_t b1 = (uint64_t) vget_high_u64(vreinterpretq_u64_m128d(b)); + uint64_t d[2]; + d[0] = (*(double *) &a0) < (*(double *) &b0) ? a0 : b0; + d[1] = (*(double *) &a1) < (*(double *) &b1) ? a1 : b1; + return vreinterpretq_m128d_u64(vld1q_u64(d)); +#endif } -// Compares for ordered. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/343t62da(v=vs.100) -FORCE_INLINE __m128 _mm_cmpord_ss(__m128 a, __m128 b) +// Compare the lower double-precision (64-bit) floating-point elements in a and +// b, store the minimum value in the lower element of dst, and copy the upper +// element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_sd +FORCE_INLINE __m128d _mm_min_sd(__m128d a, __m128d b) { - return _mm_move_ss(a, _mm_cmpord_ps(a, b)); +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_min_pd(a, b)); +#else + double *da = (double *) &a; + double *db = (double *) &b; + double c[2] = {da[0] < db[0] ? da[0] : db[0], da[1]}; + return vreinterpretq_m128d_f32(vld1q_f32((float32_t *) c)); +#endif } -// Compares for unordered. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/khy6fk1t(v=vs.100) -FORCE_INLINE __m128 _mm_cmpunord_ps(__m128 a, __m128 b) +// Copy the lower 64-bit integer in a to the lower element of dst, and zero the +// upper element. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_move_epi64 +FORCE_INLINE __m128i _mm_move_epi64(__m128i a) { - uint32x4_t f32a = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t f32b = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_u32(vmvnq_u32(vandq_u32(f32a, f32b))); + return vreinterpretq_m128i_s64( + vsetq_lane_s64(0, vreinterpretq_s64_m128i(a), 1)); } -// Compares for unordered. -// https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/2as2387b(v=vs.100) -FORCE_INLINE __m128 _mm_cmpunord_ss(__m128 a, __m128 b) +// Move the lower double-precision (64-bit) floating-point element from b to the +// lower element of dst, and copy the upper element from a to the upper element +// of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_move_sd +FORCE_INLINE __m128d _mm_move_sd(__m128d a, __m128d b) { - return _mm_move_ss(a, _mm_cmpunord_ps(a, b)); + return vreinterpretq_m128d_f32( + vcombine_f32(vget_low_f32(vreinterpretq_f32_m128d(b)), + vget_high_f32(vreinterpretq_f32_m128d(a)))); } -// Compares the lower single-precision floating point scalar values of a and b -// using a less than operation. : -// https://msdn.microsoft.com/en-us/library/2kwe606b(v=vs.90).aspx Important -// note!! The documentation on MSDN is incorrect! If either of the values is a -// NAN the docs say you will get a one, but in fact, it will return a zero!! -FORCE_INLINE int _mm_comilt_ss(__m128 a, __m128 b) +// Create mask from the most significant bit of each 8-bit element in a, and +// store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movemask_epi8 +FORCE_INLINE int _mm_movemask_epi8(__m128i a) { - uint32x4_t a_not_nan = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_lt_b = - vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_lt_b), 0) != 0) ? 1 : 0; + // Use increasingly wide shifts+adds to collect the sign bits + // together. + // Since the widening shifts would be rather confusing to follow in little + // endian, everything will be illustrated in big endian order instead. This + // has a different result - the bits would actually be reversed on a big + // endian machine. + + // Starting input (only half the elements are shown): + // 89 ff 1d c0 00 10 99 33 + uint8x16_t input = vreinterpretq_u8_m128i(a); + + // Shift out everything but the sign bits with an unsigned shift right. + // + // Bytes of the vector:: + // 89 ff 1d c0 00 10 99 33 + // \ \ \ \ \ \ \ \ high_bits = (uint16x4_t)(input >> 7) + // | | | | | | | | + // 01 01 00 01 00 00 01 00 + // + // Bits of first important lane(s): + // 10001001 (89) + // \______ + // | + // 00000001 (01) + uint16x8_t high_bits = vreinterpretq_u16_u8(vshrq_n_u8(input, 7)); + + // Merge the even lanes together with a 16-bit unsigned shift right + add. + // 'xx' represents garbage data which will be ignored in the final result. + // In the important bytes, the add functions like a binary OR. + // + // 01 01 00 01 00 00 01 00 + // \_ | \_ | \_ | \_ | paired16 = (uint32x4_t)(input + (input >> 7)) + // \| \| \| \| + // xx 03 xx 01 xx 00 xx 02 + // + // 00000001 00000001 (01 01) + // \_______ | + // \| + // xxxxxxxx xxxxxx11 (xx 03) + uint32x4_t paired16 = + vreinterpretq_u32_u16(vsraq_n_u16(high_bits, high_bits, 7)); + + // Repeat with a wider 32-bit shift + add. + // xx 03 xx 01 xx 00 xx 02 + // \____ | \____ | paired32 = (uint64x1_t)(paired16 + (paired16 >> + // 14)) + // \| \| + // xx xx xx 0d xx xx xx 02 + // + // 00000011 00000001 (03 01) + // \\_____ || + // '----.\|| + // xxxxxxxx xxxx1101 (xx 0d) + uint64x2_t paired32 = + vreinterpretq_u64_u32(vsraq_n_u32(paired16, paired16, 14)); + + // Last, an even wider 64-bit shift + add to get our result in the low 8 bit + // lanes. xx xx xx 0d xx xx xx 02 + // \_________ | paired64 = (uint8x8_t)(paired32 + (paired32 >> + // 28)) + // \| + // xx xx xx xx xx xx xx d2 + // + // 00001101 00000010 (0d 02) + // \ \___ | | + // '---. \| | + // xxxxxxxx 11010010 (xx d2) + uint8x16_t paired64 = + vreinterpretq_u8_u64(vsraq_n_u64(paired32, paired32, 28)); + + // Extract the low 8 bits from each 64-bit lane with 2 8-bit extracts. + // xx xx xx xx xx xx xx d2 + // || return paired64[0] + // d2 + // Note: Little endian would return the correct value 4b (01001011) instead. + return vgetq_lane_u8(paired64, 0) | ((int) vgetq_lane_u8(paired64, 8) << 8); } -// Compares the lower single-precision floating point scalar values of a and b -// using a greater than operation. : -// https://msdn.microsoft.com/en-us/library/b0738e0t(v=vs.100).aspx -FORCE_INLINE int _mm_comigt_ss(__m128 a, __m128 b) +// Set each bit of mask dst based on the most significant bit of the +// corresponding packed double-precision (64-bit) floating-point element in a. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movemask_pd +FORCE_INLINE int _mm_movemask_pd(__m128d a) { - // return vgetq_lane_u32(vcgtq_f32(vreinterpretq_f32_m128(a), - // vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_gt_b = - vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0) ? 1 : 0; + uint64x2_t input = vreinterpretq_u64_m128d(a); + uint64x2_t high_bits = vshrq_n_u64(input, 63); + return (int) (vgetq_lane_u64(high_bits, 0) | + (vgetq_lane_u64(high_bits, 1) << 1)); } -// Compares the lower single-precision floating point scalar values of a and b -// using a less than or equal operation. : -// https://msdn.microsoft.com/en-us/library/1w4t7c57(v=vs.90).aspx -FORCE_INLINE int _mm_comile_ss(__m128 a, __m128 b) +// Copy the lower 64-bit integer in a to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movepi64_pi64 +FORCE_INLINE __m64 _mm_movepi64_pi64(__m128i a) { - // return vgetq_lane_u32(vcleq_f32(vreinterpretq_f32_m128(a), - // vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_le_b = - vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_le_b), 0) != 0) ? 1 : 0; + return vreinterpret_m64_s64(vget_low_s64(vreinterpretq_s64_m128i(a))); } -// Compares the lower single-precision floating point scalar values of a and b -// using a greater than or equal operation. : -// https://msdn.microsoft.com/en-us/library/8t80des6(v=vs.100).aspx -FORCE_INLINE int _mm_comige_ss(__m128 a, __m128 b) +// Copy the 64-bit integer a to the lower element of dst, and zero the upper +// element. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movpi64_epi64 +FORCE_INLINE __m128i _mm_movpi64_epi64(__m64 a) { - // return vgetq_lane_u32(vcgeq_f32(vreinterpretq_f32_m128(a), - // vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_ge_b = - vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0) ? 1 : 0; + return vreinterpretq_m128i_s64( + vcombine_s64(vreinterpret_s64_m64(a), vdup_n_s64(0))); } -// Compares the lower single-precision floating point scalar values of a and b -// using an equality operation. : -// https://msdn.microsoft.com/en-us/library/93yx2h2b(v=vs.100).aspx -FORCE_INLINE int _mm_comieq_ss(__m128 a, __m128 b) +// Multiply the low unsigned 32-bit integers from each packed 64-bit element in +// a and b, and store the unsigned 64-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mul_epu32 +FORCE_INLINE __m128i _mm_mul_epu32(__m128i a, __m128i b) { - // return vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), - // vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_eq_b = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_eq_b), 0) != 0) ? 1 : 0; + // vmull_u32 upcasts instead of masking, so we downcast. + uint32x2_t a_lo = vmovn_u64(vreinterpretq_u64_m128i(a)); + uint32x2_t b_lo = vmovn_u64(vreinterpretq_u64_m128i(b)); + return vreinterpretq_m128i_u64(vmull_u32(a_lo, b_lo)); } -// Compares the lower single-precision floating point scalar values of a and b -// using an inequality operation. : -// https://msdn.microsoft.com/en-us/library/bafh5e0a(v=vs.90).aspx -FORCE_INLINE int _mm_comineq_ss(__m128 a, __m128 b) +// Multiply packed double-precision (64-bit) floating-point elements in a and b, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mul_pd +FORCE_INLINE __m128d _mm_mul_pd(__m128d a, __m128d b) { - // return !vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), - // vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = - vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); - uint32x4_t a_neq_b = vmvnq_u32( - vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); - return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_neq_b), 0) != 0) ? 1 : 0; +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vmulq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + double *da = (double *) &a; + double *db = (double *) &b; + double c[2]; + c[0] = da[0] * db[0]; + c[1] = da[1] * db[1]; + return vld1q_f32((float32_t *) c); +#endif } -// according to the documentation, these intrinsics behave the same as the -// non-'u' versions. We'll just alias them here. -#define _mm_ucomilt_ss _mm_comilt_ss -#define _mm_ucomile_ss _mm_comile_ss -#define _mm_ucomigt_ss _mm_comigt_ss -#define _mm_ucomige_ss _mm_comige_ss -#define _mm_ucomieq_ss _mm_comieq_ss -#define _mm_ucomineq_ss _mm_comineq_ss +// Multiply the lower double-precision (64-bit) floating-point element in a and +// b, store the result in the lower element of dst, and copy the upper element +// from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=mm_mul_sd +FORCE_INLINE __m128d _mm_mul_sd(__m128d a, __m128d b) +{ + return _mm_move_sd(a, _mm_mul_pd(a, b)); +} -/* Conversions */ +// Multiply the low unsigned 32-bit integers from a and b, and store the +// unsigned 64-bit result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mul_su32 +FORCE_INLINE __m64 _mm_mul_su32(__m64 a, __m64 b) +{ + return vreinterpret_m64_u64(vget_low_u64( + vmull_u32(vreinterpret_u32_m64(a), vreinterpret_u32_m64(b)))); +} -// Convert packed signed 32-bit integers in b to packed single-precision -// (32-bit) floating-point elements, store the results in the lower 2 elements -// of dst, and copy the upper 2 packed elements from a to the upper elements of +// Multiply the packed signed 16-bit integers in a and b, producing intermediate +// 32-bit integers, and store the high 16 bits of the intermediate integers in // dst. -// -// dst[31:0] := Convert_Int32_To_FP32(b[31:0]) -// dst[63:32] := Convert_Int32_To_FP32(b[63:32]) -// dst[95:64] := a[95:64] -// dst[127:96] := a[127:96] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvt_pi2ps -FORCE_INLINE __m128 _mm_cvt_pi2ps(__m128 a, __m64 b) +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mulhi_epi16 +FORCE_INLINE __m128i _mm_mulhi_epi16(__m128i a, __m128i b) { - return vreinterpretq_m128_f32( - vcombine_f32(vcvt_f32_s32(vreinterpret_s32_m64(b)), - vget_high_f32(vreinterpretq_f32_m128(a)))); + /* FIXME: issue with large values because of result saturation */ + // int16x8_t ret = vqdmulhq_s16(vreinterpretq_s16_m128i(a), + // vreinterpretq_s16_m128i(b)); /* =2*a*b */ return + // vreinterpretq_m128i_s16(vshrq_n_s16(ret, 1)); + int16x4_t a3210 = vget_low_s16(vreinterpretq_s16_m128i(a)); + int16x4_t b3210 = vget_low_s16(vreinterpretq_s16_m128i(b)); + int32x4_t ab3210 = vmull_s16(a3210, b3210); /* 3333222211110000 */ + int16x4_t a7654 = vget_high_s16(vreinterpretq_s16_m128i(a)); + int16x4_t b7654 = vget_high_s16(vreinterpretq_s16_m128i(b)); + int32x4_t ab7654 = vmull_s16(a7654, b7654); /* 7777666655554444 */ + uint16x8x2_t r = + vuzpq_u16(vreinterpretq_u16_s32(ab3210), vreinterpretq_u16_s32(ab7654)); + return vreinterpretq_m128i_u16(r.val[1]); } -// Convert the signed 32-bit integer b to a single-precision (32-bit) -// floating-point element, store the result in the lower element of dst, and -// copy the upper 3 packed elements from a to the upper elements of dst. -// -// dst[31:0] := Convert_Int32_To_FP32(b[31:0]) -// dst[127:32] := a[127:32] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvt_si2ss -FORCE_INLINE __m128 _mm_cvt_si2ss(__m128 a, int b) +// Multiply the packed unsigned 16-bit integers in a and b, producing +// intermediate 32-bit integers, and store the high 16 bits of the intermediate +// integers in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mulhi_epu16 +FORCE_INLINE __m128i _mm_mulhi_epu16(__m128i a, __m128i b) { - return vreinterpretq_m128_f32( - vsetq_lane_f32((float) b, vreinterpretq_f32_m128(a), 0)); + uint16x4_t a3210 = vget_low_u16(vreinterpretq_u16_m128i(a)); + uint16x4_t b3210 = vget_low_u16(vreinterpretq_u16_m128i(b)); + uint32x4_t ab3210 = vmull_u16(a3210, b3210); +#if defined(__aarch64__) || defined(_M_ARM64) + uint32x4_t ab7654 = + vmull_high_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b)); + uint16x8_t r = vuzp2q_u16(vreinterpretq_u16_u32(ab3210), + vreinterpretq_u16_u32(ab7654)); + return vreinterpretq_m128i_u16(r); +#else + uint16x4_t a7654 = vget_high_u16(vreinterpretq_u16_m128i(a)); + uint16x4_t b7654 = vget_high_u16(vreinterpretq_u16_m128i(b)); + uint32x4_t ab7654 = vmull_u16(a7654, b7654); + uint16x8x2_t r = + vuzpq_u16(vreinterpretq_u16_u32(ab3210), vreinterpretq_u16_u32(ab7654)); + return vreinterpretq_m128i_u16(r.val[1]); +#endif } -// Convert the signed 32-bit integer b to a single-precision (32-bit) -// floating-point element, store the result in the lower element of dst, and -// copy the upper 3 packed elements from a to the upper elements of dst. -// -// dst[31:0] := Convert_Int32_To_FP32(b[31:0]) -// dst[127:32] := a[127:32] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtsi32_ss -#define _mm_cvtsi32_ss(a, b) _mm_cvt_si2ss(a, b) +// Multiply the packed 16-bit integers in a and b, producing intermediate 32-bit +// integers, and store the low 16 bits of the intermediate integers in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mullo_epi16 +FORCE_INLINE __m128i _mm_mullo_epi16(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s16( + vmulq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +} -// Convert the signed 64-bit integer b to a single-precision (32-bit) -// floating-point element, store the result in the lower element of dst, and -// copy the upper 3 packed elements from a to the upper elements of dst. -// -// dst[31:0] := Convert_Int64_To_FP32(b[63:0]) -// dst[127:32] := a[127:32] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtsi64_ss -FORCE_INLINE __m128 _mm_cvtsi64_ss(__m128 a, int64_t b) +// Compute the bitwise OR of packed double-precision (64-bit) floating-point +// elements in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=mm_or_pd +FORCE_INLINE __m128d _mm_or_pd(__m128d a, __m128d b) { - return vreinterpretq_m128_f32( - vsetq_lane_f32((float) b, vreinterpretq_f32_m128(a), 0)); + return vreinterpretq_m128d_s64( + vorrq_s64(vreinterpretq_s64_m128d(a), vreinterpretq_s64_m128d(b))); } -// Convert the lower single-precision (32-bit) floating-point element in a to a -// 32-bit integer, and store the result in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvt_ss2si -FORCE_INLINE int _mm_cvt_ss2si(__m128 a) -{ -#if defined(__aarch64__) - return vgetq_lane_s32(vcvtnq_s32_f32(vreinterpretq_f32_m128(a)), 0); -#else - float32_t data = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); - float32_t diff = data - floor(data); - if (diff > 0.5) - return (int32_t) ceil(data); - if (diff == 0.5) { - int32_t f = (int32_t) floor(data); - int32_t c = (int32_t) ceil(data); - return c & 1 ? f : c; - } - return (int32_t) floor(data); -#endif +// Compute the bitwise OR of 128 bits (representing integer data) in a and b, +// and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_or_si128 +FORCE_INLINE __m128i _mm_or_si128(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s32( + vorrq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +} + +// Convert packed signed 16-bit integers from a and b to packed 8-bit integers +// using signed saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packs_epi16 +FORCE_INLINE __m128i _mm_packs_epi16(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s8( + vcombine_s8(vqmovn_s16(vreinterpretq_s16_m128i(a)), + vqmovn_s16(vreinterpretq_s16_m128i(b)))); +} + +// Convert packed signed 32-bit integers from a and b to packed 16-bit integers +// using signed saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packs_epi32 +FORCE_INLINE __m128i _mm_packs_epi32(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s16( + vcombine_s16(vqmovn_s32(vreinterpretq_s32_m128i(a)), + vqmovn_s32(vreinterpretq_s32_m128i(b)))); +} + +// Convert packed signed 16-bit integers from a and b to packed 8-bit integers +// using unsigned saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packus_epi16 +FORCE_INLINE __m128i _mm_packus_epi16(const __m128i a, const __m128i b) +{ + return vreinterpretq_m128i_u8( + vcombine_u8(vqmovun_s16(vreinterpretq_s16_m128i(a)), + vqmovun_s16(vreinterpretq_s16_m128i(b)))); +} + +// Pause the processor. This is typically used in spin-wait loops and depending +// on the x86 processor typical values are in the 40-100 cycle range. The +// 'yield' instruction isn't a good fit because it's effectively a nop on most +// Arm cores. Experience with several databases has shown has shown an 'isb' is +// a reasonable approximation. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_pause +FORCE_INLINE void _mm_pause(void) +{ +#if defined(_MSC_VER) + __isb(_ARM64_BARRIER_SY); +#else + __asm__ __volatile__("isb\n"); +#endif +} + +// Compute the absolute differences of packed unsigned 8-bit integers in a and +// b, then horizontally sum each consecutive 8 differences to produce two +// unsigned 16-bit integers, and pack these unsigned 16-bit integers in the low +// 16 bits of 64-bit elements in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sad_epu8 +FORCE_INLINE __m128i _mm_sad_epu8(__m128i a, __m128i b) +{ + uint16x8_t t = vpaddlq_u8(vabdq_u8((uint8x16_t) a, (uint8x16_t) b)); + return vreinterpretq_m128i_u64(vpaddlq_u32(vpaddlq_u16(t))); +} + +// Set packed 16-bit integers in dst with the supplied values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_epi16 +FORCE_INLINE __m128i _mm_set_epi16(short i7, + short i6, + short i5, + short i4, + short i3, + short i2, + short i1, + short i0) +{ + int16_t ALIGN_STRUCT(16) data[8] = {i0, i1, i2, i3, i4, i5, i6, i7}; + return vreinterpretq_m128i_s16(vld1q_s16(data)); +} + +// Set packed 32-bit integers in dst with the supplied values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_epi32 +FORCE_INLINE __m128i _mm_set_epi32(int i3, int i2, int i1, int i0) +{ + int32_t ALIGN_STRUCT(16) data[4] = {i0, i1, i2, i3}; + return vreinterpretq_m128i_s32(vld1q_s32(data)); +} + +// Set packed 64-bit integers in dst with the supplied values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_epi64 +FORCE_INLINE __m128i _mm_set_epi64(__m64 i1, __m64 i2) +{ + return _mm_set_epi64x(vget_lane_s64(i1, 0), vget_lane_s64(i2, 0)); +} + +// Set packed 64-bit integers in dst with the supplied values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_epi64x +FORCE_INLINE __m128i _mm_set_epi64x(int64_t i1, int64_t i2) +{ + return vreinterpretq_m128i_s64( + vcombine_s64(vcreate_s64(i2), vcreate_s64(i1))); +} + +// Set packed 8-bit integers in dst with the supplied values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_epi8 +FORCE_INLINE __m128i _mm_set_epi8(signed char b15, + signed char b14, + signed char b13, + signed char b12, + signed char b11, + signed char b10, + signed char b9, + signed char b8, + signed char b7, + signed char b6, + signed char b5, + signed char b4, + signed char b3, + signed char b2, + signed char b1, + signed char b0) +{ + int8_t ALIGN_STRUCT(16) + data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3, + (int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7, + (int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11, + (int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15}; + return (__m128i) vld1q_s8(data); +} + +// Set packed double-precision (64-bit) floating-point elements in dst with the +// supplied values. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_pd +FORCE_INLINE __m128d _mm_set_pd(double e1, double e0) +{ + double ALIGN_STRUCT(16) data[2] = {e0, e1}; +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vld1q_f64((float64_t *) data)); +#else + return vreinterpretq_m128d_f32(vld1q_f32((float32_t *) data)); +#endif +} + +// Broadcast double-precision (64-bit) floating-point value a to all elements of +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_pd1 +#define _mm_set_pd1 _mm_set1_pd + +// Copy double-precision (64-bit) floating-point element a to the lower element +// of dst, and zero the upper element. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set_sd +FORCE_INLINE __m128d _mm_set_sd(double a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vsetq_lane_f64(a, vdupq_n_f64(0), 0)); +#else + return _mm_set_pd(0, a); +#endif +} + +// Broadcast 16-bit integer a to all elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set1_epi16 +FORCE_INLINE __m128i _mm_set1_epi16(short w) +{ + return vreinterpretq_m128i_s16(vdupq_n_s16(w)); +} + +// Broadcast 32-bit integer a to all elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set1_epi32 +FORCE_INLINE __m128i _mm_set1_epi32(int _i) +{ + return vreinterpretq_m128i_s32(vdupq_n_s32(_i)); +} + +// Broadcast 64-bit integer a to all elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set1_epi64 +FORCE_INLINE __m128i _mm_set1_epi64(__m64 _i) +{ + return vreinterpretq_m128i_s64(vdupq_lane_s64(_i, 0)); +} + +// Broadcast 64-bit integer a to all elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set1_epi64x +FORCE_INLINE __m128i _mm_set1_epi64x(int64_t _i) +{ + return vreinterpretq_m128i_s64(vdupq_n_s64(_i)); +} + +// Broadcast 8-bit integer a to all elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set1_epi8 +FORCE_INLINE __m128i _mm_set1_epi8(signed char w) +{ + return vreinterpretq_m128i_s8(vdupq_n_s8(w)); +} + +// Broadcast double-precision (64-bit) floating-point value a to all elements of +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_set1_pd +FORCE_INLINE __m128d _mm_set1_pd(double d) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vdupq_n_f64(d)); +#else + return vreinterpretq_m128d_s64(vdupq_n_s64(*(int64_t *) &d)); +#endif +} + +// Set packed 16-bit integers in dst with the supplied values in reverse order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setr_epi16 +FORCE_INLINE __m128i _mm_setr_epi16(short w0, + short w1, + short w2, + short w3, + short w4, + short w5, + short w6, + short w7) +{ + int16_t ALIGN_STRUCT(16) data[8] = {w0, w1, w2, w3, w4, w5, w6, w7}; + return vreinterpretq_m128i_s16(vld1q_s16((int16_t *) data)); +} + +// Set packed 32-bit integers in dst with the supplied values in reverse order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setr_epi32 +FORCE_INLINE __m128i _mm_setr_epi32(int i3, int i2, int i1, int i0) +{ + int32_t ALIGN_STRUCT(16) data[4] = {i3, i2, i1, i0}; + return vreinterpretq_m128i_s32(vld1q_s32(data)); +} + +// Set packed 64-bit integers in dst with the supplied values in reverse order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setr_epi64 +FORCE_INLINE __m128i _mm_setr_epi64(__m64 e1, __m64 e0) +{ + return vreinterpretq_m128i_s64(vcombine_s64(e1, e0)); +} + +// Set packed 8-bit integers in dst with the supplied values in reverse order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setr_epi8 +FORCE_INLINE __m128i _mm_setr_epi8(signed char b0, + signed char b1, + signed char b2, + signed char b3, + signed char b4, + signed char b5, + signed char b6, + signed char b7, + signed char b8, + signed char b9, + signed char b10, + signed char b11, + signed char b12, + signed char b13, + signed char b14, + signed char b15) +{ + int8_t ALIGN_STRUCT(16) + data[16] = {(int8_t) b0, (int8_t) b1, (int8_t) b2, (int8_t) b3, + (int8_t) b4, (int8_t) b5, (int8_t) b6, (int8_t) b7, + (int8_t) b8, (int8_t) b9, (int8_t) b10, (int8_t) b11, + (int8_t) b12, (int8_t) b13, (int8_t) b14, (int8_t) b15}; + return (__m128i) vld1q_s8(data); +} + +// Set packed double-precision (64-bit) floating-point elements in dst with the +// supplied values in reverse order. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setr_pd +FORCE_INLINE __m128d _mm_setr_pd(double e1, double e0) +{ + return _mm_set_pd(e0, e1); +} + +// Return vector of type __m128d with all elements set to zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setzero_pd +FORCE_INLINE __m128d _mm_setzero_pd(void) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vdupq_n_f64(0)); +#else + return vreinterpretq_m128d_f32(vdupq_n_f32(0)); +#endif +} + +// Return vector of type __m128i with all elements set to zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_setzero_si128 +FORCE_INLINE __m128i _mm_setzero_si128(void) +{ + return vreinterpretq_m128i_s32(vdupq_n_s32(0)); +} + +// Shuffle 32-bit integers in a using the control in imm8, and store the results +// in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_epi32 +// FORCE_INLINE __m128i _mm_shuffle_epi32(__m128i a, +// __constrange(0,255) int imm) +#if defined(_sse2neon_shuffle) +#define _mm_shuffle_epi32(a, imm) \ + __extension__({ \ + int32x4_t _input = vreinterpretq_s32_m128i(a); \ + int32x4_t _shuf = \ + vshuffleq_s32(_input, _input, (imm) & (0x3), ((imm) >> 2) & 0x3, \ + ((imm) >> 4) & 0x3, ((imm) >> 6) & 0x3); \ + vreinterpretq_m128i_s32(_shuf); \ + }) +#else // generic +#define _mm_shuffle_epi32(a, imm) \ + _sse2neon_define1( \ + __m128i, a, __m128i ret; switch (imm) { \ + case _MM_SHUFFLE(1, 0, 3, 2): \ + ret = _mm_shuffle_epi_1032(_a); \ + break; \ + case _MM_SHUFFLE(2, 3, 0, 1): \ + ret = _mm_shuffle_epi_2301(_a); \ + break; \ + case _MM_SHUFFLE(0, 3, 2, 1): \ + ret = _mm_shuffle_epi_0321(_a); \ + break; \ + case _MM_SHUFFLE(2, 1, 0, 3): \ + ret = _mm_shuffle_epi_2103(_a); \ + break; \ + case _MM_SHUFFLE(1, 0, 1, 0): \ + ret = _mm_shuffle_epi_1010(_a); \ + break; \ + case _MM_SHUFFLE(1, 0, 0, 1): \ + ret = _mm_shuffle_epi_1001(_a); \ + break; \ + case _MM_SHUFFLE(0, 1, 0, 1): \ + ret = _mm_shuffle_epi_0101(_a); \ + break; \ + case _MM_SHUFFLE(2, 2, 1, 1): \ + ret = _mm_shuffle_epi_2211(_a); \ + break; \ + case _MM_SHUFFLE(0, 1, 2, 2): \ + ret = _mm_shuffle_epi_0122(_a); \ + break; \ + case _MM_SHUFFLE(3, 3, 3, 2): \ + ret = _mm_shuffle_epi_3332(_a); \ + break; \ + case _MM_SHUFFLE(0, 0, 0, 0): \ + ret = _mm_shuffle_epi32_splat(_a, 0); \ + break; \ + case _MM_SHUFFLE(1, 1, 1, 1): \ + ret = _mm_shuffle_epi32_splat(_a, 1); \ + break; \ + case _MM_SHUFFLE(2, 2, 2, 2): \ + ret = _mm_shuffle_epi32_splat(_a, 2); \ + break; \ + case _MM_SHUFFLE(3, 3, 3, 3): \ + ret = _mm_shuffle_epi32_splat(_a, 3); \ + break; \ + default: \ + ret = _mm_shuffle_epi32_default(_a, (imm)); \ + break; \ + } _sse2neon_return(ret);) +#endif + +// Shuffle double-precision (64-bit) floating-point elements using the control +// in imm8, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_pd +#ifdef _sse2neon_shuffle +#define _mm_shuffle_pd(a, b, imm8) \ + vreinterpretq_m128d_s64( \ + vshuffleq_s64(vreinterpretq_s64_m128d(a), vreinterpretq_s64_m128d(b), \ + imm8 & 0x1, ((imm8 & 0x2) >> 1) + 2)) +#else +#define _mm_shuffle_pd(a, b, imm8) \ + _mm_castsi128_pd(_mm_set_epi64x( \ + vgetq_lane_s64(vreinterpretq_s64_m128d(b), (imm8 & 0x2) >> 1), \ + vgetq_lane_s64(vreinterpretq_s64_m128d(a), imm8 & 0x1))) +#endif + +// FORCE_INLINE __m128i _mm_shufflehi_epi16(__m128i a, +// __constrange(0,255) int imm) +#if defined(_sse2neon_shuffle) +#define _mm_shufflehi_epi16(a, imm) \ + __extension__({ \ + int16x8_t _input = vreinterpretq_s16_m128i(a); \ + int16x8_t _shuf = \ + vshuffleq_s16(_input, _input, 0, 1, 2, 3, ((imm) & (0x3)) + 4, \ + (((imm) >> 2) & 0x3) + 4, (((imm) >> 4) & 0x3) + 4, \ + (((imm) >> 6) & 0x3) + 4); \ + vreinterpretq_m128i_s16(_shuf); \ + }) +#else // generic +#define _mm_shufflehi_epi16(a, imm) _mm_shufflehi_epi16_function((a), (imm)) +#endif + +// FORCE_INLINE __m128i _mm_shufflelo_epi16(__m128i a, +// __constrange(0,255) int imm) +#if defined(_sse2neon_shuffle) +#define _mm_shufflelo_epi16(a, imm) \ + __extension__({ \ + int16x8_t _input = vreinterpretq_s16_m128i(a); \ + int16x8_t _shuf = vshuffleq_s16( \ + _input, _input, ((imm) & (0x3)), (((imm) >> 2) & 0x3), \ + (((imm) >> 4) & 0x3), (((imm) >> 6) & 0x3), 4, 5, 6, 7); \ + vreinterpretq_m128i_s16(_shuf); \ + }) +#else // generic +#define _mm_shufflelo_epi16(a, imm) _mm_shufflelo_epi16_function((a), (imm)) +#endif + +// Shift packed 16-bit integers in a left by count while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sll_epi16 +FORCE_INLINE __m128i _mm_sll_epi16(__m128i a, __m128i count) +{ + uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); + if (_sse2neon_unlikely(c & ~15)) + return _mm_setzero_si128(); + + int16x8_t vc = vdupq_n_s16((int16_t) c); + return vreinterpretq_m128i_s16(vshlq_s16(vreinterpretq_s16_m128i(a), vc)); +} + +// Shift packed 32-bit integers in a left by count while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sll_epi32 +FORCE_INLINE __m128i _mm_sll_epi32(__m128i a, __m128i count) +{ + uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); + if (_sse2neon_unlikely(c & ~31)) + return _mm_setzero_si128(); + + int32x4_t vc = vdupq_n_s32((int32_t) c); + return vreinterpretq_m128i_s32(vshlq_s32(vreinterpretq_s32_m128i(a), vc)); +} + +// Shift packed 64-bit integers in a left by count while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sll_epi64 +FORCE_INLINE __m128i _mm_sll_epi64(__m128i a, __m128i count) +{ + uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); + if (_sse2neon_unlikely(c & ~63)) + return _mm_setzero_si128(); + + int64x2_t vc = vdupq_n_s64((int64_t) c); + return vreinterpretq_m128i_s64(vshlq_s64(vreinterpretq_s64_m128i(a), vc)); +} + +// Shift packed 16-bit integers in a left by imm8 while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_slli_epi16 +FORCE_INLINE __m128i _mm_slli_epi16(__m128i a, int imm) +{ + if (_sse2neon_unlikely(imm & ~15)) + return _mm_setzero_si128(); + return vreinterpretq_m128i_s16( + vshlq_s16(vreinterpretq_s16_m128i(a), vdupq_n_s16(imm))); +} + +// Shift packed 32-bit integers in a left by imm8 while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_slli_epi32 +FORCE_INLINE __m128i _mm_slli_epi32(__m128i a, int imm) +{ + if (_sse2neon_unlikely(imm & ~31)) + return _mm_setzero_si128(); + return vreinterpretq_m128i_s32( + vshlq_s32(vreinterpretq_s32_m128i(a), vdupq_n_s32(imm))); +} + +// Shift packed 64-bit integers in a left by imm8 while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_slli_epi64 +FORCE_INLINE __m128i _mm_slli_epi64(__m128i a, int imm) +{ + if (_sse2neon_unlikely(imm & ~63)) + return _mm_setzero_si128(); + return vreinterpretq_m128i_s64( + vshlq_s64(vreinterpretq_s64_m128i(a), vdupq_n_s64(imm))); +} + +// Shift a left by imm8 bytes while shifting in zeros, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_slli_si128 +#define _mm_slli_si128(a, imm) \ + _sse2neon_define1( \ + __m128i, a, int8x16_t ret; \ + if (_sse2neon_unlikely(imm == 0)) ret = vreinterpretq_s8_m128i(_a); \ + else if (_sse2neon_unlikely((imm) & ~15)) ret = vdupq_n_s8(0); \ + else ret = vextq_s8(vdupq_n_s8(0), vreinterpretq_s8_m128i(_a), \ + ((imm <= 0 || imm > 15) ? 0 : (16 - imm))); \ + _sse2neon_return(vreinterpretq_m128i_s8(ret));) + +// Compute the square root of packed double-precision (64-bit) floating-point +// elements in a, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sqrt_pd +FORCE_INLINE __m128d _mm_sqrt_pd(__m128d a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vsqrtq_f64(vreinterpretq_f64_m128d(a))); +#else + double a0 = sqrt(((double *) &a)[0]); + double a1 = sqrt(((double *) &a)[1]); + return _mm_set_pd(a1, a0); +#endif +} + +// Compute the square root of the lower double-precision (64-bit) floating-point +// element in b, store the result in the lower element of dst, and copy the +// upper element from a to the upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sqrt_sd +FORCE_INLINE __m128d _mm_sqrt_sd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return _mm_move_sd(a, _mm_sqrt_pd(b)); +#else + return _mm_set_pd(((double *) &a)[1], sqrt(((double *) &b)[0])); +#endif +} + +// Shift packed 16-bit integers in a right by count while shifting in sign bits, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sra_epi16 +FORCE_INLINE __m128i _mm_sra_epi16(__m128i a, __m128i count) +{ + int64_t c = vgetq_lane_s64(count, 0); + if (_sse2neon_unlikely(c & ~15)) + return _mm_cmplt_epi16(a, _mm_setzero_si128()); + return vreinterpretq_m128i_s16( + vshlq_s16((int16x8_t) a, vdupq_n_s16((int) -c))); +} + +// Shift packed 32-bit integers in a right by count while shifting in sign bits, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sra_epi32 +FORCE_INLINE __m128i _mm_sra_epi32(__m128i a, __m128i count) +{ + int64_t c = vgetq_lane_s64(count, 0); + if (_sse2neon_unlikely(c & ~31)) + return _mm_cmplt_epi32(a, _mm_setzero_si128()); + return vreinterpretq_m128i_s32( + vshlq_s32((int32x4_t) a, vdupq_n_s32((int) -c))); +} + +// Shift packed 16-bit integers in a right by imm8 while shifting in sign +// bits, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srai_epi16 +FORCE_INLINE __m128i _mm_srai_epi16(__m128i a, int imm) +{ + const int count = (imm & ~15) ? 15 : imm; + return (__m128i) vshlq_s16((int16x8_t) a, vdupq_n_s16(-count)); +} + +// Shift packed 32-bit integers in a right by imm8 while shifting in sign bits, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srai_epi32 +// FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, __constrange(0,255) int imm) +#define _mm_srai_epi32(a, imm) \ + _sse2neon_define0( \ + __m128i, a, __m128i ret; if (_sse2neon_unlikely((imm) == 0)) { \ + ret = _a; \ + } else if (_sse2neon_likely(0 < (imm) && (imm) < 32)) { \ + ret = vreinterpretq_m128i_s32( \ + vshlq_s32(vreinterpretq_s32_m128i(_a), vdupq_n_s32(-(imm)))); \ + } else { \ + ret = vreinterpretq_m128i_s32( \ + vshrq_n_s32(vreinterpretq_s32_m128i(_a), 31)); \ + } _sse2neon_return(ret);) + +// Shift packed 16-bit integers in a right by count while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srl_epi16 +FORCE_INLINE __m128i _mm_srl_epi16(__m128i a, __m128i count) +{ + uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); + if (_sse2neon_unlikely(c & ~15)) + return _mm_setzero_si128(); + + int16x8_t vc = vdupq_n_s16(-(int16_t) c); + return vreinterpretq_m128i_u16(vshlq_u16(vreinterpretq_u16_m128i(a), vc)); +} + +// Shift packed 32-bit integers in a right by count while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srl_epi32 +FORCE_INLINE __m128i _mm_srl_epi32(__m128i a, __m128i count) +{ + uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); + if (_sse2neon_unlikely(c & ~31)) + return _mm_setzero_si128(); + + int32x4_t vc = vdupq_n_s32(-(int32_t) c); + return vreinterpretq_m128i_u32(vshlq_u32(vreinterpretq_u32_m128i(a), vc)); +} + +// Shift packed 64-bit integers in a right by count while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srl_epi64 +FORCE_INLINE __m128i _mm_srl_epi64(__m128i a, __m128i count) +{ + uint64_t c = vreinterpretq_nth_u64_m128i(count, 0); + if (_sse2neon_unlikely(c & ~63)) + return _mm_setzero_si128(); + + int64x2_t vc = vdupq_n_s64(-(int64_t) c); + return vreinterpretq_m128i_u64(vshlq_u64(vreinterpretq_u64_m128i(a), vc)); +} + +// Shift packed 16-bit integers in a right by imm8 while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srli_epi16 +#define _mm_srli_epi16(a, imm) \ + _sse2neon_define0( \ + __m128i, a, __m128i ret; if (_sse2neon_unlikely((imm) & ~15)) { \ + ret = _mm_setzero_si128(); \ + } else { \ + ret = vreinterpretq_m128i_u16( \ + vshlq_u16(vreinterpretq_u16_m128i(_a), vdupq_n_s16(-(imm)))); \ + } _sse2neon_return(ret);) + +// Shift packed 32-bit integers in a right by imm8 while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srli_epi32 +// FORCE_INLINE __m128i _mm_srli_epi32(__m128i a, __constrange(0,255) int imm) +#define _mm_srli_epi32(a, imm) \ + _sse2neon_define0( \ + __m128i, a, __m128i ret; if (_sse2neon_unlikely((imm) & ~31)) { \ + ret = _mm_setzero_si128(); \ + } else { \ + ret = vreinterpretq_m128i_u32( \ + vshlq_u32(vreinterpretq_u32_m128i(_a), vdupq_n_s32(-(imm)))); \ + } _sse2neon_return(ret);) + +// Shift packed 64-bit integers in a right by imm8 while shifting in zeros, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srli_epi64 +#define _mm_srli_epi64(a, imm) \ + _sse2neon_define0( \ + __m128i, a, __m128i ret; if (_sse2neon_unlikely((imm) & ~63)) { \ + ret = _mm_setzero_si128(); \ + } else { \ + ret = vreinterpretq_m128i_u64( \ + vshlq_u64(vreinterpretq_u64_m128i(_a), vdupq_n_s64(-(imm)))); \ + } _sse2neon_return(ret);) + +// Shift a right by imm8 bytes while shifting in zeros, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_srli_si128 +#define _mm_srli_si128(a, imm) \ + _sse2neon_define1( \ + __m128i, a, int8x16_t ret; \ + if (_sse2neon_unlikely((imm) & ~15)) ret = vdupq_n_s8(0); \ + else ret = vextq_s8(vreinterpretq_s8_m128i(_a), vdupq_n_s8(0), \ + (imm > 15 ? 0 : imm)); \ + _sse2neon_return(vreinterpretq_m128i_s8(ret));) + +// Store 128-bits (composed of 2 packed double-precision (64-bit) floating-point +// elements) from a into memory. mem_addr must be aligned on a 16-byte boundary +// or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_store_pd +FORCE_INLINE void _mm_store_pd(double *mem_addr, __m128d a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + vst1q_f64((float64_t *) mem_addr, vreinterpretq_f64_m128d(a)); +#else + vst1q_f32((float32_t *) mem_addr, vreinterpretq_f32_m128d(a)); +#endif +} + +// Store the lower double-precision (64-bit) floating-point element from a into +// 2 contiguous elements in memory. mem_addr must be aligned on a 16-byte +// boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_store_pd1 +FORCE_INLINE void _mm_store_pd1(double *mem_addr, __m128d a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + float64x1_t a_low = vget_low_f64(vreinterpretq_f64_m128d(a)); + vst1q_f64((float64_t *) mem_addr, + vreinterpretq_f64_m128d(vcombine_f64(a_low, a_low))); +#else + float32x2_t a_low = vget_low_f32(vreinterpretq_f32_m128d(a)); + vst1q_f32((float32_t *) mem_addr, + vreinterpretq_f32_m128d(vcombine_f32(a_low, a_low))); +#endif +} + +// Store the lower double-precision (64-bit) floating-point element from a into +// memory. mem_addr does not need to be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=mm_store_sd +FORCE_INLINE void _mm_store_sd(double *mem_addr, __m128d a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + vst1_f64((float64_t *) mem_addr, vget_low_f64(vreinterpretq_f64_m128d(a))); +#else + vst1_u64((uint64_t *) mem_addr, vget_low_u64(vreinterpretq_u64_m128d(a))); +#endif +} + +// Store 128-bits of integer data from a into memory. mem_addr must be aligned +// on a 16-byte boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_store_si128 +FORCE_INLINE void _mm_store_si128(__m128i *p, __m128i a) +{ + vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a)); +} + +// Store the lower double-precision (64-bit) floating-point element from a into +// 2 contiguous elements in memory. mem_addr must be aligned on a 16-byte +// boundary or a general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#expand=9,526,5601&text=_mm_store1_pd +#define _mm_store1_pd _mm_store_pd1 + +// Store the upper double-precision (64-bit) floating-point element from a into +// memory. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeh_pd +FORCE_INLINE void _mm_storeh_pd(double *mem_addr, __m128d a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + vst1_f64((float64_t *) mem_addr, vget_high_f64(vreinterpretq_f64_m128d(a))); +#else + vst1_f32((float32_t *) mem_addr, vget_high_f32(vreinterpretq_f32_m128d(a))); +#endif +} + +// Store 64-bit integer from the first element of a into memory. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storel_epi64 +FORCE_INLINE void _mm_storel_epi64(__m128i *a, __m128i b) +{ + vst1_u64((uint64_t *) a, vget_low_u64(vreinterpretq_u64_m128i(b))); +} + +// Store the lower double-precision (64-bit) floating-point element from a into +// memory. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storel_pd +FORCE_INLINE void _mm_storel_pd(double *mem_addr, __m128d a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + vst1_f64((float64_t *) mem_addr, vget_low_f64(vreinterpretq_f64_m128d(a))); +#else + vst1_f32((float32_t *) mem_addr, vget_low_f32(vreinterpretq_f32_m128d(a))); +#endif +} + +// Store 2 double-precision (64-bit) floating-point elements from a into memory +// in reverse order. mem_addr must be aligned on a 16-byte boundary or a +// general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storer_pd +FORCE_INLINE void _mm_storer_pd(double *mem_addr, __m128d a) +{ + float32x4_t f = vreinterpretq_f32_m128d(a); + _mm_store_pd(mem_addr, vreinterpretq_m128d_f32(vextq_f32(f, f, 2))); +} + +// Store 128-bits (composed of 2 packed double-precision (64-bit) floating-point +// elements) from a into memory. mem_addr does not need to be aligned on any +// particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeu_pd +FORCE_INLINE void _mm_storeu_pd(double *mem_addr, __m128d a) +{ + _mm_store_pd(mem_addr, a); +} + +// Store 128-bits of integer data from a into memory. mem_addr does not need to +// be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeu_si128 +FORCE_INLINE void _mm_storeu_si128(__m128i *p, __m128i a) +{ + vst1q_s32((int32_t *) p, vreinterpretq_s32_m128i(a)); +} + +// Store 32-bit integer from the first element of a into memory. mem_addr does +// not need to be aligned on any particular boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_storeu_si32 +FORCE_INLINE void _mm_storeu_si32(void *p, __m128i a) +{ + vst1q_lane_s32((int32_t *) p, vreinterpretq_s32_m128i(a), 0); +} + +// Store 128-bits (composed of 2 packed double-precision (64-bit) floating-point +// elements) from a into memory using a non-temporal memory hint. mem_addr must +// be aligned on a 16-byte boundary or a general-protection exception may be +// generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_stream_pd +FORCE_INLINE void _mm_stream_pd(double *p, __m128d a) +{ +#if __has_builtin(__builtin_nontemporal_store) + __builtin_nontemporal_store(a, (__m128d *) p); +#elif defined(__aarch64__) || defined(_M_ARM64) + vst1q_f64(p, vreinterpretq_f64_m128d(a)); +#else + vst1q_s64((int64_t *) p, vreinterpretq_s64_m128d(a)); +#endif +} + +// Store 128-bits of integer data from a into memory using a non-temporal memory +// hint. mem_addr must be aligned on a 16-byte boundary or a general-protection +// exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_stream_si128 +FORCE_INLINE void _mm_stream_si128(__m128i *p, __m128i a) +{ +#if __has_builtin(__builtin_nontemporal_store) + __builtin_nontemporal_store(a, p); +#else + vst1q_s64((int64_t *) p, vreinterpretq_s64_m128i(a)); +#endif +} + +// Store 32-bit integer a into memory using a non-temporal hint to minimize +// cache pollution. If the cache line containing address mem_addr is already in +// the cache, the cache will be updated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_stream_si32 +FORCE_INLINE void _mm_stream_si32(int *p, int a) +{ + vst1q_lane_s32((int32_t *) p, vdupq_n_s32(a), 0); +} + +// Store 64-bit integer a into memory using a non-temporal hint to minimize +// cache pollution. If the cache line containing address mem_addr is already in +// the cache, the cache will be updated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_stream_si64 +FORCE_INLINE void _mm_stream_si64(__int64 *p, __int64 a) +{ + vst1_s64((int64_t *) p, vdup_n_s64((int64_t) a)); +} + +// Subtract packed 16-bit integers in b from packed 16-bit integers in a, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_epi16 +FORCE_INLINE __m128i _mm_sub_epi16(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s16( + vsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +} + +// Subtract packed 32-bit integers in b from packed 32-bit integers in a, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_epi32 +FORCE_INLINE __m128i _mm_sub_epi32(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s32( + vsubq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +} + +// Subtract packed 64-bit integers in b from packed 64-bit integers in a, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_epi64 +FORCE_INLINE __m128i _mm_sub_epi64(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s64( + vsubq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); +} + +// Subtract packed 8-bit integers in b from packed 8-bit integers in a, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_epi8 +FORCE_INLINE __m128i _mm_sub_epi8(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s8( + vsubq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +} + +// Subtract packed double-precision (64-bit) floating-point elements in b from +// packed double-precision (64-bit) floating-point elements in a, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=mm_sub_pd +FORCE_INLINE __m128d _mm_sub_pd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vsubq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + double *da = (double *) &a; + double *db = (double *) &b; + double c[2]; + c[0] = da[0] - db[0]; + c[1] = da[1] - db[1]; + return vld1q_f32((float32_t *) c); +#endif +} + +// Subtract the lower double-precision (64-bit) floating-point element in b from +// the lower double-precision (64-bit) floating-point element in a, store the +// result in the lower element of dst, and copy the upper element from a to the +// upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_sd +FORCE_INLINE __m128d _mm_sub_sd(__m128d a, __m128d b) +{ + return _mm_move_sd(a, _mm_sub_pd(a, b)); +} + +// Subtract 64-bit integer b from 64-bit integer a, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sub_si64 +FORCE_INLINE __m64 _mm_sub_si64(__m64 a, __m64 b) +{ + return vreinterpret_m64_s64( + vsub_s64(vreinterpret_s64_m64(a), vreinterpret_s64_m64(b))); +} + +// Subtract packed signed 16-bit integers in b from packed 16-bit integers in a +// using saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_subs_epi16 +FORCE_INLINE __m128i _mm_subs_epi16(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s16( + vqsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +} + +// Subtract packed signed 8-bit integers in b from packed 8-bit integers in a +// using saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_subs_epi8 +FORCE_INLINE __m128i _mm_subs_epi8(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s8( + vqsubq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +} + +// Subtract packed unsigned 16-bit integers in b from packed unsigned 16-bit +// integers in a using saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_subs_epu16 +FORCE_INLINE __m128i _mm_subs_epu16(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_u16( + vqsubq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); +} + +// Subtract packed unsigned 8-bit integers in b from packed unsigned 8-bit +// integers in a using saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_subs_epu8 +FORCE_INLINE __m128i _mm_subs_epu8(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_u8( + vqsubq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); +} + +#define _mm_ucomieq_sd _mm_comieq_sd +#define _mm_ucomige_sd _mm_comige_sd +#define _mm_ucomigt_sd _mm_comigt_sd +#define _mm_ucomile_sd _mm_comile_sd +#define _mm_ucomilt_sd _mm_comilt_sd +#define _mm_ucomineq_sd _mm_comineq_sd + +// Return vector of type __m128d with undefined elements. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_undefined_pd +FORCE_INLINE __m128d _mm_undefined_pd(void) +{ +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuninitialized" +#endif + __m128d a; +#if defined(_MSC_VER) + a = _mm_setzero_pd(); +#endif + return a; +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif +} + +// Unpack and interleave 16-bit integers from the high half of a and b, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpackhi_epi16 +FORCE_INLINE __m128i _mm_unpackhi_epi16(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s16( + vzip2q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +#else + int16x4_t a1 = vget_high_s16(vreinterpretq_s16_m128i(a)); + int16x4_t b1 = vget_high_s16(vreinterpretq_s16_m128i(b)); + int16x4x2_t result = vzip_s16(a1, b1); + return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); +#endif +} + +// Unpack and interleave 32-bit integers from the high half of a and b, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpackhi_epi32 +FORCE_INLINE __m128i _mm_unpackhi_epi32(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s32( + vzip2q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +#else + int32x2_t a1 = vget_high_s32(vreinterpretq_s32_m128i(a)); + int32x2_t b1 = vget_high_s32(vreinterpretq_s32_m128i(b)); + int32x2x2_t result = vzip_s32(a1, b1); + return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); +#endif +} + +// Unpack and interleave 64-bit integers from the high half of a and b, and +// store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpackhi_epi64 +FORCE_INLINE __m128i _mm_unpackhi_epi64(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s64( + vzip2q_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); +#else + int64x1_t a_h = vget_high_s64(vreinterpretq_s64_m128i(a)); + int64x1_t b_h = vget_high_s64(vreinterpretq_s64_m128i(b)); + return vreinterpretq_m128i_s64(vcombine_s64(a_h, b_h)); +#endif +} + +// Unpack and interleave 8-bit integers from the high half of a and b, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpackhi_epi8 +FORCE_INLINE __m128i _mm_unpackhi_epi8(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s8( + vzip2q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +#else + int8x8_t a1 = + vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(a))); + int8x8_t b1 = + vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(b))); + int8x8x2_t result = vzip_s8(a1, b1); + return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); +#endif +} + +// Unpack and interleave double-precision (64-bit) floating-point elements from +// the high half of a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpackhi_pd +FORCE_INLINE __m128d _mm_unpackhi_pd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vzip2q_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + return vreinterpretq_m128d_s64( + vcombine_s64(vget_high_s64(vreinterpretq_s64_m128d(a)), + vget_high_s64(vreinterpretq_s64_m128d(b)))); +#endif +} + +// Unpack and interleave 16-bit integers from the low half of a and b, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpacklo_epi16 +FORCE_INLINE __m128i _mm_unpacklo_epi16(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s16( + vzip1q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); +#else + int16x4_t a1 = vget_low_s16(vreinterpretq_s16_m128i(a)); + int16x4_t b1 = vget_low_s16(vreinterpretq_s16_m128i(b)); + int16x4x2_t result = vzip_s16(a1, b1); + return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); +#endif +} + +// Unpack and interleave 32-bit integers from the low half of a and b, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpacklo_epi32 +FORCE_INLINE __m128i _mm_unpacklo_epi32(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s32( + vzip1q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +#else + int32x2_t a1 = vget_low_s32(vreinterpretq_s32_m128i(a)); + int32x2_t b1 = vget_low_s32(vreinterpretq_s32_m128i(b)); + int32x2x2_t result = vzip_s32(a1, b1); + return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); +#endif +} + +// Unpack and interleave 64-bit integers from the low half of a and b, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpacklo_epi64 +FORCE_INLINE __m128i _mm_unpacklo_epi64(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s64( + vzip1q_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); +#else + int64x1_t a_l = vget_low_s64(vreinterpretq_s64_m128i(a)); + int64x1_t b_l = vget_low_s64(vreinterpretq_s64_m128i(b)); + return vreinterpretq_m128i_s64(vcombine_s64(a_l, b_l)); +#endif +} + +// Unpack and interleave 8-bit integers from the low half of a and b, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpacklo_epi8 +FORCE_INLINE __m128i _mm_unpacklo_epi8(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s8( + vzip1q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +#else + int8x8_t a1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(a))); + int8x8_t b1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(b))); + int8x8x2_t result = vzip_s8(a1, b1); + return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); +#endif +} + +// Unpack and interleave double-precision (64-bit) floating-point elements from +// the low half of a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_unpacklo_pd +FORCE_INLINE __m128d _mm_unpacklo_pd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vzip1q_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + return vreinterpretq_m128d_s64( + vcombine_s64(vget_low_s64(vreinterpretq_s64_m128d(a)), + vget_low_s64(vreinterpretq_s64_m128d(b)))); +#endif +} + +// Compute the bitwise XOR of packed double-precision (64-bit) floating-point +// elements in a and b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_xor_pd +FORCE_INLINE __m128d _mm_xor_pd(__m128d a, __m128d b) +{ + return vreinterpretq_m128d_s64( + veorq_s64(vreinterpretq_s64_m128d(a), vreinterpretq_s64_m128d(b))); +} + +// Compute the bitwise XOR of 128 bits (representing integer data) in a and b, +// and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_xor_si128 +FORCE_INLINE __m128i _mm_xor_si128(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s32( + veorq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +} + +/* SSE3 */ + +// Alternatively add and subtract packed double-precision (64-bit) +// floating-point elements in a to/from packed elements in b, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_addsub_pd +FORCE_INLINE __m128d _mm_addsub_pd(__m128d a, __m128d b) +{ + _sse2neon_const __m128d mask = _mm_set_pd(1.0f, -1.0f); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vfmaq_f64(vreinterpretq_f64_m128d(a), + vreinterpretq_f64_m128d(b), + vreinterpretq_f64_m128d(mask))); +#else + return _mm_add_pd(_mm_mul_pd(b, mask), a); +#endif +} + +// Alternatively add and subtract packed single-precision (32-bit) +// floating-point elements in a to/from packed elements in b, and store the +// results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=addsub_ps +FORCE_INLINE __m128 _mm_addsub_ps(__m128 a, __m128 b) +{ + _sse2neon_const __m128 mask = _mm_setr_ps(-1.0f, 1.0f, -1.0f, 1.0f); +#if (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_FMA) /* VFPv4+ */ + return vreinterpretq_m128_f32(vfmaq_f32(vreinterpretq_f32_m128(a), + vreinterpretq_f32_m128(mask), + vreinterpretq_f32_m128(b))); +#else + return _mm_add_ps(_mm_mul_ps(b, mask), a); +#endif +} + +// Horizontally add adjacent pairs of double-precision (64-bit) floating-point +// elements in a and b, and pack the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_pd +FORCE_INLINE __m128d _mm_hadd_pd(__m128d a, __m128d b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vpaddq_f64(vreinterpretq_f64_m128d(a), vreinterpretq_f64_m128d(b))); +#else + double *da = (double *) &a; + double *db = (double *) &b; + double c[] = {da[0] + da[1], db[0] + db[1]}; + return vreinterpretq_m128d_u64(vld1q_u64((uint64_t *) c)); +#endif +} + +// Horizontally add adjacent pairs of single-precision (32-bit) floating-point +// elements in a and b, and pack the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_ps +FORCE_INLINE __m128 _mm_hadd_ps(__m128 a, __m128 b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32( + vpaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); +#else + float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); + float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); + float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); + float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); + return vreinterpretq_m128_f32( + vcombine_f32(vpadd_f32(a10, a32), vpadd_f32(b10, b32))); +#endif +} + +// Horizontally subtract adjacent pairs of double-precision (64-bit) +// floating-point elements in a and b, and pack the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsub_pd +FORCE_INLINE __m128d _mm_hsub_pd(__m128d _a, __m128d _b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + float64x2_t a = vreinterpretq_f64_m128d(_a); + float64x2_t b = vreinterpretq_f64_m128d(_b); + return vreinterpretq_m128d_f64( + vsubq_f64(vuzp1q_f64(a, b), vuzp2q_f64(a, b))); +#else + double *da = (double *) &_a; + double *db = (double *) &_b; + double c[] = {da[0] - da[1], db[0] - db[1]}; + return vreinterpretq_m128d_u64(vld1q_u64((uint64_t *) c)); +#endif +} + +// Horizontally subtract adjacent pairs of single-precision (32-bit) +// floating-point elements in a and b, and pack the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsub_ps +FORCE_INLINE __m128 _mm_hsub_ps(__m128 _a, __m128 _b) +{ + float32x4_t a = vreinterpretq_f32_m128(_a); + float32x4_t b = vreinterpretq_f32_m128(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32( + vsubq_f32(vuzp1q_f32(a, b), vuzp2q_f32(a, b))); +#else + float32x4x2_t c = vuzpq_f32(a, b); + return vreinterpretq_m128_f32(vsubq_f32(c.val[0], c.val[1])); +#endif +} + +// Load 128-bits of integer data from unaligned memory into dst. This intrinsic +// may perform better than _mm_loadu_si128 when the data crosses a cache line +// boundary. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_lddqu_si128 +#define _mm_lddqu_si128 _mm_loadu_si128 + +// Load a double-precision (64-bit) floating-point element from memory into both +// elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_loaddup_pd +#define _mm_loaddup_pd _mm_load1_pd + +// Duplicate the low double-precision (64-bit) floating-point element from a, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movedup_pd +FORCE_INLINE __m128d _mm_movedup_pd(__m128d a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64( + vdupq_laneq_f64(vreinterpretq_f64_m128d(a), 0)); +#else + return vreinterpretq_m128d_u64( + vdupq_n_u64(vgetq_lane_u64(vreinterpretq_u64_m128d(a), 0))); +#endif +} + +// Duplicate odd-indexed single-precision (32-bit) floating-point elements +// from a, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_movehdup_ps +FORCE_INLINE __m128 _mm_movehdup_ps(__m128 a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32( + vtrn2q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a))); +#elif defined(_sse2neon_shuffle) + return vreinterpretq_m128_f32(vshuffleq_s32( + vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 1, 1, 3, 3)); +#else + float32_t a1 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 1); + float32_t a3 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 3); + float ALIGN_STRUCT(16) data[4] = {a1, a1, a3, a3}; + return vreinterpretq_m128_f32(vld1q_f32(data)); +#endif +} + +// Duplicate even-indexed single-precision (32-bit) floating-point elements +// from a, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_moveldup_ps +FORCE_INLINE __m128 _mm_moveldup_ps(__m128 a) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128_f32( + vtrn1q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a))); +#elif defined(_sse2neon_shuffle) + return vreinterpretq_m128_f32(vshuffleq_s32( + vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 0, 0, 2, 2)); +#else + float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); + float32_t a2 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 2); + float ALIGN_STRUCT(16) data[4] = {a0, a0, a2, a2}; + return vreinterpretq_m128_f32(vld1q_f32(data)); +#endif +} + +/* SSSE3 */ + +// Compute the absolute value of packed signed 16-bit integers in a, and store +// the unsigned results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_abs_epi16 +FORCE_INLINE __m128i _mm_abs_epi16(__m128i a) +{ + return vreinterpretq_m128i_s16(vabsq_s16(vreinterpretq_s16_m128i(a))); +} + +// Compute the absolute value of packed signed 32-bit integers in a, and store +// the unsigned results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_abs_epi32 +FORCE_INLINE __m128i _mm_abs_epi32(__m128i a) +{ + return vreinterpretq_m128i_s32(vabsq_s32(vreinterpretq_s32_m128i(a))); +} + +// Compute the absolute value of packed signed 8-bit integers in a, and store +// the unsigned results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_abs_epi8 +FORCE_INLINE __m128i _mm_abs_epi8(__m128i a) +{ + return vreinterpretq_m128i_s8(vabsq_s8(vreinterpretq_s8_m128i(a))); +} + +// Compute the absolute value of packed signed 16-bit integers in a, and store +// the unsigned results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_abs_pi16 +FORCE_INLINE __m64 _mm_abs_pi16(__m64 a) +{ + return vreinterpret_m64_s16(vabs_s16(vreinterpret_s16_m64(a))); +} + +// Compute the absolute value of packed signed 32-bit integers in a, and store +// the unsigned results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_abs_pi32 +FORCE_INLINE __m64 _mm_abs_pi32(__m64 a) +{ + return vreinterpret_m64_s32(vabs_s32(vreinterpret_s32_m64(a))); +} + +// Compute the absolute value of packed signed 8-bit integers in a, and store +// the unsigned results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_abs_pi8 +FORCE_INLINE __m64 _mm_abs_pi8(__m64 a) +{ + return vreinterpret_m64_s8(vabs_s8(vreinterpret_s8_m64(a))); +} + +// Concatenate 16-byte blocks in a and b into a 32-byte temporary result, shift +// the result right by imm8 bytes, and store the low 16 bytes in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_alignr_epi8 +#if defined(__GNUC__) && !defined(__clang__) +#define _mm_alignr_epi8(a, b, imm) \ + __extension__({ \ + uint8x16_t _a = vreinterpretq_u8_m128i(a); \ + uint8x16_t _b = vreinterpretq_u8_m128i(b); \ + __m128i ret; \ + if (_sse2neon_unlikely((imm) & ~31)) \ + ret = vreinterpretq_m128i_u8(vdupq_n_u8(0)); \ + else if (imm >= 16) \ + ret = _mm_srli_si128(a, imm >= 16 ? imm - 16 : 0); \ + else \ + ret = \ + vreinterpretq_m128i_u8(vextq_u8(_b, _a, imm < 16 ? imm : 0)); \ + ret; \ + }) + +#else +#define _mm_alignr_epi8(a, b, imm) \ + _sse2neon_define2( \ + __m128i, a, b, uint8x16_t __a = vreinterpretq_u8_m128i(_a); \ + uint8x16_t __b = vreinterpretq_u8_m128i(_b); __m128i ret; \ + if (_sse2neon_unlikely((imm) & ~31)) ret = \ + vreinterpretq_m128i_u8(vdupq_n_u8(0)); \ + else if (imm >= 16) ret = \ + _mm_srli_si128(_a, imm >= 16 ? imm - 16 : 0); \ + else ret = \ + vreinterpretq_m128i_u8(vextq_u8(__b, __a, imm < 16 ? imm : 0)); \ + _sse2neon_return(ret);) + +#endif + +// Concatenate 8-byte blocks in a and b into a 16-byte temporary result, shift +// the result right by imm8 bytes, and store the low 8 bytes in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_alignr_pi8 +#define _mm_alignr_pi8(a, b, imm) \ + _sse2neon_define2( \ + __m64, a, b, __m64 ret; if (_sse2neon_unlikely((imm) >= 16)) { \ + ret = vreinterpret_m64_s8(vdup_n_s8(0)); \ + } else { \ + uint8x8_t tmp_low; \ + uint8x8_t tmp_high; \ + if ((imm) >= 8) { \ + const int idx = (imm) -8; \ + tmp_low = vreinterpret_u8_m64(_a); \ + tmp_high = vdup_n_u8(0); \ + ret = vreinterpret_m64_u8(vext_u8(tmp_low, tmp_high, idx)); \ + } else { \ + const int idx = (imm); \ + tmp_low = vreinterpret_u8_m64(_b); \ + tmp_high = vreinterpret_u8_m64(_a); \ + ret = vreinterpret_m64_u8(vext_u8(tmp_low, tmp_high, idx)); \ + } \ + } _sse2neon_return(ret);) + +// Horizontally add adjacent pairs of 16-bit integers in a and b, and pack the +// signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_epi16 +FORCE_INLINE __m128i _mm_hadd_epi16(__m128i _a, __m128i _b) +{ + int16x8_t a = vreinterpretq_s16_m128i(_a); + int16x8_t b = vreinterpretq_s16_m128i(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s16(vpaddq_s16(a, b)); +#else + return vreinterpretq_m128i_s16( + vcombine_s16(vpadd_s16(vget_low_s16(a), vget_high_s16(a)), + vpadd_s16(vget_low_s16(b), vget_high_s16(b)))); +#endif +} + +// Horizontally add adjacent pairs of 32-bit integers in a and b, and pack the +// signed 32-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_epi32 +FORCE_INLINE __m128i _mm_hadd_epi32(__m128i _a, __m128i _b) +{ + int32x4_t a = vreinterpretq_s32_m128i(_a); + int32x4_t b = vreinterpretq_s32_m128i(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s32(vpaddq_s32(a, b)); +#else + return vreinterpretq_m128i_s32( + vcombine_s32(vpadd_s32(vget_low_s32(a), vget_high_s32(a)), + vpadd_s32(vget_low_s32(b), vget_high_s32(b)))); +#endif +} + +// Horizontally add adjacent pairs of 16-bit integers in a and b, and pack the +// signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_pi16 +FORCE_INLINE __m64 _mm_hadd_pi16(__m64 a, __m64 b) +{ + return vreinterpret_m64_s16( + vpadd_s16(vreinterpret_s16_m64(a), vreinterpret_s16_m64(b))); +} + +// Horizontally add adjacent pairs of 32-bit integers in a and b, and pack the +// signed 32-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadd_pi32 +FORCE_INLINE __m64 _mm_hadd_pi32(__m64 a, __m64 b) +{ + return vreinterpret_m64_s32( + vpadd_s32(vreinterpret_s32_m64(a), vreinterpret_s32_m64(b))); +} + +// Horizontally add adjacent pairs of signed 16-bit integers in a and b using +// saturation, and pack the signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadds_epi16 +FORCE_INLINE __m128i _mm_hadds_epi16(__m128i _a, __m128i _b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + int16x8_t a = vreinterpretq_s16_m128i(_a); + int16x8_t b = vreinterpretq_s16_m128i(_b); + return vreinterpretq_s64_s16( + vqaddq_s16(vuzp1q_s16(a, b), vuzp2q_s16(a, b))); +#else + int32x4_t a = vreinterpretq_s32_m128i(_a); + int32x4_t b = vreinterpretq_s32_m128i(_b); + // Interleave using vshrn/vmovn + // [a0|a2|a4|a6|b0|b2|b4|b6] + // [a1|a3|a5|a7|b1|b3|b5|b7] + int16x8_t ab0246 = vcombine_s16(vmovn_s32(a), vmovn_s32(b)); + int16x8_t ab1357 = vcombine_s16(vshrn_n_s32(a, 16), vshrn_n_s32(b, 16)); + // Saturated add + return vreinterpretq_m128i_s16(vqaddq_s16(ab0246, ab1357)); +#endif +} + +// Horizontally add adjacent pairs of signed 16-bit integers in a and b using +// saturation, and pack the signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hadds_pi16 +FORCE_INLINE __m64 _mm_hadds_pi16(__m64 _a, __m64 _b) +{ + int16x4_t a = vreinterpret_s16_m64(_a); + int16x4_t b = vreinterpret_s16_m64(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpret_s64_s16(vqadd_s16(vuzp1_s16(a, b), vuzp2_s16(a, b))); +#else + int16x4x2_t res = vuzp_s16(a, b); + return vreinterpret_s64_s16(vqadd_s16(res.val[0], res.val[1])); +#endif +} + +// Horizontally subtract adjacent pairs of 16-bit integers in a and b, and pack +// the signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsub_epi16 +FORCE_INLINE __m128i _mm_hsub_epi16(__m128i _a, __m128i _b) +{ + int16x8_t a = vreinterpretq_s16_m128i(_a); + int16x8_t b = vreinterpretq_s16_m128i(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s16( + vsubq_s16(vuzp1q_s16(a, b), vuzp2q_s16(a, b))); +#else + int16x8x2_t c = vuzpq_s16(a, b); + return vreinterpretq_m128i_s16(vsubq_s16(c.val[0], c.val[1])); +#endif +} + +// Horizontally subtract adjacent pairs of 32-bit integers in a and b, and pack +// the signed 32-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsub_epi32 +FORCE_INLINE __m128i _mm_hsub_epi32(__m128i _a, __m128i _b) +{ + int32x4_t a = vreinterpretq_s32_m128i(_a); + int32x4_t b = vreinterpretq_s32_m128i(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s32( + vsubq_s32(vuzp1q_s32(a, b), vuzp2q_s32(a, b))); +#else + int32x4x2_t c = vuzpq_s32(a, b); + return vreinterpretq_m128i_s32(vsubq_s32(c.val[0], c.val[1])); +#endif +} + +// Horizontally subtract adjacent pairs of 16-bit integers in a and b, and pack +// the signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsub_pi16 +FORCE_INLINE __m64 _mm_hsub_pi16(__m64 _a, __m64 _b) +{ + int16x4_t a = vreinterpret_s16_m64(_a); + int16x4_t b = vreinterpret_s16_m64(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpret_m64_s16(vsub_s16(vuzp1_s16(a, b), vuzp2_s16(a, b))); +#else + int16x4x2_t c = vuzp_s16(a, b); + return vreinterpret_m64_s16(vsub_s16(c.val[0], c.val[1])); +#endif +} + +// Horizontally subtract adjacent pairs of 32-bit integers in a and b, and pack +// the signed 32-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=mm_hsub_pi32 +FORCE_INLINE __m64 _mm_hsub_pi32(__m64 _a, __m64 _b) +{ + int32x2_t a = vreinterpret_s32_m64(_a); + int32x2_t b = vreinterpret_s32_m64(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpret_m64_s32(vsub_s32(vuzp1_s32(a, b), vuzp2_s32(a, b))); +#else + int32x2x2_t c = vuzp_s32(a, b); + return vreinterpret_m64_s32(vsub_s32(c.val[0], c.val[1])); +#endif +} + +// Horizontally subtract adjacent pairs of signed 16-bit integers in a and b +// using saturation, and pack the signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsubs_epi16 +FORCE_INLINE __m128i _mm_hsubs_epi16(__m128i _a, __m128i _b) +{ + int16x8_t a = vreinterpretq_s16_m128i(_a); + int16x8_t b = vreinterpretq_s16_m128i(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s16( + vqsubq_s16(vuzp1q_s16(a, b), vuzp2q_s16(a, b))); +#else + int16x8x2_t c = vuzpq_s16(a, b); + return vreinterpretq_m128i_s16(vqsubq_s16(c.val[0], c.val[1])); +#endif +} + +// Horizontally subtract adjacent pairs of signed 16-bit integers in a and b +// using saturation, and pack the signed 16-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_hsubs_pi16 +FORCE_INLINE __m64 _mm_hsubs_pi16(__m64 _a, __m64 _b) +{ + int16x4_t a = vreinterpret_s16_m64(_a); + int16x4_t b = vreinterpret_s16_m64(_b); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpret_m64_s16(vqsub_s16(vuzp1_s16(a, b), vuzp2_s16(a, b))); +#else + int16x4x2_t c = vuzp_s16(a, b); + return vreinterpret_m64_s16(vqsub_s16(c.val[0], c.val[1])); +#endif +} + +// Vertically multiply each unsigned 8-bit integer from a with the corresponding +// signed 8-bit integer from b, producing intermediate signed 16-bit integers. +// Horizontally add adjacent pairs of intermediate signed 16-bit integers, +// and pack the saturated results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maddubs_epi16 +FORCE_INLINE __m128i _mm_maddubs_epi16(__m128i _a, __m128i _b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + uint8x16_t a = vreinterpretq_u8_m128i(_a); + int8x16_t b = vreinterpretq_s8_m128i(_b); + int16x8_t tl = vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(a))), + vmovl_s8(vget_low_s8(b))); + int16x8_t th = vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(a))), + vmovl_s8(vget_high_s8(b))); + return vreinterpretq_m128i_s16( + vqaddq_s16(vuzp1q_s16(tl, th), vuzp2q_s16(tl, th))); +#else + // This would be much simpler if x86 would choose to zero extend OR sign + // extend, not both. This could probably be optimized better. + uint16x8_t a = vreinterpretq_u16_m128i(_a); + int16x8_t b = vreinterpretq_s16_m128i(_b); + + // Zero extend a + int16x8_t a_odd = vreinterpretq_s16_u16(vshrq_n_u16(a, 8)); + int16x8_t a_even = vreinterpretq_s16_u16(vbicq_u16(a, vdupq_n_u16(0xff00))); + + // Sign extend by shifting left then shifting right. + int16x8_t b_even = vshrq_n_s16(vshlq_n_s16(b, 8), 8); + int16x8_t b_odd = vshrq_n_s16(b, 8); + + // multiply + int16x8_t prod1 = vmulq_s16(a_even, b_even); + int16x8_t prod2 = vmulq_s16(a_odd, b_odd); + + // saturated add + return vreinterpretq_m128i_s16(vqaddq_s16(prod1, prod2)); +#endif +} + +// Vertically multiply each unsigned 8-bit integer from a with the corresponding +// signed 8-bit integer from b, producing intermediate signed 16-bit integers. +// Horizontally add adjacent pairs of intermediate signed 16-bit integers, and +// pack the saturated results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_maddubs_pi16 +FORCE_INLINE __m64 _mm_maddubs_pi16(__m64 _a, __m64 _b) +{ + uint16x4_t a = vreinterpret_u16_m64(_a); + int16x4_t b = vreinterpret_s16_m64(_b); + + // Zero extend a + int16x4_t a_odd = vreinterpret_s16_u16(vshr_n_u16(a, 8)); + int16x4_t a_even = vreinterpret_s16_u16(vand_u16(a, vdup_n_u16(0xff))); + + // Sign extend by shifting left then shifting right. + int16x4_t b_even = vshr_n_s16(vshl_n_s16(b, 8), 8); + int16x4_t b_odd = vshr_n_s16(b, 8); + + // multiply + int16x4_t prod1 = vmul_s16(a_even, b_even); + int16x4_t prod2 = vmul_s16(a_odd, b_odd); + + // saturated add + return vreinterpret_m64_s16(vqadd_s16(prod1, prod2)); +} + +// Multiply packed signed 16-bit integers in a and b, producing intermediate +// signed 32-bit integers. Shift right by 15 bits while rounding up, and store +// the packed 16-bit integers in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mulhrs_epi16 +FORCE_INLINE __m128i _mm_mulhrs_epi16(__m128i a, __m128i b) +{ + // Has issues due to saturation + // return vreinterpretq_m128i_s16(vqrdmulhq_s16(a, b)); + + // Multiply + int32x4_t mul_lo = vmull_s16(vget_low_s16(vreinterpretq_s16_m128i(a)), + vget_low_s16(vreinterpretq_s16_m128i(b))); + int32x4_t mul_hi = vmull_s16(vget_high_s16(vreinterpretq_s16_m128i(a)), + vget_high_s16(vreinterpretq_s16_m128i(b))); + + // Rounding narrowing shift right + // narrow = (int16_t)((mul + 16384) >> 15); + int16x4_t narrow_lo = vrshrn_n_s32(mul_lo, 15); + int16x4_t narrow_hi = vrshrn_n_s32(mul_hi, 15); + + // Join together + return vreinterpretq_m128i_s16(vcombine_s16(narrow_lo, narrow_hi)); } -// Convert packed 16-bit integers in a to packed single-precision (32-bit) -// floating-point elements, and store the results in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// m := j*32 -// dst[m+31:m] := Convert_Int16_To_FP32(a[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtpi16_ps -FORCE_INLINE __m128 _mm_cvtpi16_ps(__m64 a) +// Multiply packed signed 16-bit integers in a and b, producing intermediate +// signed 32-bit integers. Truncate each intermediate integer to the 18 most +// significant bits, round by adding 1, and store bits [16:1] to dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mulhrs_pi16 +FORCE_INLINE __m64 _mm_mulhrs_pi16(__m64 a, __m64 b) { - return vreinterpretq_m128_f32( - vcvtq_f32_s32(vmovl_s16(vreinterpret_s16_m64(a)))); -} + int32x4_t mul_extend = + vmull_s16((vreinterpret_s16_m64(a)), (vreinterpret_s16_m64(b))); -// Convert packed 32-bit integers in b to packed single-precision (32-bit) -// floating-point elements, store the results in the lower 2 elements of dst, -// and copy the upper 2 packed elements from a to the upper elements of dst. -// -// dst[31:0] := Convert_Int32_To_FP32(b[31:0]) -// dst[63:32] := Convert_Int32_To_FP32(b[63:32]) -// dst[95:64] := a[95:64] -// dst[127:96] := a[127:96] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtpi32_ps -FORCE_INLINE __m128 _mm_cvtpi32_ps(__m128 a, __m64 b) -{ - return vreinterpretq_m128_f32( - vcombine_f32(vcvt_f32_s32(vreinterpret_s32_m64(b)), - vget_high_f32(vreinterpretq_f32_m128(a)))); + // Rounding narrowing shift right + return vreinterpret_m64_s16(vrshrn_n_s32(mul_extend, 15)); } -// Convert packed signed 32-bit integers in a to packed single-precision -// (32-bit) floating-point elements, store the results in the lower 2 elements -// of dst, then covert the packed signed 32-bit integers in b to -// single-precision (32-bit) floating-point element, and store the results in -// the upper 2 elements of dst. -// -// dst[31:0] := Convert_Int32_To_FP32(a[31:0]) -// dst[63:32] := Convert_Int32_To_FP32(a[63:32]) -// dst[95:64] := Convert_Int32_To_FP32(b[31:0]) -// dst[127:96] := Convert_Int32_To_FP32(b[63:32]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtpi32x2_ps -FORCE_INLINE __m128 _mm_cvtpi32x2_ps(__m64 a, __m64 b) +// Shuffle packed 8-bit integers in a according to shuffle control mask in the +// corresponding 8-bit element of b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_epi8 +FORCE_INLINE __m128i _mm_shuffle_epi8(__m128i a, __m128i b) { - return vreinterpretq_m128_f32(vcvtq_f32_s32( - vcombine_s32(vreinterpret_s32_m64(a), vreinterpret_s32_m64(b)))); + int8x16_t tbl = vreinterpretq_s8_m128i(a); // input a + uint8x16_t idx = vreinterpretq_u8_m128i(b); // input b + uint8x16_t idx_masked = + vandq_u8(idx, vdupq_n_u8(0x8F)); // avoid using meaningless bits +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_s8(vqtbl1q_s8(tbl, idx_masked)); +#elif defined(__GNUC__) + int8x16_t ret; + // %e and %f represent the even and odd D registers + // respectively. + __asm__ __volatile__( + "vtbl.8 %e[ret], {%e[tbl], %f[tbl]}, %e[idx]\n" + "vtbl.8 %f[ret], {%e[tbl], %f[tbl]}, %f[idx]\n" + : [ret] "=&w"(ret) + : [tbl] "w"(tbl), [idx] "w"(idx_masked)); + return vreinterpretq_m128i_s8(ret); +#else + // use this line if testing on aarch64 + int8x8x2_t a_split = {vget_low_s8(tbl), vget_high_s8(tbl)}; + return vreinterpretq_m128i_s8( + vcombine_s8(vtbl2_s8(a_split, vget_low_u8(idx_masked)), + vtbl2_s8(a_split, vget_high_u8(idx_masked)))); +#endif } -// Convert the lower packed 8-bit integers in a to packed single-precision -// (32-bit) floating-point elements, and store the results in dst. -// -// FOR j := 0 to 3 -// i := j*8 -// m := j*32 -// dst[m+31:m] := Convert_Int8_To_FP32(a[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtpi8_ps -FORCE_INLINE __m128 _mm_cvtpi8_ps(__m64 a) +// Shuffle packed 8-bit integers in a according to shuffle control mask in the +// corresponding 8-bit element of b, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_shuffle_pi8 +FORCE_INLINE __m64 _mm_shuffle_pi8(__m64 a, __m64 b) { - return vreinterpretq_m128_f32(vcvtq_f32_s32( - vmovl_s16(vget_low_s16(vmovl_s8(vreinterpret_s8_m64(a)))))); + const int8x8_t controlMask = + vand_s8(vreinterpret_s8_m64(b), vdup_n_s8((int8_t) (0x1 << 7 | 0x07))); + int8x8_t res = vtbl1_s8(vreinterpret_s8_m64(a), controlMask); + return vreinterpret_m64_s8(res); } -// Convert packed unsigned 16-bit integers in a to packed single-precision -// (32-bit) floating-point elements, and store the results in dst. -// -// FOR j := 0 to 3 -// i := j*16 -// m := j*32 -// dst[m+31:m] := Convert_UInt16_To_FP32(a[i+15:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtpu16_ps -FORCE_INLINE __m128 _mm_cvtpu16_ps(__m64 a) +// Negate packed 16-bit integers in a when the corresponding signed +// 16-bit integer in b is negative, and store the results in dst. +// Element in dst are zeroed out when the corresponding element +// in b is zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sign_epi16 +FORCE_INLINE __m128i _mm_sign_epi16(__m128i _a, __m128i _b) { - return vreinterpretq_m128_f32( - vcvtq_f32_u32(vmovl_u16(vreinterpret_u16_m64(a)))); -} + int16x8_t a = vreinterpretq_s16_m128i(_a); + int16x8_t b = vreinterpretq_s16_m128i(_b); -// Convert the lower packed unsigned 8-bit integers in a to packed -// single-precision (32-bit) floating-point elements, and store the results in -// dst. -// -// FOR j := 0 to 3 -// i := j*8 -// m := j*32 -// dst[m+31:m] := Convert_UInt8_To_FP32(a[i+7:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtpu8_ps -FORCE_INLINE __m128 _mm_cvtpu8_ps(__m64 a) -{ - return vreinterpretq_m128_f32(vcvtq_f32_u32( - vmovl_u16(vget_low_u16(vmovl_u8(vreinterpret_u8_m64(a)))))); + // signed shift right: faster than vclt + // (b < 0) ? 0xFFFF : 0 + uint16x8_t ltMask = vreinterpretq_u16_s16(vshrq_n_s16(b, 15)); + // (b == 0) ? 0xFFFF : 0 +#if defined(__aarch64__) || defined(_M_ARM64) + int16x8_t zeroMask = vreinterpretq_s16_u16(vceqzq_s16(b)); +#else + int16x8_t zeroMask = vreinterpretq_s16_u16(vceqq_s16(b, vdupq_n_s16(0))); +#endif + + // bitwise select either a or negative 'a' (vnegq_s16(a) equals to negative + // 'a') based on ltMask + int16x8_t masked = vbslq_s16(ltMask, vnegq_s16(a), a); + // res = masked & (~zeroMask) + int16x8_t res = vbicq_s16(masked, zeroMask); + return vreinterpretq_m128i_s16(res); } -// Converts the four single-precision, floating-point values of a to signed -// 32-bit integer values using truncate. -// https://msdn.microsoft.com/en-us/library/vstudio/1h005y6x(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cvttps_epi32(__m128 a) +// Negate packed 32-bit integers in a when the corresponding signed +// 32-bit integer in b is negative, and store the results in dst. +// Element in dst are zeroed out when the corresponding element +// in b is zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sign_epi32 +FORCE_INLINE __m128i _mm_sign_epi32(__m128i _a, __m128i _b) { - return vreinterpretq_m128i_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a))); + int32x4_t a = vreinterpretq_s32_m128i(_a); + int32x4_t b = vreinterpretq_s32_m128i(_b); + + // signed shift right: faster than vclt + // (b < 0) ? 0xFFFFFFFF : 0 + uint32x4_t ltMask = vreinterpretq_u32_s32(vshrq_n_s32(b, 31)); + + // (b == 0) ? 0xFFFFFFFF : 0 +#if defined(__aarch64__) || defined(_M_ARM64) + int32x4_t zeroMask = vreinterpretq_s32_u32(vceqzq_s32(b)); +#else + int32x4_t zeroMask = vreinterpretq_s32_u32(vceqq_s32(b, vdupq_n_s32(0))); +#endif + + // bitwise select either a or negative 'a' (vnegq_s32(a) equals to negative + // 'a') based on ltMask + int32x4_t masked = vbslq_s32(ltMask, vnegq_s32(a), a); + // res = masked & (~zeroMask) + int32x4_t res = vbicq_s32(masked, zeroMask); + return vreinterpretq_m128i_s32(res); } -// Convert the lower double-precision (64-bit) floating-point element in a to a -// 64-bit integer with truncation, and store the result in dst. -// -// dst[63:0] := Convert_FP64_To_Int64_Truncate(a[63:0]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvttsd_si64 -FORCE_INLINE int64_t _mm_cvttsd_si64(__m128d a) +// Negate packed 8-bit integers in a when the corresponding signed +// 8-bit integer in b is negative, and store the results in dst. +// Element in dst are zeroed out when the corresponding element +// in b is zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sign_epi8 +FORCE_INLINE __m128i _mm_sign_epi8(__m128i _a, __m128i _b) { -#if defined(__aarch64__) - return vgetq_lane_s64(vcvtq_s64_f64(vreinterpretq_f64_m128d(a)), 0); + int8x16_t a = vreinterpretq_s8_m128i(_a); + int8x16_t b = vreinterpretq_s8_m128i(_b); + + // signed shift right: faster than vclt + // (b < 0) ? 0xFF : 0 + uint8x16_t ltMask = vreinterpretq_u8_s8(vshrq_n_s8(b, 7)); + + // (b == 0) ? 0xFF : 0 +#if defined(__aarch64__) || defined(_M_ARM64) + int8x16_t zeroMask = vreinterpretq_s8_u8(vceqzq_s8(b)); #else - double ret = *((double *) &a); - return (int64_t) ret; + int8x16_t zeroMask = vreinterpretq_s8_u8(vceqq_s8(b, vdupq_n_s8(0))); #endif -} -// Convert the lower double-precision (64-bit) floating-point element in a to a -// 64-bit integer with truncation, and store the result in dst. -// -// dst[63:0] := Convert_FP64_To_Int64_Truncate(a[63:0]) -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvttsd_si64x -#define _mm_cvttsd_si64x(a) _mm_cvttsd_si64(a) + // bitwise select either a or negative 'a' (vnegq_s8(a) return negative 'a') + // based on ltMask + int8x16_t masked = vbslq_s8(ltMask, vnegq_s8(a), a); + // res = masked & (~zeroMask) + int8x16_t res = vbicq_s8(masked, zeroMask); -// Converts the four signed 32-bit integer values of a to single-precision, -// floating-point values -// https://msdn.microsoft.com/en-us/library/vstudio/36bwxcx5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cvtepi32_ps(__m128i a) -{ - return vreinterpretq_m128_f32(vcvtq_f32_s32(vreinterpretq_s32_m128i(a))); + return vreinterpretq_m128i_s8(res); } -// Converts the four unsigned 8-bit integers in the lower 16 bits to four -// unsigned 32-bit integers. -FORCE_INLINE __m128i _mm_cvtepu8_epi16(__m128i a) +// Negate packed 16-bit integers in a when the corresponding signed 16-bit +// integer in b is negative, and store the results in dst. Element in dst are +// zeroed out when the corresponding element in b is zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sign_pi16 +FORCE_INLINE __m64 _mm_sign_pi16(__m64 _a, __m64 _b) { - uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx DCBA */ - uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */ - return vreinterpretq_m128i_u16(u16x8); -} + int16x4_t a = vreinterpret_s16_m64(_a); + int16x4_t b = vreinterpret_s16_m64(_b); -// Converts the four unsigned 8-bit integers in the lower 32 bits to four -// unsigned 32-bit integers. -// https://msdn.microsoft.com/en-us/library/bb531467%28v=vs.100%29.aspx -FORCE_INLINE __m128i _mm_cvtepu8_epi32(__m128i a) -{ - uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx DCBA */ - uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */ - uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000D 000C 000B 000A */ - return vreinterpretq_m128i_u32(u32x4); -} + // signed shift right: faster than vclt + // (b < 0) ? 0xFFFF : 0 + uint16x4_t ltMask = vreinterpret_u16_s16(vshr_n_s16(b, 15)); -// Converts the two unsigned 8-bit integers in the lower 16 bits to two -// unsigned 64-bit integers. -FORCE_INLINE __m128i _mm_cvtepu8_epi64(__m128i a) -{ - uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx xxBA */ - uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0x0x 0B0A */ - uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */ - uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */ - return vreinterpretq_m128i_u64(u64x2); -} + // (b == 0) ? 0xFFFF : 0 +#if defined(__aarch64__) || defined(_M_ARM64) + int16x4_t zeroMask = vreinterpret_s16_u16(vceqz_s16(b)); +#else + int16x4_t zeroMask = vreinterpret_s16_u16(vceq_s16(b, vdup_n_s16(0))); +#endif -// Converts the four unsigned 8-bit integers in the lower 16 bits to four -// unsigned 32-bit integers. -FORCE_INLINE __m128i _mm_cvtepi8_epi16(__m128i a) -{ - int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */ - int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */ - return vreinterpretq_m128i_s16(s16x8); -} + // bitwise select either a or negative 'a' (vneg_s16(a) return negative 'a') + // based on ltMask + int16x4_t masked = vbsl_s16(ltMask, vneg_s16(a), a); + // res = masked & (~zeroMask) + int16x4_t res = vbic_s16(masked, zeroMask); -// Converts the four unsigned 8-bit integers in the lower 32 bits to four -// unsigned 32-bit integers. -FORCE_INLINE __m128i _mm_cvtepi8_epi32(__m128i a) -{ - int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */ - int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */ - int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000D 000C 000B 000A */ - return vreinterpretq_m128i_s32(s32x4); + return vreinterpret_m64_s16(res); } -// Converts the two signed 8-bit integers in the lower 32 bits to four -// signed 64-bit integers. -FORCE_INLINE __m128i _mm_cvtepi8_epi64(__m128i a) +// Negate packed 32-bit integers in a when the corresponding signed 32-bit +// integer in b is negative, and store the results in dst. Element in dst are +// zeroed out when the corresponding element in b is zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sign_pi32 +FORCE_INLINE __m64 _mm_sign_pi32(__m64 _a, __m64 _b) { - int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx xxBA */ - int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0x0x 0B0A */ - int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */ - int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */ - return vreinterpretq_m128i_s64(s64x2); -} + int32x2_t a = vreinterpret_s32_m64(_a); + int32x2_t b = vreinterpret_s32_m64(_b); -// Converts the four signed 16-bit integers in the lower 64 bits to four signed -// 32-bit integers. -FORCE_INLINE __m128i _mm_cvtepi16_epi32(__m128i a) -{ - return vreinterpretq_m128i_s32( - vmovl_s16(vget_low_s16(vreinterpretq_s16_m128i(a)))); -} + // signed shift right: faster than vclt + // (b < 0) ? 0xFFFFFFFF : 0 + uint32x2_t ltMask = vreinterpret_u32_s32(vshr_n_s32(b, 31)); -// Converts the two signed 16-bit integers in the lower 32 bits two signed -// 32-bit integers. -FORCE_INLINE __m128i _mm_cvtepi16_epi64(__m128i a) -{ - int16x8_t s16x8 = vreinterpretq_s16_m128i(a); /* xxxx xxxx xxxx 0B0A */ - int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */ - int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */ - return vreinterpretq_m128i_s64(s64x2); -} + // (b == 0) ? 0xFFFFFFFF : 0 +#if defined(__aarch64__) || defined(_M_ARM64) + int32x2_t zeroMask = vreinterpret_s32_u32(vceqz_s32(b)); +#else + int32x2_t zeroMask = vreinterpret_s32_u32(vceq_s32(b, vdup_n_s32(0))); +#endif -// Converts the four unsigned 16-bit integers in the lower 64 bits to four -// unsigned 32-bit integers. -FORCE_INLINE __m128i _mm_cvtepu16_epi32(__m128i a) -{ - return vreinterpretq_m128i_u32( - vmovl_u16(vget_low_u16(vreinterpretq_u16_m128i(a)))); -} + // bitwise select either a or negative 'a' (vneg_s32(a) return negative 'a') + // based on ltMask + int32x2_t masked = vbsl_s32(ltMask, vneg_s32(a), a); + // res = masked & (~zeroMask) + int32x2_t res = vbic_s32(masked, zeroMask); -// Converts the two unsigned 16-bit integers in the lower 32 bits to two -// unsigned 64-bit integers. -FORCE_INLINE __m128i _mm_cvtepu16_epi64(__m128i a) -{ - uint16x8_t u16x8 = vreinterpretq_u16_m128i(a); /* xxxx xxxx xxxx 0B0A */ - uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */ - uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */ - return vreinterpretq_m128i_u64(u64x2); + return vreinterpret_m64_s32(res); } -// Converts the two unsigned 32-bit integers in the lower 64 bits to two -// unsigned 64-bit integers. -FORCE_INLINE __m128i _mm_cvtepu32_epi64(__m128i a) +// Negate packed 8-bit integers in a when the corresponding signed 8-bit integer +// in b is negative, and store the results in dst. Element in dst are zeroed out +// when the corresponding element in b is zero. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_sign_pi8 +FORCE_INLINE __m64 _mm_sign_pi8(__m64 _a, __m64 _b) { - return vreinterpretq_m128i_u64( - vmovl_u32(vget_low_u32(vreinterpretq_u32_m128i(a)))); -} + int8x8_t a = vreinterpret_s8_m64(_a); + int8x8_t b = vreinterpret_s8_m64(_b); -// Converts the two signed 32-bit integers in the lower 64 bits to two signed -// 64-bit integers. -FORCE_INLINE __m128i _mm_cvtepi32_epi64(__m128i a) -{ - return vreinterpretq_m128i_s64( - vmovl_s32(vget_low_s32(vreinterpretq_s32_m128i(a)))); -} + // signed shift right: faster than vclt + // (b < 0) ? 0xFF : 0 + uint8x8_t ltMask = vreinterpret_u8_s8(vshr_n_s8(b, 7)); -// Converts the four single-precision, floating-point values of a to signed -// 32-bit integer values. -// -// r0 := (int) a0 -// r1 := (int) a1 -// r2 := (int) a2 -// r3 := (int) a3 -// -// https://msdn.microsoft.com/en-us/library/vstudio/xdc42k5e(v=vs.100).aspx -// *NOTE*. The default rounding mode on SSE is 'round to even', which ARMv7-A -// does not support! It is supported on ARMv8-A however. -FORCE_INLINE __m128i _mm_cvtps_epi32(__m128 a) -{ -#if defined(__aarch64__) - return vreinterpretq_m128i_s32(vcvtnq_s32_f32(a)); -#else - uint32x4_t signmask = vdupq_n_u32(0x80000000); - float32x4_t half = vbslq_f32(signmask, vreinterpretq_f32_m128(a), - vdupq_n_f32(0.5f)); /* +/- 0.5 */ - int32x4_t r_normal = vcvtq_s32_f32(vaddq_f32( - vreinterpretq_f32_m128(a), half)); /* round to integer: [a + 0.5]*/ - int32x4_t r_trunc = - vcvtq_s32_f32(vreinterpretq_f32_m128(a)); /* truncate to integer: [a] */ - int32x4_t plusone = vreinterpretq_s32_u32(vshrq_n_u32( - vreinterpretq_u32_s32(vnegq_s32(r_trunc)), 31)); /* 1 or 0 */ - int32x4_t r_even = vbicq_s32(vaddq_s32(r_trunc, plusone), - vdupq_n_s32(1)); /* ([a] + {0,1}) & ~1 */ - float32x4_t delta = vsubq_f32( - vreinterpretq_f32_m128(a), - vcvtq_f32_s32(r_trunc)); /* compute delta: delta = (a - [a]) */ - uint32x4_t is_delta_half = vceqq_f32(delta, half); /* delta == +/- 0.5 */ - return vreinterpretq_m128i_s32(vbslq_s32(is_delta_half, r_even, r_normal)); + // (b == 0) ? 0xFF : 0 +#if defined(__aarch64__) || defined(_M_ARM64) + int8x8_t zeroMask = vreinterpret_s8_u8(vceqz_s8(b)); +#else + int8x8_t zeroMask = vreinterpret_s8_u8(vceq_s8(b, vdup_n_s8(0))); #endif + + // bitwise select either a or negative 'a' (vneg_s8(a) return negative 'a') + // based on ltMask + int8x8_t masked = vbsl_s8(ltMask, vneg_s8(a), a); + // res = masked & (~zeroMask) + int8x8_t res = vbic_s8(masked, zeroMask); + + return vreinterpret_m64_s8(res); } -// Copy the lower 32-bit integer in a to dst. -// -// dst[31:0] := a[31:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtsi128_si32 -FORCE_INLINE int _mm_cvtsi128_si32(__m128i a) +/* SSE4.1 */ + +// Blend packed 16-bit integers from a and b using control mask imm8, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_blend_epi16 +// FORCE_INLINE __m128i _mm_blend_epi16(__m128i a, __m128i b, +// __constrange(0,255) int imm) +#define _mm_blend_epi16(a, b, imm) \ + _sse2neon_define2( \ + __m128i, a, b, \ + const uint16_t _mask[8] = \ + _sse2neon_init(((imm) & (1 << 0)) ? (uint16_t) -1 : 0x0, \ + ((imm) & (1 << 1)) ? (uint16_t) -1 : 0x0, \ + ((imm) & (1 << 2)) ? (uint16_t) -1 : 0x0, \ + ((imm) & (1 << 3)) ? (uint16_t) -1 : 0x0, \ + ((imm) & (1 << 4)) ? (uint16_t) -1 : 0x0, \ + ((imm) & (1 << 5)) ? (uint16_t) -1 : 0x0, \ + ((imm) & (1 << 6)) ? (uint16_t) -1 : 0x0, \ + ((imm) & (1 << 7)) ? (uint16_t) -1 : 0x0); \ + uint16x8_t _mask_vec = vld1q_u16(_mask); \ + uint16x8_t __a = vreinterpretq_u16_m128i(_a); \ + uint16x8_t __b = vreinterpretq_u16_m128i(_b); _sse2neon_return( \ + vreinterpretq_m128i_u16(vbslq_u16(_mask_vec, __b, __a)));) + +// Blend packed double-precision (64-bit) floating-point elements from a and b +// using control mask imm8, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_blend_pd +#define _mm_blend_pd(a, b, imm) \ + _sse2neon_define2( \ + __m128d, a, b, \ + const uint64_t _mask[2] = \ + _sse2neon_init(((imm) & (1 << 0)) ? ~UINT64_C(0) : UINT64_C(0), \ + ((imm) & (1 << 1)) ? ~UINT64_C(0) : UINT64_C(0)); \ + uint64x2_t _mask_vec = vld1q_u64(_mask); \ + uint64x2_t __a = vreinterpretq_u64_m128d(_a); \ + uint64x2_t __b = vreinterpretq_u64_m128d(_b); _sse2neon_return( \ + vreinterpretq_m128d_u64(vbslq_u64(_mask_vec, __b, __a)));) + +// Blend packed single-precision (32-bit) floating-point elements from a and b +// using mask, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_blend_ps +FORCE_INLINE __m128 _mm_blend_ps(__m128 _a, __m128 _b, const char imm8) { - return vgetq_lane_s32(vreinterpretq_s32_m128i(a), 0); + const uint32_t ALIGN_STRUCT(16) + data[4] = {((imm8) & (1 << 0)) ? UINT32_MAX : 0, + ((imm8) & (1 << 1)) ? UINT32_MAX : 0, + ((imm8) & (1 << 2)) ? UINT32_MAX : 0, + ((imm8) & (1 << 3)) ? UINT32_MAX : 0}; + uint32x4_t mask = vld1q_u32(data); + float32x4_t a = vreinterpretq_f32_m128(_a); + float32x4_t b = vreinterpretq_f32_m128(_b); + return vreinterpretq_m128_f32(vbslq_f32(mask, b, a)); } -// Copy the lower 64-bit integer in a to dst. -// -// dst[63:0] := a[63:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtsi128_si64 -FORCE_INLINE int64_t _mm_cvtsi128_si64(__m128i a) +// Blend packed 8-bit integers from a and b using mask, and store the results in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_blendv_epi8 +FORCE_INLINE __m128i _mm_blendv_epi8(__m128i _a, __m128i _b, __m128i _mask) { - return vgetq_lane_s64(vreinterpretq_s64_m128i(a), 0); + // Use a signed shift right to create a mask with the sign bit + uint8x16_t mask = + vreinterpretq_u8_s8(vshrq_n_s8(vreinterpretq_s8_m128i(_mask), 7)); + uint8x16_t a = vreinterpretq_u8_m128i(_a); + uint8x16_t b = vreinterpretq_u8_m128i(_b); + return vreinterpretq_m128i_u8(vbslq_u8(mask, b, a)); } -// Copy the lower 64-bit integer in a to dst. -// -// dst[63:0] := a[63:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtsi128_si64x -#define _mm_cvtsi128_si64x(a) _mm_cvtsi128_si64(a) - -// Moves 32-bit integer a to the least significant 32 bits of an __m128 object, -// zero extending the upper bits. -// -// r0 := a -// r1 := 0x0 -// r2 := 0x0 -// r3 := 0x0 -// -// https://msdn.microsoft.com/en-us/library/ct3539ha%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_cvtsi32_si128(int a) +// Blend packed double-precision (64-bit) floating-point elements from a and b +// using mask, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_blendv_pd +FORCE_INLINE __m128d _mm_blendv_pd(__m128d _a, __m128d _b, __m128d _mask) { - return vreinterpretq_m128i_s32(vsetq_lane_s32(a, vdupq_n_s32(0), 0)); + uint64x2_t mask = + vreinterpretq_u64_s64(vshrq_n_s64(vreinterpretq_s64_m128d(_mask), 63)); +#if defined(__aarch64__) || defined(_M_ARM64) + float64x2_t a = vreinterpretq_f64_m128d(_a); + float64x2_t b = vreinterpretq_f64_m128d(_b); + return vreinterpretq_m128d_f64(vbslq_f64(mask, b, a)); +#else + uint64x2_t a = vreinterpretq_u64_m128d(_a); + uint64x2_t b = vreinterpretq_u64_m128d(_b); + return vreinterpretq_m128d_u64(vbslq_u64(mask, b, a)); +#endif } -// Moves 64-bit integer a to the least significant 64 bits of an __m128 object, -// zero extending the upper bits. -// -// r0 := a -// r1 := 0x0 -FORCE_INLINE __m128i _mm_cvtsi64_si128(int64_t a) +// Blend packed single-precision (32-bit) floating-point elements from a and b +// using mask, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_blendv_ps +FORCE_INLINE __m128 _mm_blendv_ps(__m128 _a, __m128 _b, __m128 _mask) { - return vreinterpretq_m128i_s64(vsetq_lane_s64(a, vdupq_n_s64(0), 0)); + // Use a signed shift right to create a mask with the sign bit + uint32x4_t mask = + vreinterpretq_u32_s32(vshrq_n_s32(vreinterpretq_s32_m128(_mask), 31)); + float32x4_t a = vreinterpretq_f32_m128(_a); + float32x4_t b = vreinterpretq_f32_m128(_b); + return vreinterpretq_m128_f32(vbslq_f32(mask, b, a)); } -// Cast vector of type __m128 to type __m128d. This intrinsic is only used for -// compilation and does not generate any instructions, thus it has zero latency. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_castps_pd -FORCE_INLINE __m128d _mm_castps_pd(__m128 a) +// Round the packed double-precision (64-bit) floating-point elements in a up +// to an integer value, and store the results as packed double-precision +// floating-point elements in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_ceil_pd +FORCE_INLINE __m128d _mm_ceil_pd(__m128d a) { - return vreinterpretq_m128d_s32(vreinterpretq_s32_m128(a)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vrndpq_f64(vreinterpretq_f64_m128d(a))); +#else + double *f = (double *) &a; + return _mm_set_pd(ceil(f[1]), ceil(f[0])); +#endif } -// Applies a type cast to reinterpret four 32-bit floating point values passed -// in as a 128-bit parameter as packed 32-bit integers. -// https://msdn.microsoft.com/en-us/library/bb514099.aspx -FORCE_INLINE __m128i _mm_castps_si128(__m128 a) +// Round the packed single-precision (32-bit) floating-point elements in a up to +// an integer value, and store the results as packed single-precision +// floating-point elements in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_ceil_ps +FORCE_INLINE __m128 _mm_ceil_ps(__m128 a) { - return vreinterpretq_m128i_s32(vreinterpretq_s32_m128(a)); +#if (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_DIRECTED_ROUNDING) + return vreinterpretq_m128_f32(vrndpq_f32(vreinterpretq_f32_m128(a))); +#else + float *f = (float *) &a; + return _mm_set_ps(ceilf(f[3]), ceilf(f[2]), ceilf(f[1]), ceilf(f[0])); +#endif } -// Applies a type cast to reinterpret four 32-bit integers passed in as a -// 128-bit parameter as packed 32-bit floating point values. -// https://msdn.microsoft.com/en-us/library/bb514029.aspx -FORCE_INLINE __m128 _mm_castsi128_ps(__m128i a) +// Round the lower double-precision (64-bit) floating-point element in b up to +// an integer value, store the result as a double-precision floating-point +// element in the lower element of dst, and copy the upper element from a to the +// upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_ceil_sd +FORCE_INLINE __m128d _mm_ceil_sd(__m128d a, __m128d b) { - return vreinterpretq_m128_s32(vreinterpretq_s32_m128i(a)); + return _mm_move_sd(a, _mm_ceil_pd(b)); } -// Loads 128-bit value. : -// https://msdn.microsoft.com/en-us/library/atzzad1h(v=vs.80).aspx -FORCE_INLINE __m128i _mm_load_si128(const __m128i *p) +// Round the lower single-precision (32-bit) floating-point element in b up to +// an integer value, store the result as a single-precision floating-point +// element in the lower element of dst, and copy the upper 3 packed elements +// from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_ceil_ss +FORCE_INLINE __m128 _mm_ceil_ss(__m128 a, __m128 b) { - return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p)); + return _mm_move_ss(a, _mm_ceil_ps(b)); } -// Load a double-precision (64-bit) floating-point element from memory into both -// elements of dst. -// -// dst[63:0] := MEM[mem_addr+63:mem_addr] -// dst[127:64] := MEM[mem_addr+63:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load1_pd -FORCE_INLINE __m128d _mm_load1_pd(const double *p) +// Compare packed 64-bit integers in a and b for equality, and store the results +// in dst +FORCE_INLINE __m128i _mm_cmpeq_epi64(__m128i a, __m128i b) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64(vld1q_dup_f64(p)); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_u64( + vceqq_u64(vreinterpretq_u64_m128i(a), vreinterpretq_u64_m128i(b))); #else - return vreinterpretq_m128d_s64(vdupq_n_s64(*(const int64_t *) p)); + // ARMv7 lacks vceqq_u64 + // (a == b) -> (a_lo == b_lo) && (a_hi == b_hi) + uint32x4_t cmp = + vceqq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b)); + uint32x4_t swapped = vrev64q_u32(cmp); + return vreinterpretq_m128i_u32(vandq_u32(cmp, swapped)); #endif } -// Load a double-precision (64-bit) floating-point element from memory into the -// upper element of dst, and copy the lower element from a to dst. mem_addr does -// not need to be aligned on any particular boundary. -// -// dst[63:0] := a[63:0] -// dst[127:64] := MEM[mem_addr+63:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadh_pd -FORCE_INLINE __m128d _mm_loadh_pd(__m128d a, const double *p) +// Sign extend packed 16-bit integers in a to packed 32-bit integers, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi16_epi32 +FORCE_INLINE __m128i _mm_cvtepi16_epi32(__m128i a) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64( - vcombine_f64(vget_low_f64(vreinterpretq_f64_m128d(a)), vld1_f64(p))); -#else - return vreinterpretq_m128d_f32(vcombine_f32( - vget_low_f32(vreinterpretq_f32_m128d(a)), vld1_f32((const float *) p))); -#endif + return vreinterpretq_m128i_s32( + vmovl_s16(vget_low_s16(vreinterpretq_s16_m128i(a)))); } -// Load a double-precision (64-bit) floating-point element from memory into both -// elements of dst. -// -// dst[63:0] := MEM[mem_addr+63:mem_addr] -// dst[127:64] := MEM[mem_addr+63:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load_pd1 -#define _mm_load_pd1 _mm_load1_pd - -// Load a double-precision (64-bit) floating-point element from memory into both -// elements of dst. -// -// dst[63:0] := MEM[mem_addr+63:mem_addr] -// dst[127:64] := MEM[mem_addr+63:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loaddup_pd -#define _mm_loaddup_pd _mm_load1_pd +// Sign extend packed 16-bit integers in a to packed 64-bit integers, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi16_epi64 +FORCE_INLINE __m128i _mm_cvtepi16_epi64(__m128i a) +{ + int16x8_t s16x8 = vreinterpretq_s16_m128i(a); /* xxxx xxxx xxxx 0B0A */ + int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */ + int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */ + return vreinterpretq_m128i_s64(s64x2); +} -// Loads 128-bit value. : -// https://msdn.microsoft.com/zh-cn/library/f4k12ae8(v=vs.90).aspx -FORCE_INLINE __m128i _mm_loadu_si128(const __m128i *p) +// Sign extend packed 32-bit integers in a to packed 64-bit integers, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi32_epi64 +FORCE_INLINE __m128i _mm_cvtepi32_epi64(__m128i a) { - return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *) p)); + return vreinterpretq_m128i_s64( + vmovl_s32(vget_low_s32(vreinterpretq_s32_m128i(a)))); } -// Load unaligned 32-bit integer from memory into the first element of dst. -// -// dst[31:0] := MEM[mem_addr+31:mem_addr] -// dst[MAX:32] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadu_si32 -FORCE_INLINE __m128i _mm_loadu_si32(const void *p) +// Sign extend packed 8-bit integers in a to packed 16-bit integers, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi8_epi16 +FORCE_INLINE __m128i _mm_cvtepi8_epi16(__m128i a) { - return vreinterpretq_m128i_s32( - vsetq_lane_s32(*(const int32_t *) p, vdupq_n_s32(0), 0)); + int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */ + int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */ + return vreinterpretq_m128i_s16(s16x8); } -// Convert packed double-precision (64-bit) floating-point elements in a to -// packed single-precision (32-bit) floating-point elements, and store the -// results in dst. -// -// FOR j := 0 to 1 -// i := 32*j -// k := 64*j -// dst[i+31:i] := Convert_FP64_To_FP32(a[k+64:k]) -// ENDFOR -// dst[127:64] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtpd_ps -FORCE_INLINE __m128 _mm_cvtpd_ps(__m128d a) +// Sign extend packed 8-bit integers in a to packed 32-bit integers, and store +// the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi8_epi32 +FORCE_INLINE __m128i _mm_cvtepi8_epi32(__m128i a) { -#if defined(__aarch64__) - float32x2_t tmp = vcvt_f32_f64(vreinterpretq_f64_m128d(a)); - return vreinterpretq_m128_f32(vcombine_f32(tmp, vdup_n_f32(0))); -#else - float a0 = (float) ((double *) &a)[0]; - float a1 = (float) ((double *) &a)[1]; - return _mm_set_ps(0, 0, a1, a0); -#endif + int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx DCBA */ + int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0D0C 0B0A */ + int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000D 000C 000B 000A */ + return vreinterpretq_m128i_s32(s32x4); } -// Copy the lower double-precision (64-bit) floating-point element of a to dst. -// -// dst[63:0] := a[63:0] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtsd_f64 -FORCE_INLINE double _mm_cvtsd_f64(__m128d a) +// Sign extend packed 8-bit integers in the low 8 bytes of a to packed 64-bit +// integers, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepi8_epi64 +FORCE_INLINE __m128i _mm_cvtepi8_epi64(__m128i a) { -#if defined(__aarch64__) - return (double) vgetq_lane_f64(vreinterpretq_f64_m128d(a), 0); -#else - return ((double *) &a)[0]; -#endif + int8x16_t s8x16 = vreinterpretq_s8_m128i(a); /* xxxx xxxx xxxx xxBA */ + int16x8_t s16x8 = vmovl_s8(vget_low_s8(s8x16)); /* 0x0x 0x0x 0x0x 0B0A */ + int32x4_t s32x4 = vmovl_s16(vget_low_s16(s16x8)); /* 000x 000x 000B 000A */ + int64x2_t s64x2 = vmovl_s32(vget_low_s32(s32x4)); /* 0000 000B 0000 000A */ + return vreinterpretq_m128i_s64(s64x2); } -// Convert packed single-precision (32-bit) floating-point elements in a to -// packed double-precision (64-bit) floating-point elements, and store the -// results in dst. -// -// FOR j := 0 to 1 -// i := 64*j -// k := 32*j -// dst[i+63:i] := Convert_FP32_To_FP64(a[k+31:k]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvtps_pd -FORCE_INLINE __m128d _mm_cvtps_pd(__m128 a) +// Zero extend packed unsigned 16-bit integers in a to packed 32-bit integers, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepu16_epi32 +FORCE_INLINE __m128i _mm_cvtepu16_epi32(__m128i a) { -#if defined(__aarch64__) - return vreinterpretq_m128d_f64( - vcvt_f64_f32(vget_low_f32(vreinterpretq_f32_m128(a)))); -#else - double a0 = (double) vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); - double a1 = (double) vgetq_lane_f32(vreinterpretq_f32_m128(a), 1); - return _mm_set_pd(a1, a0); -#endif + return vreinterpretq_m128i_u32( + vmovl_u16(vget_low_u16(vreinterpretq_u16_m128i(a)))); } -// Cast vector of type __m128d to type __m128i. This intrinsic is only used for -// compilation and does not generate any instructions, thus it has zero latency. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_castpd_si128 -FORCE_INLINE __m128i _mm_castpd_si128(__m128d a) +// Zero extend packed unsigned 16-bit integers in a to packed 64-bit integers, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepu16_epi64 +FORCE_INLINE __m128i _mm_cvtepu16_epi64(__m128i a) { - return vreinterpretq_m128i_s64(vreinterpretq_s64_m128d(a)); + uint16x8_t u16x8 = vreinterpretq_u16_m128i(a); /* xxxx xxxx xxxx 0B0A */ + uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */ + uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */ + return vreinterpretq_m128i_u64(u64x2); } -// Cast vector of type __m128d to type __m128. This intrinsic is only used for -// compilation and does not generate any instructions, thus it has zero latency. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_castpd_ps -FORCE_INLINE __m128 _mm_castpd_ps(__m128d a) +// Zero extend packed unsigned 32-bit integers in a to packed 64-bit integers, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepu32_epi64 +FORCE_INLINE __m128i _mm_cvtepu32_epi64(__m128i a) { - return vreinterpretq_m128_s64(vreinterpretq_s64_m128d(a)); + return vreinterpretq_m128i_u64( + vmovl_u32(vget_low_u32(vreinterpretq_u32_m128i(a)))); } -// Blend packed single-precision (32-bit) floating-point elements from a and b -// using mask, and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_blendv_ps -FORCE_INLINE __m128 _mm_blendv_ps(__m128 a, __m128 b, __m128 mask) +// Zero extend packed unsigned 8-bit integers in a to packed 16-bit integers, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepu8_epi16 +FORCE_INLINE __m128i _mm_cvtepu8_epi16(__m128i a) { - return vreinterpretq_m128_f32(vbslq_f32(vreinterpretq_u32_m128(mask), - vreinterpretq_f32_m128(b), - vreinterpretq_f32_m128(a))); + uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx HGFE DCBA */ + uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0H0G 0F0E 0D0C 0B0A */ + return vreinterpretq_m128i_u16(u16x8); } -// Blend packed double-precision (64-bit) floating-point elements from a and b -// using mask, and store the results in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_blendv_pd -FORCE_INLINE __m128d _mm_blendv_pd(__m128d _a, __m128d _b, __m128d _mask) +// Zero extend packed unsigned 8-bit integers in a to packed 32-bit integers, +// and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepu8_epi32 +FORCE_INLINE __m128i _mm_cvtepu8_epi32(__m128i a) { - uint64x2_t mask = - vreinterpretq_u64_s64(vshrq_n_s64(vreinterpretq_s64_m128d(_mask), 63)); -#if defined(__aarch64__) - float64x2_t a = vreinterpretq_f64_m128d(_a); - float64x2_t b = vreinterpretq_f64_m128d(_b); - return vreinterpretq_m128d_f64(vbslq_f64(mask, b, a)); -#else - uint64x2_t a = vreinterpretq_u64_m128d(_a); - uint64x2_t b = vreinterpretq_u64_m128d(_b); - return vreinterpretq_m128d_u64(vbslq_u64(mask, b, a)); -#endif + uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx DCBA */ + uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */ + uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000D 000C 000B 000A */ + return vreinterpretq_m128i_u32(u32x4); } -// Round the packed single-precision (32-bit) floating-point elements in a using -// the rounding parameter, and store the results as packed single-precision -// floating-point elements in dst. -// software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_round_ps -FORCE_INLINE __m128 _mm_round_ps(__m128 a, int rounding) +// Zero extend packed unsigned 8-bit integers in the low 8 bytes of a to packed +// 64-bit integers, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cvtepu8_epi64 +FORCE_INLINE __m128i _mm_cvtepu8_epi64(__m128i a) { -#if defined(__aarch64__) - switch (rounding) { - case (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC): - return vreinterpretq_m128_f32(vrndnq_f32(vreinterpretq_f32_m128(a))); - case (_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC): - return vreinterpretq_m128_f32(vrndmq_f32(vreinterpretq_f32_m128(a))); - case (_MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC): - return vreinterpretq_m128_f32(vrndpq_f32(vreinterpretq_f32_m128(a))); - case (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC): - return vreinterpretq_m128_f32(vrndq_f32(vreinterpretq_f32_m128(a))); - default: //_MM_FROUND_CUR_DIRECTION - return vreinterpretq_m128_f32(vrndiq_f32(vreinterpretq_f32_m128(a))); - } -#else - float *v_float = (float *) &a; - __m128 zero, neg_inf, pos_inf; - - switch (rounding) { - case (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC): - return _mm_cvtepi32_ps(_mm_cvtps_epi32(a)); - case (_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC): - return (__m128){floorf(v_float[0]), floorf(v_float[1]), - floorf(v_float[2]), floorf(v_float[3])}; - case (_MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC): - return (__m128){ceilf(v_float[0]), ceilf(v_float[1]), ceilf(v_float[2]), - ceilf(v_float[3])}; - case (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC): - zero = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f); - neg_inf = _mm_set_ps(floorf(v_float[0]), floorf(v_float[1]), - floorf(v_float[2]), floorf(v_float[3])); - pos_inf = _mm_set_ps(ceilf(v_float[0]), ceilf(v_float[1]), - ceilf(v_float[2]), ceilf(v_float[3])); - return _mm_blendv_ps(pos_inf, neg_inf, _mm_cmple_ps(a, zero)); - default: //_MM_FROUND_CUR_DIRECTION - return (__m128){roundf(v_float[0]), roundf(v_float[1]), - roundf(v_float[2]), roundf(v_float[3])}; - } -#endif + uint8x16_t u8x16 = vreinterpretq_u8_m128i(a); /* xxxx xxxx xxxx xxBA */ + uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0x0x 0B0A */ + uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000x 000x 000B 000A */ + uint64x2_t u64x2 = vmovl_u32(vget_low_u32(u32x4)); /* 0000 000B 0000 000A */ + return vreinterpretq_m128i_u64(u64x2); } -// Convert packed single-precision (32-bit) floating-point elements in a to -// packed 32-bit integers, and store the results in dst. -// -// FOR j := 0 to 1 -// i := 32*j -// dst[i+31:i] := Convert_FP32_To_Int32(a[i+31:i]) -// ENDFOR -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cvt_ps2pi -FORCE_INLINE __m64 _mm_cvt_ps2pi(__m128 a) +// Conditionally multiply the packed double-precision (64-bit) floating-point +// elements in a and b using the high 4 bits in imm8, sum the four products, and +// conditionally store the sum in dst using the low 4 bits of imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_dp_pd +FORCE_INLINE __m128d _mm_dp_pd(__m128d a, __m128d b, const int imm) { -#if defined(__aarch64__) - return vreinterpret_m64_s32( - vget_low_s32(vcvtnq_s32_f32(vreinterpretq_f32_m128(a)))); + // Generate mask value from constant immediate bit value + const int64_t bit0Mask = imm & 0x01 ? UINT64_MAX : 0; + const int64_t bit1Mask = imm & 0x02 ? UINT64_MAX : 0; +#if !SSE2NEON_PRECISE_DP + const int64_t bit4Mask = imm & 0x10 ? UINT64_MAX : 0; + const int64_t bit5Mask = imm & 0x20 ? UINT64_MAX : 0; +#endif + // Conditional multiplication +#if !SSE2NEON_PRECISE_DP + __m128d mul = _mm_mul_pd(a, b); + const __m128d mulMask = + _mm_castsi128_pd(_mm_set_epi64x(bit5Mask, bit4Mask)); + __m128d tmp = _mm_and_pd(mul, mulMask); #else - return vreinterpret_m64_s32( - vcvt_s32_f32(vget_low_f32(vreinterpretq_f32_m128( - _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC))))); +#if defined(__aarch64__) || defined(_M_ARM64) + double d0 = (imm & 0x10) ? vgetq_lane_f64(vreinterpretq_f64_m128d(a), 0) * + vgetq_lane_f64(vreinterpretq_f64_m128d(b), 0) + : 0; + double d1 = (imm & 0x20) ? vgetq_lane_f64(vreinterpretq_f64_m128d(a), 1) * + vgetq_lane_f64(vreinterpretq_f64_m128d(b), 1) + : 0; +#else + double d0 = (imm & 0x10) ? ((double *) &a)[0] * ((double *) &b)[0] : 0; + double d1 = (imm & 0x20) ? ((double *) &a)[1] * ((double *) &b)[1] : 0; +#endif + __m128d tmp = _mm_set_pd(d1, d0); +#endif + // Sum the products +#if defined(__aarch64__) || defined(_M_ARM64) + double sum = vpaddd_f64(vreinterpretq_f64_m128d(tmp)); +#else + double sum = *((double *) &tmp) + *(((double *) &tmp) + 1); #endif + // Conditionally store the sum + const __m128d sumMask = + _mm_castsi128_pd(_mm_set_epi64x(bit1Mask, bit0Mask)); + __m128d res = _mm_and_pd(_mm_set_pd1(sum), sumMask); + return res; } -// Round the packed single-precision (32-bit) floating-point elements in a up to -// an integer value, and store the results as packed single-precision -// floating-point elements in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_ceil_ps -FORCE_INLINE __m128 _mm_ceil_ps(__m128 a) +// Conditionally multiply the packed single-precision (32-bit) floating-point +// elements in a and b using the high 4 bits in imm8, sum the four products, +// and conditionally store the sum in dst using the low 4 bits of imm. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_dp_ps +FORCE_INLINE __m128 _mm_dp_ps(__m128 a, __m128 b, const int imm) { - return _mm_round_ps(a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC); -} + float32x4_t elementwise_prod = _mm_mul_ps(a, b); -// Round the packed single-precision (32-bit) floating-point elements in a down -// to an integer value, and store the results as packed single-precision -// floating-point elements in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_floor_ps -FORCE_INLINE __m128 _mm_floor_ps(__m128 a) -{ - return _mm_round_ps(a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC); -} +#if defined(__aarch64__) || defined(_M_ARM64) + /* shortcuts */ + if (imm == 0xFF) { + return _mm_set1_ps(vaddvq_f32(elementwise_prod)); + } + if ((imm & 0x0F) == 0x0F) { + if (!(imm & (1 << 4))) + elementwise_prod = vsetq_lane_f32(0.0f, elementwise_prod, 0); + if (!(imm & (1 << 5))) + elementwise_prod = vsetq_lane_f32(0.0f, elementwise_prod, 1); + if (!(imm & (1 << 6))) + elementwise_prod = vsetq_lane_f32(0.0f, elementwise_prod, 2); + if (!(imm & (1 << 7))) + elementwise_prod = vsetq_lane_f32(0.0f, elementwise_prod, 3); + + return _mm_set1_ps(vaddvq_f32(elementwise_prod)); + } +#endif -// Load 128-bits of integer data from unaligned memory into dst. This intrinsic -// may perform better than _mm_loadu_si128 when the data crosses a cache line -// boundary. -// -// dst[127:0] := MEM[mem_addr+127:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_lddqu_si128 -#define _mm_lddqu_si128 _mm_loadu_si128 + float s = 0.0f; -/* Miscellaneous Operations */ + if (imm & (1 << 4)) + s += vgetq_lane_f32(elementwise_prod, 0); + if (imm & (1 << 5)) + s += vgetq_lane_f32(elementwise_prod, 1); + if (imm & (1 << 6)) + s += vgetq_lane_f32(elementwise_prod, 2); + if (imm & (1 << 7)) + s += vgetq_lane_f32(elementwise_prod, 3); -// Shifts the 8 signed 16-bit integers in a right by count bits while shifting -// in the sign bit. -// -// r0 := a0 >> count -// r1 := a1 >> count -// ... -// r7 := a7 >> count -// -// https://msdn.microsoft.com/en-us/library/3c9997dk(v%3dvs.90).aspx -FORCE_INLINE __m128i _mm_sra_epi16(__m128i a, __m128i count) -{ - int64_t c = (int64_t) vget_low_s64((int64x2_t) count); - if (c > 15) - return _mm_cmplt_epi16(a, _mm_setzero_si128()); - return vreinterpretq_m128i_s16(vshlq_s16((int16x8_t) a, vdupq_n_s16(-c))); + const float32_t res[4] = { + (imm & 0x1) ? s : 0.0f, + (imm & 0x2) ? s : 0.0f, + (imm & 0x4) ? s : 0.0f, + (imm & 0x8) ? s : 0.0f, + }; + return vreinterpretq_m128_f32(vld1q_f32(res)); } -// Shifts the 4 signed 32-bit integers in a right by count bits while shifting -// in the sign bit. -// -// r0 := a0 >> count -// r1 := a1 >> count -// r2 := a2 >> count -// r3 := a3 >> count -// -// https://msdn.microsoft.com/en-us/library/ce40009e(v%3dvs.100).aspx -FORCE_INLINE __m128i _mm_sra_epi32(__m128i a, __m128i count) -{ - int64_t c = (int64_t) vget_low_s64((int64x2_t) count); - if (c > 31) - return _mm_cmplt_epi32(a, _mm_setzero_si128()); - return vreinterpretq_m128i_s32(vshlq_s32((int32x4_t) a, vdupq_n_s32(-c))); -} +// Extract a 32-bit integer from a, selected with imm8, and store the result in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_extract_epi32 +// FORCE_INLINE int _mm_extract_epi32(__m128i a, __constrange(0,4) int imm) +#define _mm_extract_epi32(a, imm) \ + vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)) -// Packs the 16 signed 16-bit integers from a and b into 8-bit integers and -// saturates. -// https://msdn.microsoft.com/en-us/library/k4y4f7w5%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_packs_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s8( - vcombine_s8(vqmovn_s16(vreinterpretq_s16_m128i(a)), - vqmovn_s16(vreinterpretq_s16_m128i(b)))); -} +// Extract a 64-bit integer from a, selected with imm8, and store the result in +// dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_extract_epi64 +// FORCE_INLINE __int64 _mm_extract_epi64(__m128i a, __constrange(0,2) int imm) +#define _mm_extract_epi64(a, imm) \ + vgetq_lane_s64(vreinterpretq_s64_m128i(a), (imm)) -// Packs the 16 signed 16 - bit integers from a and b into 8 - bit unsigned -// integers and saturates. -// -// r0 := UnsignedSaturate(a0) -// r1 := UnsignedSaturate(a1) -// ... -// r7 := UnsignedSaturate(a7) -// r8 := UnsignedSaturate(b0) -// r9 := UnsignedSaturate(b1) -// ... -// r15 := UnsignedSaturate(b7) -// -// https://msdn.microsoft.com/en-us/library/07ad1wx4(v=vs.100).aspx -FORCE_INLINE __m128i _mm_packus_epi16(const __m128i a, const __m128i b) -{ - return vreinterpretq_m128i_u8( - vcombine_u8(vqmovun_s16(vreinterpretq_s16_m128i(a)), - vqmovun_s16(vreinterpretq_s16_m128i(b)))); -} +// Extract an 8-bit integer from a, selected with imm8, and store the result in +// the lower element of dst. FORCE_INLINE int _mm_extract_epi8(__m128i a, +// __constrange(0,16) int imm) +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_extract_epi8 +#define _mm_extract_epi8(a, imm) vgetq_lane_u8(vreinterpretq_u8_m128i(a), (imm)) -// Packs the 8 signed 32-bit integers from a and b into signed 16-bit integers -// and saturates. -// -// r0 := SignedSaturate(a0) -// r1 := SignedSaturate(a1) -// r2 := SignedSaturate(a2) -// r3 := SignedSaturate(a3) -// r4 := SignedSaturate(b0) -// r5 := SignedSaturate(b1) -// r6 := SignedSaturate(b2) -// r7 := SignedSaturate(b3) -// -// https://msdn.microsoft.com/en-us/library/393t56f9%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_packs_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16( - vcombine_s16(vqmovn_s32(vreinterpretq_s32_m128i(a)), - vqmovn_s32(vreinterpretq_s32_m128i(b)))); -} +// Extracts the selected single-precision (32-bit) floating-point from a. +// FORCE_INLINE int _mm_extract_ps(__m128 a, __constrange(0,4) int imm) +#define _mm_extract_ps(a, imm) vgetq_lane_s32(vreinterpretq_s32_m128(a), (imm)) -// Packs the 8 unsigned 32-bit integers from a and b into unsigned 16-bit -// integers and saturates. -// -// r0 := UnsignedSaturate(a0) -// r1 := UnsignedSaturate(a1) -// r2 := UnsignedSaturate(a2) -// r3 := UnsignedSaturate(a3) -// r4 := UnsignedSaturate(b0) -// r5 := UnsignedSaturate(b1) -// r6 := UnsignedSaturate(b2) -// r7 := UnsignedSaturate(b3) -FORCE_INLINE __m128i _mm_packus_epi32(__m128i a, __m128i b) +// Round the packed double-precision (64-bit) floating-point elements in a down +// to an integer value, and store the results as packed double-precision +// floating-point elements in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_floor_pd +FORCE_INLINE __m128d _mm_floor_pd(__m128d a) { - return vreinterpretq_m128i_u16( - vcombine_u16(vqmovun_s32(vreinterpretq_s32_m128i(a)), - vqmovun_s32(vreinterpretq_s32_m128i(b)))); +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128d_f64(vrndmq_f64(vreinterpretq_f64_m128d(a))); +#else + double *f = (double *) &a; + return _mm_set_pd(floor(f[1]), floor(f[0])); +#endif } -// Interleaves the lower 8 signed or unsigned 8-bit integers in a with the lower -// 8 signed or unsigned 8-bit integers in b. -// -// r0 := a0 -// r1 := b0 -// r2 := a1 -// r3 := b1 -// ... -// r14 := a7 -// r15 := b7 -// -// https://msdn.microsoft.com/en-us/library/xf7k860c%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_unpacklo_epi8(__m128i a, __m128i b) +// Round the packed single-precision (32-bit) floating-point elements in a down +// to an integer value, and store the results as packed single-precision +// floating-point elements in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_floor_ps +FORCE_INLINE __m128 _mm_floor_ps(__m128 a) { -#if defined(__aarch64__) - return vreinterpretq_m128i_s8( - vzip1q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); +#if (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_DIRECTED_ROUNDING) + return vreinterpretq_m128_f32(vrndmq_f32(vreinterpretq_f32_m128(a))); #else - int8x8_t a1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(a))); - int8x8_t b1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(b))); - int8x8x2_t result = vzip_s8(a1, b1); - return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); + float *f = (float *) &a; + return _mm_set_ps(floorf(f[3]), floorf(f[2]), floorf(f[1]), floorf(f[0])); #endif } -// Interleaves the lower 4 signed or unsigned 16-bit integers in a with the -// lower 4 signed or unsigned 16-bit integers in b. -// -// r0 := a0 -// r1 := b0 -// r2 := a1 -// r3 := b1 -// r4 := a2 -// r5 := b2 -// r6 := a3 -// r7 := b3 -// -// https://msdn.microsoft.com/en-us/library/btxb17bw%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_unpacklo_epi16(__m128i a, __m128i b) +// Round the lower double-precision (64-bit) floating-point element in b down to +// an integer value, store the result as a double-precision floating-point +// element in the lower element of dst, and copy the upper element from a to the +// upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_floor_sd +FORCE_INLINE __m128d _mm_floor_sd(__m128d a, __m128d b) { -#if defined(__aarch64__) - return vreinterpretq_m128i_s16( - vzip1q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -#else - int16x4_t a1 = vget_low_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b1 = vget_low_s16(vreinterpretq_s16_m128i(b)); - int16x4x2_t result = vzip_s16(a1, b1); - return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); -#endif + return _mm_move_sd(a, _mm_floor_pd(b)); } -// Interleaves the lower 2 signed or unsigned 32 - bit integers in a with the -// lower 2 signed or unsigned 32 - bit integers in b. -// -// r0 := a0 -// r1 := b0 -// r2 := a1 -// r3 := b1 -// -// https://msdn.microsoft.com/en-us/library/x8atst9d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpacklo_epi32(__m128i a, __m128i b) +// Round the lower single-precision (32-bit) floating-point element in b down to +// an integer value, store the result as a single-precision floating-point +// element in the lower element of dst, and copy the upper 3 packed elements +// from a to the upper elements of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_floor_ss +FORCE_INLINE __m128 _mm_floor_ss(__m128 a, __m128 b) +{ + return _mm_move_ss(a, _mm_floor_ps(b)); +} + +// Copy a to dst, and insert the 32-bit integer i into dst at the location +// specified by imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_insert_epi32 +// FORCE_INLINE __m128i _mm_insert_epi32(__m128i a, int b, +// __constrange(0,4) int imm) +#define _mm_insert_epi32(a, b, imm) \ + vreinterpretq_m128i_s32( \ + vsetq_lane_s32((b), vreinterpretq_s32_m128i(a), (imm))) + +// Copy a to dst, and insert the 64-bit integer i into dst at the location +// specified by imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_insert_epi64 +// FORCE_INLINE __m128i _mm_insert_epi64(__m128i a, __int64 b, +// __constrange(0,2) int imm) +#define _mm_insert_epi64(a, b, imm) \ + vreinterpretq_m128i_s64( \ + vsetq_lane_s64((b), vreinterpretq_s64_m128i(a), (imm))) + +// Copy a to dst, and insert the lower 8-bit integer from i into dst at the +// location specified by imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_insert_epi8 +// FORCE_INLINE __m128i _mm_insert_epi8(__m128i a, int b, +// __constrange(0,16) int imm) +#define _mm_insert_epi8(a, b, imm) \ + vreinterpretq_m128i_s8(vsetq_lane_s8((b), vreinterpretq_s8_m128i(a), (imm))) + +// Copy a to tmp, then insert a single-precision (32-bit) floating-point +// element from b into tmp using the control in imm8. Store tmp to dst using +// the mask in imm8 (elements are zeroed out when the corresponding bit is set). +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=insert_ps +#define _mm_insert_ps(a, b, imm8) \ + _sse2neon_define2( \ + __m128, a, b, \ + float32x4_t tmp1 = \ + vsetq_lane_f32(vgetq_lane_f32(_b, (imm8 >> 6) & 0x3), \ + vreinterpretq_f32_m128(_a), 0); \ + float32x4_t tmp2 = \ + vsetq_lane_f32(vgetq_lane_f32(tmp1, 0), \ + vreinterpretq_f32_m128(_a), ((imm8 >> 4) & 0x3)); \ + const uint32_t data[4] = \ + _sse2neon_init(((imm8) & (1 << 0)) ? UINT32_MAX : 0, \ + ((imm8) & (1 << 1)) ? UINT32_MAX : 0, \ + ((imm8) & (1 << 2)) ? UINT32_MAX : 0, \ + ((imm8) & (1 << 3)) ? UINT32_MAX : 0); \ + uint32x4_t mask = vld1q_u32(data); \ + float32x4_t all_zeros = vdupq_n_f32(0); \ + \ + _sse2neon_return(vreinterpretq_m128_f32( \ + vbslq_f32(mask, all_zeros, vreinterpretq_f32_m128(tmp2))));) + +// Compare packed signed 32-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_epi32 +FORCE_INLINE __m128i _mm_max_epi32(__m128i a, __m128i b) { -#if defined(__aarch64__) return vreinterpretq_m128i_s32( - vzip1q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -#else - int32x2_t a1 = vget_low_s32(vreinterpretq_s32_m128i(a)); - int32x2_t b1 = vget_low_s32(vreinterpretq_s32_m128i(b)); - int32x2x2_t result = vzip_s32(a1, b1); - return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); -#endif + vmaxq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } -FORCE_INLINE __m128i _mm_unpacklo_epi64(__m128i a, __m128i b) +// Compare packed signed 8-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_epi8 +FORCE_INLINE __m128i _mm_max_epi8(__m128i a, __m128i b) { - int64x1_t a_l = vget_low_s64(vreinterpretq_s64_m128i(a)); - int64x1_t b_l = vget_low_s64(vreinterpretq_s64_m128i(b)); - return vreinterpretq_m128i_s64(vcombine_s64(a_l, b_l)); + return vreinterpretq_m128i_s8( + vmaxq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } -// Selects and interleaves the lower two single-precision, floating-point values -// from a and b. -// -// r0 := a0 -// r1 := b0 -// r2 := a1 -// r3 := b1 -// -// https://msdn.microsoft.com/en-us/library/25st103b%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_unpacklo_ps(__m128 a, __m128 b) +// Compare packed unsigned 16-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_epu16 +FORCE_INLINE __m128i _mm_max_epu16(__m128i a, __m128i b) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32( - vzip1q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -#else - float32x2_t a1 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b1 = vget_low_f32(vreinterpretq_f32_m128(b)); - float32x2x2_t result = vzip_f32(a1, b1); - return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); -#endif + return vreinterpretq_m128i_u16( + vmaxq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); } -// Selects and interleaves the upper two single-precision, floating-point values -// from a and b. -// -// r0 := a2 -// r1 := b2 -// r2 := a3 -// r3 := b3 -// -// https://msdn.microsoft.com/en-us/library/skccxx7d%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_unpackhi_ps(__m128 a, __m128 b) +// Compare packed unsigned 32-bit integers in a and b, and store packed maximum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_epu32 +FORCE_INLINE __m128i _mm_max_epu32(__m128i a, __m128i b) { -#if defined(__aarch64__) - return vreinterpretq_m128_f32( - vzip2q_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -#else - float32x2_t a1 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b1 = vget_high_f32(vreinterpretq_f32_m128(b)); - float32x2x2_t result = vzip_f32(a1, b1); - return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); -#endif + return vreinterpretq_m128i_u32( + vmaxq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b))); } -// Interleaves the upper 8 signed or unsigned 8-bit integers in a with the upper -// 8 signed or unsigned 8-bit integers in b. -// -// r0 := a8 -// r1 := b8 -// r2 := a9 -// r3 := b9 -// ... -// r14 := a15 -// r15 := b15 -// -// https://msdn.microsoft.com/en-us/library/t5h7783k(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi8(__m128i a, __m128i b) +// Compare packed signed 32-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_epi32 +FORCE_INLINE __m128i _mm_min_epi32(__m128i a, __m128i b) { -#if defined(__aarch64__) - return vreinterpretq_m128i_s8( - vzip2q_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); -#else - int8x8_t a1 = - vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(a))); - int8x8_t b1 = - vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(b))); - int8x8x2_t result = vzip_s8(a1, b1); - return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); -#endif + return vreinterpretq_m128i_s32( + vminq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); } -// Interleaves the upper 4 signed or unsigned 16-bit integers in a with the -// upper 4 signed or unsigned 16-bit integers in b. -// -// r0 := a4 -// r1 := b4 -// r2 := a5 -// r3 := b5 -// r4 := a6 -// r5 := b6 -// r6 := a7 -// r7 := b7 -// -// https://msdn.microsoft.com/en-us/library/03196cz7(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi16(__m128i a, __m128i b) +// Compare packed signed 8-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_epi8 +FORCE_INLINE __m128i _mm_min_epi8(__m128i a, __m128i b) { -#if defined(__aarch64__) - return vreinterpretq_m128i_s16( - vzip2q_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -#else - int16x4_t a1 = vget_high_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b1 = vget_high_s16(vreinterpretq_s16_m128i(b)); - int16x4x2_t result = vzip_s16(a1, b1); - return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); -#endif + return vreinterpretq_m128i_s8( + vminq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); } -// Interleaves the upper 2 signed or unsigned 32-bit integers in a with the -// upper 2 signed or unsigned 32-bit integers in b. -// https://msdn.microsoft.com/en-us/library/65sa7cbs(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi32(__m128i a, __m128i b) +// Compare packed unsigned 16-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_min_epu16 +FORCE_INLINE __m128i _mm_min_epu16(__m128i a, __m128i b) { -#if defined(__aarch64__) - return vreinterpretq_m128i_s32( - vzip2q_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -#else - int32x2_t a1 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t b1 = vget_high_s32(vreinterpretq_s32_m128i(b)); - int32x2x2_t result = vzip_s32(a1, b1); - return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); -#endif + return vreinterpretq_m128i_u16( + vminq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); } -// Interleaves the upper signed or unsigned 64-bit integer in a with the -// upper signed or unsigned 64-bit integer in b. -// -// r0 := a1 -// r1 := b1 -FORCE_INLINE __m128i _mm_unpackhi_epi64(__m128i a, __m128i b) +// Compare packed unsigned 32-bit integers in a and b, and store packed minimum +// values in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_max_epu32 +FORCE_INLINE __m128i _mm_min_epu32(__m128i a, __m128i b) { - int64x1_t a_h = vget_high_s64(vreinterpretq_s64_m128i(a)); - int64x1_t b_h = vget_high_s64(vreinterpretq_s64_m128i(b)); - return vreinterpretq_m128i_s64(vcombine_s64(a_h, b_h)); + return vreinterpretq_m128i_u32( + vminq_u32(vreinterpretq_u32_m128i(a), vreinterpretq_u32_m128i(b))); } // Horizontally compute the minimum amongst the packed unsigned 16-bit integers // in a, store the minimum and index in dst, and zero the remaining bits in dst. -// -// index[2:0] := 0 -// min[15:0] := a[15:0] -// FOR j := 0 to 7 -// i := j*16 -// IF a[i+15:i] < min[15:0] -// index[2:0] := j -// min[15:0] := a[i+15:i] -// FI -// ENDFOR -// dst[15:0] := min[15:0] -// dst[18:16] := index[2:0] -// dst[127:19] := 0 -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_minpos_epu16 +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_minpos_epu16 FORCE_INLINE __m128i _mm_minpos_epu16(__m128i a) { __m128i dst; uint16_t min, idx = 0; +#if defined(__aarch64__) || defined(_M_ARM64) // Find the minimum value -#if defined(__aarch64__) min = vminvq_u16(vreinterpretq_u16_m128i(a)); + + // Get the index of the minimum value + static const uint16_t idxv[] = {0, 1, 2, 3, 4, 5, 6, 7}; + uint16x8_t minv = vdupq_n_u16(min); + uint16x8_t cmeq = vceqq_u16(minv, vreinterpretq_u16_m128i(a)); + idx = vminvq_u16(vornq_u16(vld1q_u16(idxv), cmeq)); #else + // Find the minimum value __m64 tmp; tmp = vreinterpret_m64_u16( vmin_u16(vget_low_u16(vreinterpretq_u16_m128i(a)), @@ -5583,7 +7258,6 @@ FORCE_INLINE __m128i _mm_minpos_epu16(__m128i a) tmp = vreinterpret_m64_u16( vpmin_u16(vreinterpret_u16_m64(tmp), vreinterpret_u16_m64(tmp))); min = vget_lane_u16(vreinterpret_u16_m64(tmp), 0); -#endif // Get the index of the minimum value int i; for (i = 0; i < 8; i++) { @@ -5593,6 +7267,7 @@ FORCE_INLINE __m128i _mm_minpos_epu16(__m128i a) } a = _mm_srli_si128(a, 2); } +#endif // Generate result dst = _mm_setzero_si128(); dst = vreinterpretq_m128i_u16( @@ -5602,32 +7277,356 @@ FORCE_INLINE __m128i _mm_minpos_epu16(__m128i a) return dst; } -// shift to right -// https://msdn.microsoft.com/en-us/library/bb514041(v=vs.120).aspx -// http://blog.csdn.net/hemmingway/article/details/44828303 -// Clang requires a macro here, as it is extremely picky about c being a -// literal. -#define _mm_alignr_epi8(a, b, c) \ - ((__m128i) vextq_s8((int8x16_t)(b), (int8x16_t)(a), (c))) +// Compute the sum of absolute differences (SADs) of quadruplets of unsigned +// 8-bit integers in a compared to those in b, and store the 16-bit results in +// dst. Eight SADs are performed using one quadruplet from b and eight +// quadruplets from a. One quadruplet is selected from b starting at on the +// offset specified in imm8. Eight quadruplets are formed from sequential 8-bit +// integers selected from a starting at the offset specified in imm8. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mpsadbw_epu8 +FORCE_INLINE __m128i _mm_mpsadbw_epu8(__m128i a, __m128i b, const int imm) +{ + uint8x16_t _a, _b; + + switch (imm & 0x4) { + case 0: + // do nothing + _a = vreinterpretq_u8_m128i(a); + break; + case 4: + _a = vreinterpretq_u8_u32(vextq_u32(vreinterpretq_u32_m128i(a), + vreinterpretq_u32_m128i(a), 1)); + break; + default: +#if defined(__GNUC__) || defined(__clang__) + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(0); +#endif + break; + } + + switch (imm & 0x3) { + case 0: + _b = vreinterpretq_u8_u32( + vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_m128i(b), 0))); + break; + case 1: + _b = vreinterpretq_u8_u32( + vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_m128i(b), 1))); + break; + case 2: + _b = vreinterpretq_u8_u32( + vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_m128i(b), 2))); + break; + case 3: + _b = vreinterpretq_u8_u32( + vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_m128i(b), 3))); + break; + default: +#if defined(__GNUC__) || defined(__clang__) + __builtin_unreachable(); +#elif defined(_MSC_VER) + __assume(0); +#endif + break; + } + + int16x8_t c04, c15, c26, c37; + uint8x8_t low_b = vget_low_u8(_b); + c04 = vreinterpretq_s16_u16(vabdl_u8(vget_low_u8(_a), low_b)); + uint8x16_t _a_1 = vextq_u8(_a, _a, 1); + c15 = vreinterpretq_s16_u16(vabdl_u8(vget_low_u8(_a_1), low_b)); + uint8x16_t _a_2 = vextq_u8(_a, _a, 2); + c26 = vreinterpretq_s16_u16(vabdl_u8(vget_low_u8(_a_2), low_b)); + uint8x16_t _a_3 = vextq_u8(_a, _a, 3); + c37 = vreinterpretq_s16_u16(vabdl_u8(vget_low_u8(_a_3), low_b)); +#if defined(__aarch64__) || defined(_M_ARM64) + // |0|4|2|6| + c04 = vpaddq_s16(c04, c26); + // |1|5|3|7| + c15 = vpaddq_s16(c15, c37); + + int32x4_t trn1_c = + vtrn1q_s32(vreinterpretq_s32_s16(c04), vreinterpretq_s32_s16(c15)); + int32x4_t trn2_c = + vtrn2q_s32(vreinterpretq_s32_s16(c04), vreinterpretq_s32_s16(c15)); + return vreinterpretq_m128i_s16(vpaddq_s16(vreinterpretq_s16_s32(trn1_c), + vreinterpretq_s16_s32(trn2_c))); +#else + int16x4_t c01, c23, c45, c67; + c01 = vpadd_s16(vget_low_s16(c04), vget_low_s16(c15)); + c23 = vpadd_s16(vget_low_s16(c26), vget_low_s16(c37)); + c45 = vpadd_s16(vget_high_s16(c04), vget_high_s16(c15)); + c67 = vpadd_s16(vget_high_s16(c26), vget_high_s16(c37)); + + return vreinterpretq_m128i_s16( + vcombine_s16(vpadd_s16(c01, c23), vpadd_s16(c45, c67))); +#endif +} + +// Multiply the low signed 32-bit integers from each packed 64-bit element in +// a and b, and store the signed 64-bit results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mul_epi32 +FORCE_INLINE __m128i _mm_mul_epi32(__m128i a, __m128i b) +{ + // vmull_s32 upcasts instead of masking, so we downcast. + int32x2_t a_lo = vmovn_s64(vreinterpretq_s64_m128i(a)); + int32x2_t b_lo = vmovn_s64(vreinterpretq_s64_m128i(b)); + return vreinterpretq_m128i_s64(vmull_s32(a_lo, b_lo)); +} + +// Multiply the packed 32-bit integers in a and b, producing intermediate 64-bit +// integers, and store the low 32 bits of the intermediate integers in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_mullo_epi32 +FORCE_INLINE __m128i _mm_mullo_epi32(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_s32( + vmulq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); +} + +// Convert packed signed 32-bit integers from a and b to packed 16-bit integers +// using unsigned saturation, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packus_epi32 +FORCE_INLINE __m128i _mm_packus_epi32(__m128i a, __m128i b) +{ + return vreinterpretq_m128i_u16( + vcombine_u16(vqmovun_s32(vreinterpretq_s32_m128i(a)), + vqmovun_s32(vreinterpretq_s32_m128i(b)))); +} + +// Round the packed double-precision (64-bit) floating-point elements in a using +// the rounding parameter, and store the results as packed double-precision +// floating-point elements in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_round_pd +FORCE_INLINE __m128d _mm_round_pd(__m128d a, int rounding) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + switch (rounding) { + case (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC): + return vreinterpretq_m128d_f64(vrndnq_f64(vreinterpretq_f64_m128d(a))); + case (_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC): + return _mm_floor_pd(a); + case (_MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC): + return _mm_ceil_pd(a); + case (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC): + return vreinterpretq_m128d_f64(vrndq_f64(vreinterpretq_f64_m128d(a))); + default: //_MM_FROUND_CUR_DIRECTION + return vreinterpretq_m128d_f64(vrndiq_f64(vreinterpretq_f64_m128d(a))); + } +#else + double *v_double = (double *) &a; + + if (rounding == (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) || + (rounding == _MM_FROUND_CUR_DIRECTION && + _MM_GET_ROUNDING_MODE() == _MM_ROUND_NEAREST)) { + double res[2], tmp; + for (int i = 0; i < 2; i++) { + tmp = (v_double[i] < 0) ? -v_double[i] : v_double[i]; + double roundDown = floor(tmp); // Round down value + double roundUp = ceil(tmp); // Round up value + double diffDown = tmp - roundDown; + double diffUp = roundUp - tmp; + if (diffDown < diffUp) { + /* If it's closer to the round down value, then use it */ + res[i] = roundDown; + } else if (diffDown > diffUp) { + /* If it's closer to the round up value, then use it */ + res[i] = roundUp; + } else { + /* If it's equidistant between round up and round down value, + * pick the one which is an even number */ + double half = roundDown / 2; + if (half != floor(half)) { + /* If the round down value is odd, return the round up value + */ + res[i] = roundUp; + } else { + /* If the round up value is odd, return the round down value + */ + res[i] = roundDown; + } + } + res[i] = (v_double[i] < 0) ? -res[i] : res[i]; + } + return _mm_set_pd(res[1], res[0]); + } else if (rounding == (_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) || + (rounding == _MM_FROUND_CUR_DIRECTION && + _MM_GET_ROUNDING_MODE() == _MM_ROUND_DOWN)) { + return _mm_floor_pd(a); + } else if (rounding == (_MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) || + (rounding == _MM_FROUND_CUR_DIRECTION && + _MM_GET_ROUNDING_MODE() == _MM_ROUND_UP)) { + return _mm_ceil_pd(a); + } + return _mm_set_pd(v_double[1] > 0 ? floor(v_double[1]) : ceil(v_double[1]), + v_double[0] > 0 ? floor(v_double[0]) : ceil(v_double[0])); +#endif +} + +// Round the packed single-precision (32-bit) floating-point elements in a using +// the rounding parameter, and store the results as packed single-precision +// floating-point elements in dst. +// software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_round_ps +FORCE_INLINE __m128 _mm_round_ps(__m128 a, int rounding) +{ +#if (defined(__aarch64__) || defined(_M_ARM64)) || \ + defined(__ARM_FEATURE_DIRECTED_ROUNDING) + switch (rounding) { + case (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC): + return vreinterpretq_m128_f32(vrndnq_f32(vreinterpretq_f32_m128(a))); + case (_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC): + return _mm_floor_ps(a); + case (_MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC): + return _mm_ceil_ps(a); + case (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC): + return vreinterpretq_m128_f32(vrndq_f32(vreinterpretq_f32_m128(a))); + default: //_MM_FROUND_CUR_DIRECTION + return vreinterpretq_m128_f32(vrndiq_f32(vreinterpretq_f32_m128(a))); + } +#else + float *v_float = (float *) &a; + + if (rounding == (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) || + (rounding == _MM_FROUND_CUR_DIRECTION && + _MM_GET_ROUNDING_MODE() == _MM_ROUND_NEAREST)) { + uint32x4_t signmask = vdupq_n_u32(0x80000000); + float32x4_t half = vbslq_f32(signmask, vreinterpretq_f32_m128(a), + vdupq_n_f32(0.5f)); /* +/- 0.5 */ + int32x4_t r_normal = vcvtq_s32_f32(vaddq_f32( + vreinterpretq_f32_m128(a), half)); /* round to integer: [a + 0.5]*/ + int32x4_t r_trunc = vcvtq_s32_f32( + vreinterpretq_f32_m128(a)); /* truncate to integer: [a] */ + int32x4_t plusone = vreinterpretq_s32_u32(vshrq_n_u32( + vreinterpretq_u32_s32(vnegq_s32(r_trunc)), 31)); /* 1 or 0 */ + int32x4_t r_even = vbicq_s32(vaddq_s32(r_trunc, plusone), + vdupq_n_s32(1)); /* ([a] + {0,1}) & ~1 */ + float32x4_t delta = vsubq_f32( + vreinterpretq_f32_m128(a), + vcvtq_f32_s32(r_trunc)); /* compute delta: delta = (a - [a]) */ + uint32x4_t is_delta_half = + vceqq_f32(delta, half); /* delta == +/- 0.5 */ + return vreinterpretq_m128_f32( + vcvtq_f32_s32(vbslq_s32(is_delta_half, r_even, r_normal))); + } else if (rounding == (_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) || + (rounding == _MM_FROUND_CUR_DIRECTION && + _MM_GET_ROUNDING_MODE() == _MM_ROUND_DOWN)) { + return _mm_floor_ps(a); + } else if (rounding == (_MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) || + (rounding == _MM_FROUND_CUR_DIRECTION && + _MM_GET_ROUNDING_MODE() == _MM_ROUND_UP)) { + return _mm_ceil_ps(a); + } + return _mm_set_ps(v_float[3] > 0 ? floorf(v_float[3]) : ceilf(v_float[3]), + v_float[2] > 0 ? floorf(v_float[2]) : ceilf(v_float[2]), + v_float[1] > 0 ? floorf(v_float[1]) : ceilf(v_float[1]), + v_float[0] > 0 ? floorf(v_float[0]) : ceilf(v_float[0])); +#endif +} + +// Round the lower double-precision (64-bit) floating-point element in b using +// the rounding parameter, store the result as a double-precision floating-point +// element in the lower element of dst, and copy the upper element from a to the +// upper element of dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_round_sd +FORCE_INLINE __m128d _mm_round_sd(__m128d a, __m128d b, int rounding) +{ + return _mm_move_sd(a, _mm_round_pd(b, rounding)); +} + +// Round the lower single-precision (32-bit) floating-point element in b using +// the rounding parameter, store the result as a single-precision floating-point +// element in the lower element of dst, and copy the upper 3 packed elements +// from a to the upper elements of dst. Rounding is done according to the +// rounding[3:0] parameter, which can be one of: +// (_MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC) // round to nearest, and +// suppress exceptions +// (_MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC) // round down, and +// suppress exceptions +// (_MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC) // round up, and suppress +// exceptions +// (_MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC) // truncate, and suppress +// exceptions _MM_FROUND_CUR_DIRECTION // use MXCSR.RC; see +// _MM_SET_ROUNDING_MODE +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_round_ss +FORCE_INLINE __m128 _mm_round_ss(__m128 a, __m128 b, int rounding) +{ + return _mm_move_ss(a, _mm_round_ps(b, rounding)); +} + +// Load 128-bits of integer data from memory into dst using a non-temporal +// memory hint. mem_addr must be aligned on a 16-byte boundary or a +// general-protection exception may be generated. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_stream_load_si128 +FORCE_INLINE __m128i _mm_stream_load_si128(__m128i *p) +{ +#if __has_builtin(__builtin_nontemporal_store) + return __builtin_nontemporal_load(p); +#else + return vreinterpretq_m128i_s64(vld1q_s64((int64_t *) p)); +#endif +} + +// Compute the bitwise NOT of a and then AND with a 128-bit vector containing +// all 1's, and return 1 if the result is zero, otherwise return 0. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_test_all_ones +FORCE_INLINE int _mm_test_all_ones(__m128i a) +{ + return (uint64_t) (vgetq_lane_s64(a, 0) & vgetq_lane_s64(a, 1)) == + ~(uint64_t) 0; +} + +// Compute the bitwise AND of 128 bits (representing integer data) in a and +// mask, and return 1 if the result is zero, otherwise return 0. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_test_all_zeros +FORCE_INLINE int _mm_test_all_zeros(__m128i a, __m128i mask) +{ + int64x2_t a_and_mask = + vandq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(mask)); + return !(vgetq_lane_s64(a_and_mask, 0) | vgetq_lane_s64(a_and_mask, 1)); +} + +// Compute the bitwise AND of 128 bits (representing integer data) in a and +// mask, and set ZF to 1 if the result is zero, otherwise set ZF to 0. Compute +// the bitwise NOT of a and then AND with mask, and set CF to 1 if the result is +// zero, otherwise set CF to 0. Return 1 if both the ZF and CF values are zero, +// otherwise return 0. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=mm_test_mix_ones_zero +FORCE_INLINE int _mm_test_mix_ones_zeros(__m128i a, __m128i mask) +{ + uint64x2_t zf = + vandq_u64(vreinterpretq_u64_m128i(mask), vreinterpretq_u64_m128i(a)); + uint64x2_t cf = + vbicq_u64(vreinterpretq_u64_m128i(mask), vreinterpretq_u64_m128i(a)); + uint64x2_t result = vandq_u64(zf, cf); + return !(vgetq_lane_u64(result, 0) | vgetq_lane_u64(result, 1)); +} // Compute the bitwise AND of 128 bits (representing integer data) in a and b, // and set ZF to 1 if the result is zero, otherwise set ZF to 0. Compute the // bitwise NOT of a and then AND with b, and set CF to 1 if the result is zero, // otherwise set CF to 0. Return the CF value. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_testc_si128 +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_testc_si128 FORCE_INLINE int _mm_testc_si128(__m128i a, __m128i b) { int64x2_t s64 = - vandq_s64(vreinterpretq_s64_s32(vmvnq_s32(vreinterpretq_s32_m128i(a))), - vreinterpretq_s64_m128i(b)); + vbicq_s64(vreinterpretq_s64_m128i(b), vreinterpretq_s64_m128i(a)); return !(vgetq_lane_s64(s64, 0) | vgetq_lane_s64(s64, 1)); } +// Compute the bitwise AND of 128 bits (representing integer data) in a and b, +// and set ZF to 1 if the result is zero, otherwise set ZF to 0. Compute the +// bitwise NOT of a and then AND with b, and set CF to 1 if the result is zero, +// otherwise set CF to 0. Return 1 if both the ZF and CF values are zero, +// otherwise return 0. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_testnzc_si128 +#define _mm_testnzc_si128(a, b) _mm_test_mix_ones_zeros(a, b) + // Compute the bitwise AND of 128 bits (representing integer data) in a and b, // and set ZF to 1 if the result is zero, otherwise set ZF to 0. Compute the // bitwise NOT of a and then AND with b, and set CF to 1 if the result is zero, // otherwise set CF to 0. Return the ZF value. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_testz_si128 +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_testz_si128 FORCE_INLINE int _mm_testz_si128(__m128i a, __m128i b) { int64x2_t s64 = @@ -5635,299 +7634,864 @@ FORCE_INLINE int _mm_testz_si128(__m128i a, __m128i b) return !(vgetq_lane_s64(s64, 0) | vgetq_lane_s64(s64, 1)); } -// Extracts the selected signed or unsigned 8-bit integer from a and zero -// extends. -// FORCE_INLINE int _mm_extract_epi8(__m128i a, __constrange(0,16) int imm) -#define _mm_extract_epi8(a, imm) vgetq_lane_u8(vreinterpretq_u8_m128i(a), (imm)) +/* SSE4.2 */ -// Inserts the least significant 8 bits of b into the selected 8-bit integer -// of a. -// FORCE_INLINE __m128i _mm_insert_epi8(__m128i a, int b, -// __constrange(0,16) int imm) -#define _mm_insert_epi8(a, b, imm) \ - __extension__({ \ - vreinterpretq_m128i_s8( \ - vsetq_lane_s8((b), vreinterpretq_s8_m128i(a), (imm))); \ - }) +static const uint16_t ALIGN_STRUCT(16) _sse2neon_cmpestr_mask16b[8] = { + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, +}; +static const uint8_t ALIGN_STRUCT(16) _sse2neon_cmpestr_mask8b[16] = { + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, +}; -// Extracts the selected signed or unsigned 16-bit integer from a and zero -// extends. -// https://msdn.microsoft.com/en-us/library/6dceta0c(v=vs.100).aspx -// FORCE_INLINE int _mm_extract_epi16(__m128i a, __constrange(0,8) int imm) -#define _mm_extract_epi16(a, imm) \ - vgetq_lane_u16(vreinterpretq_u16_m128i(a), (imm)) +/* specify the source data format */ +#define _SIDD_UBYTE_OPS 0x00 /* unsigned 8-bit characters */ +#define _SIDD_UWORD_OPS 0x01 /* unsigned 16-bit characters */ +#define _SIDD_SBYTE_OPS 0x02 /* signed 8-bit characters */ +#define _SIDD_SWORD_OPS 0x03 /* signed 16-bit characters */ + +/* specify the comparison operation */ +#define _SIDD_CMP_EQUAL_ANY 0x00 /* compare equal any: strchr */ +#define _SIDD_CMP_RANGES 0x04 /* compare ranges */ +#define _SIDD_CMP_EQUAL_EACH 0x08 /* compare equal each: strcmp */ +#define _SIDD_CMP_EQUAL_ORDERED 0x0C /* compare equal ordered */ + +/* specify the polarity */ +#define _SIDD_POSITIVE_POLARITY 0x00 +#define _SIDD_MASKED_POSITIVE_POLARITY 0x20 +#define _SIDD_NEGATIVE_POLARITY 0x10 /* negate results */ +#define _SIDD_MASKED_NEGATIVE_POLARITY \ + 0x30 /* negate results only before end of string */ + +/* specify the output selection in _mm_cmpXstri */ +#define _SIDD_LEAST_SIGNIFICANT 0x00 +#define _SIDD_MOST_SIGNIFICANT 0x40 + +/* specify the output selection in _mm_cmpXstrm */ +#define _SIDD_BIT_MASK 0x00 +#define _SIDD_UNIT_MASK 0x40 + +/* Pattern Matching for C macros. + * https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms + */ -// Inserts the least significant 16 bits of b into the selected 16-bit integer -// of a. -// https://msdn.microsoft.com/en-us/library/kaze8hz1%28v=vs.100%29.aspx -// FORCE_INLINE __m128i _mm_insert_epi16(__m128i a, int b, -// __constrange(0,8) int imm) -#define _mm_insert_epi16(a, b, imm) \ - __extension__({ \ - vreinterpretq_m128i_s16( \ - vsetq_lane_s16((b), vreinterpretq_s16_m128i(a), (imm))); \ - }) +/* catenate */ +#define SSE2NEON_PRIMITIVE_CAT(a, ...) a##__VA_ARGS__ +#define SSE2NEON_CAT(a, b) SSE2NEON_PRIMITIVE_CAT(a, b) + +#define SSE2NEON_IIF(c) SSE2NEON_PRIMITIVE_CAT(SSE2NEON_IIF_, c) +/* run the 2nd parameter */ +#define SSE2NEON_IIF_0(t, ...) __VA_ARGS__ +/* run the 1st parameter */ +#define SSE2NEON_IIF_1(t, ...) t + +#define SSE2NEON_COMPL(b) SSE2NEON_PRIMITIVE_CAT(SSE2NEON_COMPL_, b) +#define SSE2NEON_COMPL_0 1 +#define SSE2NEON_COMPL_1 0 + +#define SSE2NEON_DEC(x) SSE2NEON_PRIMITIVE_CAT(SSE2NEON_DEC_, x) +#define SSE2NEON_DEC_1 0 +#define SSE2NEON_DEC_2 1 +#define SSE2NEON_DEC_3 2 +#define SSE2NEON_DEC_4 3 +#define SSE2NEON_DEC_5 4 +#define SSE2NEON_DEC_6 5 +#define SSE2NEON_DEC_7 6 +#define SSE2NEON_DEC_8 7 +#define SSE2NEON_DEC_9 8 +#define SSE2NEON_DEC_10 9 +#define SSE2NEON_DEC_11 10 +#define SSE2NEON_DEC_12 11 +#define SSE2NEON_DEC_13 12 +#define SSE2NEON_DEC_14 13 +#define SSE2NEON_DEC_15 14 +#define SSE2NEON_DEC_16 15 + +/* detection */ +#define SSE2NEON_CHECK_N(x, n, ...) n +#define SSE2NEON_CHECK(...) SSE2NEON_CHECK_N(__VA_ARGS__, 0, ) +#define SSE2NEON_PROBE(x) x, 1, + +#define SSE2NEON_NOT(x) SSE2NEON_CHECK(SSE2NEON_PRIMITIVE_CAT(SSE2NEON_NOT_, x)) +#define SSE2NEON_NOT_0 SSE2NEON_PROBE(~) + +#define SSE2NEON_BOOL(x) SSE2NEON_COMPL(SSE2NEON_NOT(x)) +#define SSE2NEON_IF(c) SSE2NEON_IIF(SSE2NEON_BOOL(c)) + +#define SSE2NEON_EAT(...) +#define SSE2NEON_EXPAND(...) __VA_ARGS__ +#define SSE2NEON_WHEN(c) SSE2NEON_IF(c)(SSE2NEON_EXPAND, SSE2NEON_EAT) + +/* recursion */ +/* deferred expression */ +#define SSE2NEON_EMPTY() +#define SSE2NEON_DEFER(id) id SSE2NEON_EMPTY() +#define SSE2NEON_OBSTRUCT(...) __VA_ARGS__ SSE2NEON_DEFER(SSE2NEON_EMPTY)() +#define SSE2NEON_EXPAND(...) __VA_ARGS__ + +#define SSE2NEON_EVAL(...) \ + SSE2NEON_EVAL1(SSE2NEON_EVAL1(SSE2NEON_EVAL1(__VA_ARGS__))) +#define SSE2NEON_EVAL1(...) \ + SSE2NEON_EVAL2(SSE2NEON_EVAL2(SSE2NEON_EVAL2(__VA_ARGS__))) +#define SSE2NEON_EVAL2(...) \ + SSE2NEON_EVAL3(SSE2NEON_EVAL3(SSE2NEON_EVAL3(__VA_ARGS__))) +#define SSE2NEON_EVAL3(...) __VA_ARGS__ + +#define SSE2NEON_REPEAT(count, macro, ...) \ + SSE2NEON_WHEN(count) \ + (SSE2NEON_OBSTRUCT(SSE2NEON_REPEAT_INDIRECT)()( \ + SSE2NEON_DEC(count), macro, \ + __VA_ARGS__) SSE2NEON_OBSTRUCT(macro)(SSE2NEON_DEC(count), \ + __VA_ARGS__)) +#define SSE2NEON_REPEAT_INDIRECT() SSE2NEON_REPEAT + +#define SSE2NEON_SIZE_OF_byte 8 +#define SSE2NEON_NUMBER_OF_LANES_byte 16 +#define SSE2NEON_SIZE_OF_word 16 +#define SSE2NEON_NUMBER_OF_LANES_word 8 + +#define SSE2NEON_COMPARE_EQUAL_THEN_FILL_LANE(i, type) \ + mtx[i] = vreinterpretq_m128i_##type(vceqq_##type( \ + vdupq_n_##type(vgetq_lane_##type(vreinterpretq_##type##_m128i(b), i)), \ + vreinterpretq_##type##_m128i(a))); + +#define SSE2NEON_FILL_LANE(i, type) \ + vec_b[i] = \ + vdupq_n_##type(vgetq_lane_##type(vreinterpretq_##type##_m128i(b), i)); + +#define PCMPSTR_RANGES(a, b, mtx, data_type_prefix, type_prefix, size, \ + number_of_lanes, byte_or_word) \ + do { \ + SSE2NEON_CAT( \ + data_type_prefix, \ + SSE2NEON_CAT(size, \ + SSE2NEON_CAT(x, SSE2NEON_CAT(number_of_lanes, _t)))) \ + vec_b[number_of_lanes]; \ + __m128i mask = SSE2NEON_IIF(byte_or_word)( \ + vreinterpretq_m128i_u16(vdupq_n_u16(0xff)), \ + vreinterpretq_m128i_u32(vdupq_n_u32(0xffff))); \ + SSE2NEON_EVAL(SSE2NEON_REPEAT(number_of_lanes, SSE2NEON_FILL_LANE, \ + SSE2NEON_CAT(type_prefix, size))) \ + for (int i = 0; i < number_of_lanes; i++) { \ + mtx[i] = SSE2NEON_CAT(vreinterpretq_m128i_u, \ + size)(SSE2NEON_CAT(vbslq_u, size)( \ + SSE2NEON_CAT(vreinterpretq_u, \ + SSE2NEON_CAT(size, _m128i))(mask), \ + SSE2NEON_CAT(vcgeq_, SSE2NEON_CAT(type_prefix, size))( \ + vec_b[i], \ + SSE2NEON_CAT( \ + vreinterpretq_, \ + SSE2NEON_CAT(type_prefix, \ + SSE2NEON_CAT(size, _m128i(a))))), \ + SSE2NEON_CAT(vcleq_, SSE2NEON_CAT(type_prefix, size))( \ + vec_b[i], \ + SSE2NEON_CAT( \ + vreinterpretq_, \ + SSE2NEON_CAT(type_prefix, \ + SSE2NEON_CAT(size, _m128i(a))))))); \ + } \ + } while (0) -// Copy a to dst, and insert the 16-bit integer i into dst at the location -// specified by imm8. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_insert_pi16 -#define _mm_insert_pi16(a, b, imm) \ - __extension__({ \ - vreinterpret_m64_s16( \ - vset_lane_s16((b), vreinterpret_s16_m64(a), (imm))); \ - }) +#define PCMPSTR_EQ(a, b, mtx, size, number_of_lanes) \ + do { \ + SSE2NEON_EVAL(SSE2NEON_REPEAT(number_of_lanes, \ + SSE2NEON_COMPARE_EQUAL_THEN_FILL_LANE, \ + SSE2NEON_CAT(u, size))) \ + } while (0) -// Extracts the selected signed or unsigned 32-bit integer from a and zero -// extends. -// FORCE_INLINE int _mm_extract_epi32(__m128i a, __constrange(0,4) int imm) -#define _mm_extract_epi32(a, imm) \ - vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)) +#define SSE2NEON_CMP_EQUAL_ANY_IMPL(type) \ + static int _sse2neon_cmp_##type##_equal_any(__m128i a, int la, __m128i b, \ + int lb) \ + { \ + __m128i mtx[16]; \ + PCMPSTR_EQ(a, b, mtx, SSE2NEON_CAT(SSE2NEON_SIZE_OF_, type), \ + SSE2NEON_CAT(SSE2NEON_NUMBER_OF_LANES_, type)); \ + return SSE2NEON_CAT( \ + _sse2neon_aggregate_equal_any_, \ + SSE2NEON_CAT( \ + SSE2NEON_CAT(SSE2NEON_SIZE_OF_, type), \ + SSE2NEON_CAT(x, SSE2NEON_CAT(SSE2NEON_NUMBER_OF_LANES_, \ + type))))(la, lb, mtx); \ + } -// Extracts the selected single-precision (32-bit) floating-point from a. -// FORCE_INLINE int _mm_extract_ps(__m128 a, __constrange(0,4) int imm) -#define _mm_extract_ps(a, imm) vgetq_lane_s32(vreinterpretq_s32_m128(a), (imm)) +#define SSE2NEON_CMP_RANGES_IMPL(type, data_type, us, byte_or_word) \ + static int _sse2neon_cmp_##us##type##_ranges(__m128i a, int la, __m128i b, \ + int lb) \ + { \ + __m128i mtx[16]; \ + PCMPSTR_RANGES( \ + a, b, mtx, data_type, us, SSE2NEON_CAT(SSE2NEON_SIZE_OF_, type), \ + SSE2NEON_CAT(SSE2NEON_NUMBER_OF_LANES_, type), byte_or_word); \ + return SSE2NEON_CAT( \ + _sse2neon_aggregate_ranges_, \ + SSE2NEON_CAT( \ + SSE2NEON_CAT(SSE2NEON_SIZE_OF_, type), \ + SSE2NEON_CAT(x, SSE2NEON_CAT(SSE2NEON_NUMBER_OF_LANES_, \ + type))))(la, lb, mtx); \ + } -// Inserts the least significant 32 bits of b into the selected 32-bit integer -// of a. -// FORCE_INLINE __m128i _mm_insert_epi32(__m128i a, int b, -// __constrange(0,4) int imm) -#define _mm_insert_epi32(a, b, imm) \ - __extension__({ \ - vreinterpretq_m128i_s32( \ - vsetq_lane_s32((b), vreinterpretq_s32_m128i(a), (imm))); \ - }) +#define SSE2NEON_CMP_EQUAL_ORDERED_IMPL(type) \ + static int _sse2neon_cmp_##type##_equal_ordered(__m128i a, int la, \ + __m128i b, int lb) \ + { \ + __m128i mtx[16]; \ + PCMPSTR_EQ(a, b, mtx, SSE2NEON_CAT(SSE2NEON_SIZE_OF_, type), \ + SSE2NEON_CAT(SSE2NEON_NUMBER_OF_LANES_, type)); \ + return SSE2NEON_CAT( \ + _sse2neon_aggregate_equal_ordered_, \ + SSE2NEON_CAT( \ + SSE2NEON_CAT(SSE2NEON_SIZE_OF_, type), \ + SSE2NEON_CAT(x, \ + SSE2NEON_CAT(SSE2NEON_NUMBER_OF_LANES_, type))))( \ + SSE2NEON_CAT(SSE2NEON_NUMBER_OF_LANES_, type), la, lb, mtx); \ + } -// Extracts the selected signed or unsigned 64-bit integer from a and zero -// extends. -// FORCE_INLINE __int64 _mm_extract_epi64(__m128i a, __constrange(0,2) int imm) -#define _mm_extract_epi64(a, imm) \ - vgetq_lane_s64(vreinterpretq_s64_m128i(a), (imm)) +static int _sse2neon_aggregate_equal_any_8x16(int la, int lb, __m128i mtx[16]) +{ + int res = 0; + int m = (1 << la) - 1; + uint8x8_t vec_mask = vld1_u8(_sse2neon_cmpestr_mask8b); + uint8x8_t t_lo = vtst_u8(vdup_n_u8(m & 0xff), vec_mask); + uint8x8_t t_hi = vtst_u8(vdup_n_u8(m >> 8), vec_mask); + uint8x16_t vec = vcombine_u8(t_lo, t_hi); + for (int j = 0; j < lb; j++) { + mtx[j] = vreinterpretq_m128i_u8( + vandq_u8(vec, vreinterpretq_u8_m128i(mtx[j]))); + mtx[j] = vreinterpretq_m128i_u8( + vshrq_n_u8(vreinterpretq_u8_m128i(mtx[j]), 7)); + int tmp = _sse2neon_vaddvq_u8(vreinterpretq_u8_m128i(mtx[j])) ? 1 : 0; + res |= (tmp << j); + } + return res; +} + +static int _sse2neon_aggregate_equal_any_16x8(int la, int lb, __m128i mtx[16]) +{ + int res = 0; + int m = (1 << la) - 1; + uint16x8_t vec = + vtstq_u16(vdupq_n_u16(m), vld1q_u16(_sse2neon_cmpestr_mask16b)); + for (int j = 0; j < lb; j++) { + mtx[j] = vreinterpretq_m128i_u16( + vandq_u16(vec, vreinterpretq_u16_m128i(mtx[j]))); + mtx[j] = vreinterpretq_m128i_u16( + vshrq_n_u16(vreinterpretq_u16_m128i(mtx[j]), 15)); + int tmp = _sse2neon_vaddvq_u16(vreinterpretq_u16_m128i(mtx[j])) ? 1 : 0; + res |= (tmp << j); + } + return res; +} + +/* clang-format off */ +#define SSE2NEON_GENERATE_CMP_EQUAL_ANY(prefix) \ + prefix##IMPL(byte) \ + prefix##IMPL(word) +/* clang-format on */ + +SSE2NEON_GENERATE_CMP_EQUAL_ANY(SSE2NEON_CMP_EQUAL_ANY_) + +static int _sse2neon_aggregate_ranges_16x8(int la, int lb, __m128i mtx[16]) +{ + int res = 0; + int m = (1 << la) - 1; + uint16x8_t vec = + vtstq_u16(vdupq_n_u16(m), vld1q_u16(_sse2neon_cmpestr_mask16b)); + for (int j = 0; j < lb; j++) { + mtx[j] = vreinterpretq_m128i_u16( + vandq_u16(vec, vreinterpretq_u16_m128i(mtx[j]))); + mtx[j] = vreinterpretq_m128i_u16( + vshrq_n_u16(vreinterpretq_u16_m128i(mtx[j]), 15)); + __m128i tmp = vreinterpretq_m128i_u32( + vshrq_n_u32(vreinterpretq_u32_m128i(mtx[j]), 16)); + uint32x4_t vec_res = vandq_u32(vreinterpretq_u32_m128i(mtx[j]), + vreinterpretq_u32_m128i(tmp)); +#if defined(__aarch64__) || defined(_M_ARM64) + int t = vaddvq_u32(vec_res) ? 1 : 0; +#else + uint64x2_t sumh = vpaddlq_u32(vec_res); + int t = vgetq_lane_u64(sumh, 0) + vgetq_lane_u64(sumh, 1); +#endif + res |= (t << j); + } + return res; +} + +static int _sse2neon_aggregate_ranges_8x16(int la, int lb, __m128i mtx[16]) +{ + int res = 0; + int m = (1 << la) - 1; + uint8x8_t vec_mask = vld1_u8(_sse2neon_cmpestr_mask8b); + uint8x8_t t_lo = vtst_u8(vdup_n_u8(m & 0xff), vec_mask); + uint8x8_t t_hi = vtst_u8(vdup_n_u8(m >> 8), vec_mask); + uint8x16_t vec = vcombine_u8(t_lo, t_hi); + for (int j = 0; j < lb; j++) { + mtx[j] = vreinterpretq_m128i_u8( + vandq_u8(vec, vreinterpretq_u8_m128i(mtx[j]))); + mtx[j] = vreinterpretq_m128i_u8( + vshrq_n_u8(vreinterpretq_u8_m128i(mtx[j]), 7)); + __m128i tmp = vreinterpretq_m128i_u16( + vshrq_n_u16(vreinterpretq_u16_m128i(mtx[j]), 8)); + uint16x8_t vec_res = vandq_u16(vreinterpretq_u16_m128i(mtx[j]), + vreinterpretq_u16_m128i(tmp)); + int t = _sse2neon_vaddvq_u16(vec_res) ? 1 : 0; + res |= (t << j); + } + return res; +} + +#define SSE2NEON_CMP_RANGES_IS_BYTE 1 +#define SSE2NEON_CMP_RANGES_IS_WORD 0 + +/* clang-format off */ +#define SSE2NEON_GENERATE_CMP_RANGES(prefix) \ + prefix##IMPL(byte, uint, u, prefix##IS_BYTE) \ + prefix##IMPL(byte, int, s, prefix##IS_BYTE) \ + prefix##IMPL(word, uint, u, prefix##IS_WORD) \ + prefix##IMPL(word, int, s, prefix##IS_WORD) +/* clang-format on */ + +SSE2NEON_GENERATE_CMP_RANGES(SSE2NEON_CMP_RANGES_) + +#undef SSE2NEON_CMP_RANGES_IS_BYTE +#undef SSE2NEON_CMP_RANGES_IS_WORD + +static int _sse2neon_cmp_byte_equal_each(__m128i a, int la, __m128i b, int lb) +{ + uint8x16_t mtx = + vceqq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b)); + int m0 = (la < lb) ? 0 : ((1 << la) - (1 << lb)); + int m1 = 0x10000 - (1 << la); + int tb = 0x10000 - (1 << lb); + uint8x8_t vec_mask, vec0_lo, vec0_hi, vec1_lo, vec1_hi; + uint8x8_t tmp_lo, tmp_hi, res_lo, res_hi; + vec_mask = vld1_u8(_sse2neon_cmpestr_mask8b); + vec0_lo = vtst_u8(vdup_n_u8(m0), vec_mask); + vec0_hi = vtst_u8(vdup_n_u8(m0 >> 8), vec_mask); + vec1_lo = vtst_u8(vdup_n_u8(m1), vec_mask); + vec1_hi = vtst_u8(vdup_n_u8(m1 >> 8), vec_mask); + tmp_lo = vtst_u8(vdup_n_u8(tb), vec_mask); + tmp_hi = vtst_u8(vdup_n_u8(tb >> 8), vec_mask); + + res_lo = vbsl_u8(vec0_lo, vdup_n_u8(0), vget_low_u8(mtx)); + res_hi = vbsl_u8(vec0_hi, vdup_n_u8(0), vget_high_u8(mtx)); + res_lo = vbsl_u8(vec1_lo, tmp_lo, res_lo); + res_hi = vbsl_u8(vec1_hi, tmp_hi, res_hi); + res_lo = vand_u8(res_lo, vec_mask); + res_hi = vand_u8(res_hi, vec_mask); + + int res = _sse2neon_vaddv_u8(res_lo) + (_sse2neon_vaddv_u8(res_hi) << 8); + return res; +} + +static int _sse2neon_cmp_word_equal_each(__m128i a, int la, __m128i b, int lb) +{ + uint16x8_t mtx = + vceqq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b)); + int m0 = (la < lb) ? 0 : ((1 << la) - (1 << lb)); + int m1 = 0x100 - (1 << la); + int tb = 0x100 - (1 << lb); + uint16x8_t vec_mask = vld1q_u16(_sse2neon_cmpestr_mask16b); + uint16x8_t vec0 = vtstq_u16(vdupq_n_u16(m0), vec_mask); + uint16x8_t vec1 = vtstq_u16(vdupq_n_u16(m1), vec_mask); + uint16x8_t tmp = vtstq_u16(vdupq_n_u16(tb), vec_mask); + mtx = vbslq_u16(vec0, vdupq_n_u16(0), mtx); + mtx = vbslq_u16(vec1, tmp, mtx); + mtx = vandq_u16(mtx, vec_mask); + return _sse2neon_vaddvq_u16(mtx); +} + +#define SSE2NEON_AGGREGATE_EQUAL_ORDER_IS_UBYTE 1 +#define SSE2NEON_AGGREGATE_EQUAL_ORDER_IS_UWORD 0 + +#define SSE2NEON_AGGREGATE_EQUAL_ORDER_IMPL(size, number_of_lanes, data_type) \ + static int _sse2neon_aggregate_equal_ordered_##size##x##number_of_lanes( \ + int bound, int la, int lb, __m128i mtx[16]) \ + { \ + int res = 0; \ + int m1 = SSE2NEON_IIF(data_type)(0x10000, 0x100) - (1 << la); \ + uint##size##x8_t vec_mask = SSE2NEON_IIF(data_type)( \ + vld1_u##size(_sse2neon_cmpestr_mask##size##b), \ + vld1q_u##size(_sse2neon_cmpestr_mask##size##b)); \ + uint##size##x##number_of_lanes##_t vec1 = SSE2NEON_IIF(data_type)( \ + vcombine_u##size(vtst_u##size(vdup_n_u##size(m1), vec_mask), \ + vtst_u##size(vdup_n_u##size(m1 >> 8), vec_mask)), \ + vtstq_u##size(vdupq_n_u##size(m1), vec_mask)); \ + uint##size##x##number_of_lanes##_t vec_minusone = vdupq_n_u##size(-1); \ + uint##size##x##number_of_lanes##_t vec_zero = vdupq_n_u##size(0); \ + for (int j = 0; j < lb; j++) { \ + mtx[j] = vreinterpretq_m128i_u##size(vbslq_u##size( \ + vec1, vec_minusone, vreinterpretq_u##size##_m128i(mtx[j]))); \ + } \ + for (int j = lb; j < bound; j++) { \ + mtx[j] = vreinterpretq_m128i_u##size( \ + vbslq_u##size(vec1, vec_minusone, vec_zero)); \ + } \ + unsigned SSE2NEON_IIF(data_type)(char, short) *ptr = \ + (unsigned SSE2NEON_IIF(data_type)(char, short) *) mtx; \ + for (int i = 0; i < bound; i++) { \ + int val = 1; \ + for (int j = 0, k = i; j < bound - i && k < bound; j++, k++) \ + val &= ptr[k * bound + j]; \ + res += val << i; \ + } \ + return res; \ + } + +/* clang-format off */ +#define SSE2NEON_GENERATE_AGGREGATE_EQUAL_ORDER(prefix) \ + prefix##IMPL(8, 16, prefix##IS_UBYTE) \ + prefix##IMPL(16, 8, prefix##IS_UWORD) +/* clang-format on */ + +SSE2NEON_GENERATE_AGGREGATE_EQUAL_ORDER(SSE2NEON_AGGREGATE_EQUAL_ORDER_) + +#undef SSE2NEON_AGGREGATE_EQUAL_ORDER_IS_UBYTE +#undef SSE2NEON_AGGREGATE_EQUAL_ORDER_IS_UWORD -// Inserts the least significant 64 bits of b into the selected 64-bit integer -// of a. -// FORCE_INLINE __m128i _mm_insert_epi64(__m128i a, __int64 b, -// __constrange(0,2) int imm) -#define _mm_insert_epi64(a, b, imm) \ - __extension__({ \ - vreinterpretq_m128i_s64( \ - vsetq_lane_s64((b), vreinterpretq_s64_m128i(a), (imm))); \ - }) +/* clang-format off */ +#define SSE2NEON_GENERATE_CMP_EQUAL_ORDERED(prefix) \ + prefix##IMPL(byte) \ + prefix##IMPL(word) +/* clang-format on */ -// Count the number of bits set to 1 in unsigned 32-bit integer a, and -// return that count in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_popcnt_u32 -FORCE_INLINE int _mm_popcnt_u32(unsigned int a) +SSE2NEON_GENERATE_CMP_EQUAL_ORDERED(SSE2NEON_CMP_EQUAL_ORDERED_) + +#define SSE2NEON_CMPESTR_LIST \ + _(CMP_UBYTE_EQUAL_ANY, cmp_byte_equal_any) \ + _(CMP_UWORD_EQUAL_ANY, cmp_word_equal_any) \ + _(CMP_SBYTE_EQUAL_ANY, cmp_byte_equal_any) \ + _(CMP_SWORD_EQUAL_ANY, cmp_word_equal_any) \ + _(CMP_UBYTE_RANGES, cmp_ubyte_ranges) \ + _(CMP_UWORD_RANGES, cmp_uword_ranges) \ + _(CMP_SBYTE_RANGES, cmp_sbyte_ranges) \ + _(CMP_SWORD_RANGES, cmp_sword_ranges) \ + _(CMP_UBYTE_EQUAL_EACH, cmp_byte_equal_each) \ + _(CMP_UWORD_EQUAL_EACH, cmp_word_equal_each) \ + _(CMP_SBYTE_EQUAL_EACH, cmp_byte_equal_each) \ + _(CMP_SWORD_EQUAL_EACH, cmp_word_equal_each) \ + _(CMP_UBYTE_EQUAL_ORDERED, cmp_byte_equal_ordered) \ + _(CMP_UWORD_EQUAL_ORDERED, cmp_word_equal_ordered) \ + _(CMP_SBYTE_EQUAL_ORDERED, cmp_byte_equal_ordered) \ + _(CMP_SWORD_EQUAL_ORDERED, cmp_word_equal_ordered) + +enum { +#define _(name, func_suffix) name, + SSE2NEON_CMPESTR_LIST +#undef _ +}; +typedef int (*cmpestr_func_t)(__m128i a, int la, __m128i b, int lb); +static cmpestr_func_t _sse2neon_cmpfunc_table[] = { +#define _(name, func_suffix) _sse2neon_##func_suffix, + SSE2NEON_CMPESTR_LIST +#undef _ +}; + +FORCE_INLINE int _sse2neon_sido_negative(int res, int lb, int imm8, int bound) { -#if defined(__aarch64__) -#if __has_builtin(__builtin_popcount) - return __builtin_popcount(a); -#else - return (int) vaddlv_u8(vcnt_u8(vcreate_u8((uint64_t) a))); -#endif -#else - uint32_t count = 0; - uint8x8_t input_val, count8x8_val; - uint16x4_t count16x4_val; - uint32x2_t count32x2_val; + switch (imm8 & 0x30) { + case _SIDD_NEGATIVE_POLARITY: + res ^= 0xffffffff; + break; + case _SIDD_MASKED_NEGATIVE_POLARITY: + res ^= (1 << lb) - 1; + break; + default: + break; + } - input_val = vld1_u8((uint8_t *) &a); - count8x8_val = vcnt_u8(input_val); - count16x4_val = vpaddl_u8(count8x8_val); - count32x2_val = vpaddl_u16(count16x4_val); + return res & ((bound == 8) ? 0xFF : 0xFFFF); +} - vst1_u32(&count, count32x2_val); - return count; +FORCE_INLINE int _sse2neon_clz(unsigned int x) +{ +#ifdef _MSC_VER + unsigned long cnt = 0; + if (_BitScanReverse(&cnt, x)) + return 31 - cnt; + return 32; +#else + return x != 0 ? __builtin_clz(x) : 32; #endif } -// Count the number of bits set to 1 in unsigned 64-bit integer a, and -// return that count in dst. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_popcnt_u64 -FORCE_INLINE int64_t _mm_popcnt_u64(uint64_t a) +FORCE_INLINE int _sse2neon_ctz(unsigned int x) { -#if defined(__aarch64__) -#if __has_builtin(__builtin_popcountll) - return __builtin_popcountll(a); +#ifdef _MSC_VER + unsigned long cnt = 0; + if (_BitScanForward(&cnt, x)) + return cnt; + return 32; #else - return (int64_t) vaddlv_u8(vcnt_u8(vcreate_u8(a))); + return x != 0 ? __builtin_ctz(x) : 32; #endif -#else - uint64_t count = 0; - uint8x8_t input_val, count8x8_val; - uint16x4_t count16x4_val; - uint32x2_t count32x2_val; - uint64x1_t count64x1_val; +} - input_val = vld1_u8((uint8_t *) &a); - count8x8_val = vcnt_u8(input_val); - count16x4_val = vpaddl_u8(count8x8_val); - count32x2_val = vpaddl_u16(count16x4_val); - count64x1_val = vpaddl_u32(count32x2_val); - vst1_u64(&count, count64x1_val); - return count; +FORCE_INLINE int _sse2neon_ctzll(unsigned long long x) +{ +#ifdef _MSC_VER + unsigned long cnt; +#if defined(SSE2NEON_HAS_BITSCAN64) + if (_BitScanForward64(&cnt, x)) + return (int) (cnt); +#else + if (_BitScanForward(&cnt, (unsigned long) (x))) + return (int) cnt; + if (_BitScanForward(&cnt, (unsigned long) (x >> 32))) + return (int) (cnt + 32); +#endif /* SSE2NEON_HAS_BITSCAN64 */ + return 64; +#else /* assume GNU compatible compilers */ + return x != 0 ? __builtin_ctzll(x) : 64; #endif } -// Macro: Transpose the 4x4 matrix formed by the 4 rows of single-precision -// (32-bit) floating-point elements in row0, row1, row2, and row3, and store the -// transposed matrix in these vectors (row0 now contains column 0, etc.). -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=MM_TRANSPOSE4_PS -#define _MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ - do { \ - float32x4x2_t ROW01 = vtrnq_f32(row0, row1); \ - float32x4x2_t ROW23 = vtrnq_f32(row2, row3); \ - row0 = vcombine_f32(vget_low_f32(ROW01.val[0]), \ - vget_low_f32(ROW23.val[0])); \ - row1 = vcombine_f32(vget_low_f32(ROW01.val[1]), \ - vget_low_f32(ROW23.val[1])); \ - row2 = vcombine_f32(vget_high_f32(ROW01.val[0]), \ - vget_high_f32(ROW23.val[0])); \ - row3 = vcombine_f32(vget_high_f32(ROW01.val[1]), \ - vget_high_f32(ROW23.val[1])); \ +#define SSE2NEON_MIN(x, y) (x) < (y) ? (x) : (y) + +#define SSE2NEON_CMPSTR_SET_UPPER(var, imm) \ + const int var = (imm & 0x01) ? 8 : 16 + +#define SSE2NEON_CMPESTRX_LEN_PAIR(a, b, la, lb) \ + int tmp1 = la ^ (la >> 31); \ + la = tmp1 - (la >> 31); \ + int tmp2 = lb ^ (lb >> 31); \ + lb = tmp2 - (lb >> 31); \ + la = SSE2NEON_MIN(la, bound); \ + lb = SSE2NEON_MIN(lb, bound) + +// Compare all pairs of character in string a and b, +// then aggregate the result. +// As the only difference of PCMPESTR* and PCMPISTR* is the way to calculate the +// length of string, we use SSE2NEON_CMP{I,E}STRX_GET_LEN to get the length of +// string a and b. +#define SSE2NEON_COMP_AGG(a, b, la, lb, imm8, IE) \ + SSE2NEON_CMPSTR_SET_UPPER(bound, imm8); \ + SSE2NEON_##IE##_LEN_PAIR(a, b, la, lb); \ + int r2 = (_sse2neon_cmpfunc_table[imm8 & 0x0f])(a, la, b, lb); \ + r2 = _sse2neon_sido_negative(r2, lb, imm8, bound) + +#define SSE2NEON_CMPSTR_GENERATE_INDEX(r2, bound, imm8) \ + return (r2 == 0) ? bound \ + : ((imm8 & 0x40) ? (31 - _sse2neon_clz(r2)) \ + : _sse2neon_ctz(r2)) + +#define SSE2NEON_CMPSTR_GENERATE_MASK(dst) \ + __m128i dst = vreinterpretq_m128i_u8(vdupq_n_u8(0)); \ + if (imm8 & 0x40) { \ + if (bound == 8) { \ + uint16x8_t tmp = vtstq_u16(vdupq_n_u16(r2), \ + vld1q_u16(_sse2neon_cmpestr_mask16b)); \ + dst = vreinterpretq_m128i_u16(vbslq_u16( \ + tmp, vdupq_n_u16(-1), vreinterpretq_u16_m128i(dst))); \ + } else { \ + uint8x16_t vec_r2 = \ + vcombine_u8(vdup_n_u8(r2), vdup_n_u8(r2 >> 8)); \ + uint8x16_t tmp = \ + vtstq_u8(vec_r2, vld1q_u8(_sse2neon_cmpestr_mask8b)); \ + dst = vreinterpretq_m128i_u8( \ + vbslq_u8(tmp, vdupq_n_u8(-1), vreinterpretq_u8_m128i(dst))); \ + } \ + } else { \ + if (bound == 16) { \ + dst = vreinterpretq_m128i_u16( \ + vsetq_lane_u16(r2 & 0xffff, vreinterpretq_u16_m128i(dst), 0)); \ + } else { \ + dst = vreinterpretq_m128i_u8( \ + vsetq_lane_u8(r2 & 0xff, vreinterpretq_u8_m128i(dst), 0)); \ + } \ + } \ + return dst + +// Compare packed strings in a and b with lengths la and lb using the control +// in imm8, and returns 1 if b did not contain a null character and the +// resulting mask was zero, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpestra +FORCE_INLINE int _mm_cmpestra(__m128i a, + int la, + __m128i b, + int lb, + const int imm8) +{ + int lb_cpy = lb; + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPESTRX); + return !r2 & (lb_cpy > bound); +} + +// Compare packed strings in a and b with lengths la and lb using the control in +// imm8, and returns 1 if the resulting mask was non-zero, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpestrc +FORCE_INLINE int _mm_cmpestrc(__m128i a, + int la, + __m128i b, + int lb, + const int imm8) +{ + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPESTRX); + return r2 != 0; +} + +// Compare packed strings in a and b with lengths la and lb using the control +// in imm8, and store the generated index in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpestri +FORCE_INLINE int _mm_cmpestri(__m128i a, + int la, + __m128i b, + int lb, + const int imm8) +{ + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPESTRX); + SSE2NEON_CMPSTR_GENERATE_INDEX(r2, bound, imm8); +} + +// Compare packed strings in a and b with lengths la and lb using the control +// in imm8, and store the generated mask in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpestrm +FORCE_INLINE __m128i +_mm_cmpestrm(__m128i a, int la, __m128i b, int lb, const int imm8) +{ + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPESTRX); + SSE2NEON_CMPSTR_GENERATE_MASK(dst); +} + +// Compare packed strings in a and b with lengths la and lb using the control in +// imm8, and returns bit 0 of the resulting bit mask. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpestro +FORCE_INLINE int _mm_cmpestro(__m128i a, + int la, + __m128i b, + int lb, + const int imm8) +{ + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPESTRX); + return r2 & 1; +} + +// Compare packed strings in a and b with lengths la and lb using the control in +// imm8, and returns 1 if any character in a was null, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpestrs +FORCE_INLINE int _mm_cmpestrs(__m128i a, + int la, + __m128i b, + int lb, + const int imm8) +{ + (void) a; + (void) b; + (void) lb; + SSE2NEON_CMPSTR_SET_UPPER(bound, imm8); + return la <= (bound - 1); +} + +// Compare packed strings in a and b with lengths la and lb using the control in +// imm8, and returns 1 if any character in b was null, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpestrz +FORCE_INLINE int _mm_cmpestrz(__m128i a, + int la, + __m128i b, + int lb, + const int imm8) +{ + (void) a; + (void) b; + (void) la; + SSE2NEON_CMPSTR_SET_UPPER(bound, imm8); + return lb <= (bound - 1); +} + +#define SSE2NEON_CMPISTRX_LENGTH(str, len, imm8) \ + do { \ + if (imm8 & 0x01) { \ + uint16x8_t equal_mask_##str = \ + vceqq_u16(vreinterpretq_u16_m128i(str), vdupq_n_u16(0)); \ + uint8x8_t res_##str = vshrn_n_u16(equal_mask_##str, 4); \ + uint64_t matches_##str = \ + vget_lane_u64(vreinterpret_u64_u8(res_##str), 0); \ + len = _sse2neon_ctzll(matches_##str) >> 3; \ + } else { \ + uint16x8_t equal_mask_##str = vreinterpretq_u16_u8( \ + vceqq_u8(vreinterpretq_u8_m128i(str), vdupq_n_u8(0))); \ + uint8x8_t res_##str = vshrn_n_u16(equal_mask_##str, 4); \ + uint64_t matches_##str = \ + vget_lane_u64(vreinterpret_u64_u8(res_##str), 0); \ + len = _sse2neon_ctzll(matches_##str) >> 2; \ + } \ } while (0) -/* Crypto Extensions */ +#define SSE2NEON_CMPISTRX_LEN_PAIR(a, b, la, lb) \ + int la, lb; \ + do { \ + SSE2NEON_CMPISTRX_LENGTH(a, la, imm8); \ + SSE2NEON_CMPISTRX_LENGTH(b, lb, imm8); \ + } while (0) -#if defined(__ARM_FEATURE_CRYPTO) -// Wraps vmull_p64 -FORCE_INLINE uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b) +// Compare packed strings with implicit lengths in a and b using the control in +// imm8, and returns 1 if b did not contain a null character and the resulting +// mask was zero, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpistra +FORCE_INLINE int _mm_cmpistra(__m128i a, __m128i b, const int imm8) { - poly64_t a = vget_lane_p64(vreinterpret_p64_u64(_a), 0); - poly64_t b = vget_lane_p64(vreinterpret_p64_u64(_b), 0); - return vreinterpretq_u64_p128(vmull_p64(a, b)); + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPISTRX); + return !r2 & (lb >= bound); } -#else // ARMv7 polyfill -// ARMv7/some A64 lacks vmull_p64, but it has vmull_p8. -// -// vmull_p8 calculates 8 8-bit->16-bit polynomial multiplies, but we need a -// 64-bit->128-bit polynomial multiply. -// -// It needs some work and is somewhat slow, but it is still faster than all -// known scalar methods. -// -// Algorithm adapted to C from -// https://www.workofard.com/2017/07/ghash-for-low-end-cores/, which is adapted -// from "Fast Software Polynomial Multiplication on ARM Processors Using the -// NEON Engine" by Danilo Camara, Conrado Gouvea, Julio Lopez and Ricardo Dahab -// (https://hal.inria.fr/hal-01506572) -static uint64x2_t _sse2neon_vmull_p64(uint64x1_t _a, uint64x1_t _b) + +// Compare packed strings with implicit lengths in a and b using the control in +// imm8, and returns 1 if the resulting mask was non-zero, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpistrc +FORCE_INLINE int _mm_cmpistrc(__m128i a, __m128i b, const int imm8) { - poly8x8_t a = vreinterpret_p8_u64(_a); - poly8x8_t b = vreinterpret_p8_u64(_b); + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPISTRX); + return r2 != 0; +} - // Masks - uint8x16_t k48_32 = vcombine_u8(vcreate_u8(0x0000ffffffffffff), - vcreate_u8(0x00000000ffffffff)); - uint8x16_t k16_00 = vcombine_u8(vcreate_u8(0x000000000000ffff), - vcreate_u8(0x0000000000000000)); +// Compare packed strings with implicit lengths in a and b using the control in +// imm8, and store the generated index in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpistri +FORCE_INLINE int _mm_cmpistri(__m128i a, __m128i b, const int imm8) +{ + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPISTRX); + SSE2NEON_CMPSTR_GENERATE_INDEX(r2, bound, imm8); +} - // Do the multiplies, rotating with vext to get all combinations - uint8x16_t d = vreinterpretq_u8_p16(vmull_p8(a, b)); // D = A0 * B0 - uint8x16_t e = - vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 1))); // E = A0 * B1 - uint8x16_t f = - vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 1), b)); // F = A1 * B0 - uint8x16_t g = - vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 2))); // G = A0 * B2 - uint8x16_t h = - vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 2), b)); // H = A2 * B0 - uint8x16_t i = - vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 3))); // I = A0 * B3 - uint8x16_t j = - vreinterpretq_u8_p16(vmull_p8(vext_p8(a, a, 3), b)); // J = A3 * B0 - uint8x16_t k = - vreinterpretq_u8_p16(vmull_p8(a, vext_p8(b, b, 4))); // L = A0 * B4 +// Compare packed strings with implicit lengths in a and b using the control in +// imm8, and store the generated mask in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpistrm +FORCE_INLINE __m128i _mm_cmpistrm(__m128i a, __m128i b, const int imm8) +{ + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPISTRX); + SSE2NEON_CMPSTR_GENERATE_MASK(dst); +} - // Add cross products - uint8x16_t l = veorq_u8(e, f); // L = E + F - uint8x16_t m = veorq_u8(g, h); // M = G + H - uint8x16_t n = veorq_u8(i, j); // N = I + J +// Compare packed strings with implicit lengths in a and b using the control in +// imm8, and returns bit 0 of the resulting bit mask. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpistro +FORCE_INLINE int _mm_cmpistro(__m128i a, __m128i b, const int imm8) +{ + SSE2NEON_COMP_AGG(a, b, la, lb, imm8, CMPISTRX); + return r2 & 1; +} - // Interleave. Using vzip1 and vzip2 prevents Clang from emitting TBL - // instructions. -#if defined(__aarch64__) - uint8x16_t lm_p0 = vreinterpretq_u8_u64( - vzip1q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m))); - uint8x16_t lm_p1 = vreinterpretq_u8_u64( - vzip2q_u64(vreinterpretq_u64_u8(l), vreinterpretq_u64_u8(m))); - uint8x16_t nk_p0 = vreinterpretq_u8_u64( - vzip1q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k))); - uint8x16_t nk_p1 = vreinterpretq_u8_u64( - vzip2q_u64(vreinterpretq_u64_u8(n), vreinterpretq_u64_u8(k))); +// Compare packed strings with implicit lengths in a and b using the control in +// imm8, and returns 1 if any character in a was null, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpistrs +FORCE_INLINE int _mm_cmpistrs(__m128i a, __m128i b, const int imm8) +{ + (void) b; + SSE2NEON_CMPSTR_SET_UPPER(bound, imm8); + int la; + SSE2NEON_CMPISTRX_LENGTH(a, la, imm8); + return la <= (bound - 1); +} + +// Compare packed strings with implicit lengths in a and b using the control in +// imm8, and returns 1 if any character in b was null, and 0 otherwise. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_cmpistrz +FORCE_INLINE int _mm_cmpistrz(__m128i a, __m128i b, const int imm8) +{ + (void) a; + SSE2NEON_CMPSTR_SET_UPPER(bound, imm8); + int lb; + SSE2NEON_CMPISTRX_LENGTH(b, lb, imm8); + return lb <= (bound - 1); +} + +// Compares the 2 signed 64-bit integers in a and the 2 signed 64-bit integers +// in b for greater than. +FORCE_INLINE __m128i _mm_cmpgt_epi64(__m128i a, __m128i b) +{ +#if defined(__aarch64__) || defined(_M_ARM64) + return vreinterpretq_m128i_u64( + vcgtq_s64(vreinterpretq_s64_m128i(a), vreinterpretq_s64_m128i(b))); #else - uint8x16_t lm_p0 = vcombine_u8(vget_low_u8(l), vget_low_u8(m)); - uint8x16_t lm_p1 = vcombine_u8(vget_high_u8(l), vget_high_u8(m)); - uint8x16_t nk_p0 = vcombine_u8(vget_low_u8(n), vget_low_u8(k)); - uint8x16_t nk_p1 = vcombine_u8(vget_high_u8(n), vget_high_u8(k)); + return vreinterpretq_m128i_s64(vshrq_n_s64( + vqsubq_s64(vreinterpretq_s64_m128i(b), vreinterpretq_s64_m128i(a)), + 63)); #endif - // t0 = (L) (P0 + P1) << 8 - // t1 = (M) (P2 + P3) << 16 - uint8x16_t t0t1_tmp = veorq_u8(lm_p0, lm_p1); - uint8x16_t t0t1_h = vandq_u8(lm_p1, k48_32); - uint8x16_t t0t1_l = veorq_u8(t0t1_tmp, t0t1_h); +} - // t2 = (N) (P4 + P5) << 24 - // t3 = (K) (P6 + P7) << 32 - uint8x16_t t2t3_tmp = veorq_u8(nk_p0, nk_p1); - uint8x16_t t2t3_h = vandq_u8(nk_p1, k16_00); - uint8x16_t t2t3_l = veorq_u8(t2t3_tmp, t2t3_h); +// Starting with the initial value in crc, accumulates a CRC32 value for +// unsigned 16-bit integer v, and stores the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_crc32_u16 +FORCE_INLINE uint32_t _mm_crc32_u16(uint32_t crc, uint16_t v) +{ +#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) + __asm__ __volatile__("crc32ch %w[c], %w[c], %w[v]\n\t" + : [c] "+r"(crc) + : [v] "r"(v)); +#elif ((__ARM_ARCH == 8) && defined(__ARM_FEATURE_CRC32)) || \ + (defined(_M_ARM64) && !defined(__clang__)) + crc = __crc32ch(crc, v); +#else + crc = _mm_crc32_u8(crc, v & 0xff); + crc = _mm_crc32_u8(crc, (v >> 8) & 0xff); +#endif + return crc; +} - // De-interleave -#if defined(__aarch64__) - uint8x16_t t0 = vreinterpretq_u8_u64( - vuzp1q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h))); - uint8x16_t t1 = vreinterpretq_u8_u64( - vuzp2q_u64(vreinterpretq_u64_u8(t0t1_l), vreinterpretq_u64_u8(t0t1_h))); - uint8x16_t t2 = vreinterpretq_u8_u64( - vuzp1q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h))); - uint8x16_t t3 = vreinterpretq_u8_u64( - vuzp2q_u64(vreinterpretq_u64_u8(t2t3_l), vreinterpretq_u64_u8(t2t3_h))); +// Starting with the initial value in crc, accumulates a CRC32 value for +// unsigned 32-bit integer v, and stores the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_crc32_u32 +FORCE_INLINE uint32_t _mm_crc32_u32(uint32_t crc, uint32_t v) +{ +#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) + __asm__ __volatile__("crc32cw %w[c], %w[c], %w[v]\n\t" + : [c] "+r"(crc) + : [v] "r"(v)); +#elif ((__ARM_ARCH == 8) && defined(__ARM_FEATURE_CRC32)) || \ + (defined(_M_ARM64) && !defined(__clang__)) + crc = __crc32cw(crc, v); #else - uint8x16_t t1 = vcombine_u8(vget_high_u8(t0t1_l), vget_high_u8(t0t1_h)); - uint8x16_t t0 = vcombine_u8(vget_low_u8(t0t1_l), vget_low_u8(t0t1_h)); - uint8x16_t t3 = vcombine_u8(vget_high_u8(t2t3_l), vget_high_u8(t2t3_h)); - uint8x16_t t2 = vcombine_u8(vget_low_u8(t2t3_l), vget_low_u8(t2t3_h)); + crc = _mm_crc32_u16(crc, v & 0xffff); + crc = _mm_crc32_u16(crc, (v >> 16) & 0xffff); #endif - // Shift the cross products - uint8x16_t t0_shift = vextq_u8(t0, t0, 15); // t0 << 8 - uint8x16_t t1_shift = vextq_u8(t1, t1, 14); // t1 << 16 - uint8x16_t t2_shift = vextq_u8(t2, t2, 13); // t2 << 24 - uint8x16_t t3_shift = vextq_u8(t3, t3, 12); // t3 << 32 + return crc; +} - // Accumulate the products - uint8x16_t cross1 = veorq_u8(t0_shift, t1_shift); - uint8x16_t cross2 = veorq_u8(t2_shift, t3_shift); - uint8x16_t mix = veorq_u8(d, cross1); - uint8x16_t r = veorq_u8(mix, cross2); - return vreinterpretq_u64_u8(r); +// Starting with the initial value in crc, accumulates a CRC32 value for +// unsigned 64-bit integer v, and stores the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_crc32_u64 +FORCE_INLINE uint64_t _mm_crc32_u64(uint64_t crc, uint64_t v) +{ +#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) + __asm__ __volatile__("crc32cx %w[c], %w[c], %x[v]\n\t" + : [c] "+r"(crc) + : [v] "r"(v)); +#elif (defined(_M_ARM64) && !defined(__clang__)) + crc = __crc32cd((uint32_t) crc, v); +#else + crc = _mm_crc32_u32((uint32_t) (crc), v & 0xffffffff); + crc = _mm_crc32_u32((uint32_t) (crc), (v >> 32) & 0xffffffff); +#endif + return crc; } -#endif // ARMv7 polyfill -FORCE_INLINE __m128i _mm_clmulepi64_si128(__m128i _a, __m128i _b, const int imm) +// Starting with the initial value in crc, accumulates a CRC32 value for +// unsigned 8-bit integer v, and stores the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_crc32_u8 +FORCE_INLINE uint32_t _mm_crc32_u8(uint32_t crc, uint8_t v) { - uint64x2_t a = vreinterpretq_u64_m128i(_a); - uint64x2_t b = vreinterpretq_u64_m128i(_b); - switch (imm & 0x11) { - case 0x00: - return vreinterpretq_m128i_u64( - _sse2neon_vmull_p64(vget_low_u64(a), vget_low_u64(b))); - case 0x01: - return vreinterpretq_m128i_u64( - _sse2neon_vmull_p64(vget_high_u64(a), vget_low_u64(b))); - case 0x10: - return vreinterpretq_m128i_u64( - _sse2neon_vmull_p64(vget_low_u64(a), vget_high_u64(b))); - case 0x11: - return vreinterpretq_m128i_u64( - _sse2neon_vmull_p64(vget_high_u64(a), vget_high_u64(b))); - default: - abort(); +#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) + __asm__ __volatile__("crc32cb %w[c], %w[c], %w[v]\n\t" + : [c] "+r"(crc) + : [v] "r"(v)); +#elif ((__ARM_ARCH == 8) && defined(__ARM_FEATURE_CRC32)) || \ + (defined(_M_ARM64) && !defined(__clang__)) + crc = __crc32cb(crc, v); +#else + crc ^= v; + for (int bit = 0; bit < 8; bit++) { + if (crc & 1) + crc = (crc >> 1) ^ UINT32_C(0x82f63b78); + else + crc = (crc >> 1); } +#endif + return crc; } -#if !defined(__ARM_FEATURE_CRYPTO) +/* AES */ + +#if !defined(__ARM_FEATURE_CRYPTO) && (!defined(_M_ARM64) || defined(__clang__)) /* clang-format off */ -#define SSE2NEON_AES_DATA(w) \ +#define SSE2NEON_AES_SBOX(w) \ { \ w(0x63), w(0x7c), w(0x77), w(0x7b), w(0xf2), w(0x6b), w(0x6f), \ w(0xc5), w(0x30), w(0x01), w(0x67), w(0x2b), w(0xfe), w(0xd7), \ @@ -5967,53 +8531,114 @@ FORCE_INLINE __m128i _mm_clmulepi64_si128(__m128i _a, __m128i _b, const int imm) w(0xe6), w(0x42), w(0x68), w(0x41), w(0x99), w(0x2d), w(0x0f), \ w(0xb0), w(0x54), w(0xbb), w(0x16) \ } +#define SSE2NEON_AES_RSBOX(w) \ + { \ + w(0x52), w(0x09), w(0x6a), w(0xd5), w(0x30), w(0x36), w(0xa5), \ + w(0x38), w(0xbf), w(0x40), w(0xa3), w(0x9e), w(0x81), w(0xf3), \ + w(0xd7), w(0xfb), w(0x7c), w(0xe3), w(0x39), w(0x82), w(0x9b), \ + w(0x2f), w(0xff), w(0x87), w(0x34), w(0x8e), w(0x43), w(0x44), \ + w(0xc4), w(0xde), w(0xe9), w(0xcb), w(0x54), w(0x7b), w(0x94), \ + w(0x32), w(0xa6), w(0xc2), w(0x23), w(0x3d), w(0xee), w(0x4c), \ + w(0x95), w(0x0b), w(0x42), w(0xfa), w(0xc3), w(0x4e), w(0x08), \ + w(0x2e), w(0xa1), w(0x66), w(0x28), w(0xd9), w(0x24), w(0xb2), \ + w(0x76), w(0x5b), w(0xa2), w(0x49), w(0x6d), w(0x8b), w(0xd1), \ + w(0x25), w(0x72), w(0xf8), w(0xf6), w(0x64), w(0x86), w(0x68), \ + w(0x98), w(0x16), w(0xd4), w(0xa4), w(0x5c), w(0xcc), w(0x5d), \ + w(0x65), w(0xb6), w(0x92), w(0x6c), w(0x70), w(0x48), w(0x50), \ + w(0xfd), w(0xed), w(0xb9), w(0xda), w(0x5e), w(0x15), w(0x46), \ + w(0x57), w(0xa7), w(0x8d), w(0x9d), w(0x84), w(0x90), w(0xd8), \ + w(0xab), w(0x00), w(0x8c), w(0xbc), w(0xd3), w(0x0a), w(0xf7), \ + w(0xe4), w(0x58), w(0x05), w(0xb8), w(0xb3), w(0x45), w(0x06), \ + w(0xd0), w(0x2c), w(0x1e), w(0x8f), w(0xca), w(0x3f), w(0x0f), \ + w(0x02), w(0xc1), w(0xaf), w(0xbd), w(0x03), w(0x01), w(0x13), \ + w(0x8a), w(0x6b), w(0x3a), w(0x91), w(0x11), w(0x41), w(0x4f), \ + w(0x67), w(0xdc), w(0xea), w(0x97), w(0xf2), w(0xcf), w(0xce), \ + w(0xf0), w(0xb4), w(0xe6), w(0x73), w(0x96), w(0xac), w(0x74), \ + w(0x22), w(0xe7), w(0xad), w(0x35), w(0x85), w(0xe2), w(0xf9), \ + w(0x37), w(0xe8), w(0x1c), w(0x75), w(0xdf), w(0x6e), w(0x47), \ + w(0xf1), w(0x1a), w(0x71), w(0x1d), w(0x29), w(0xc5), w(0x89), \ + w(0x6f), w(0xb7), w(0x62), w(0x0e), w(0xaa), w(0x18), w(0xbe), \ + w(0x1b), w(0xfc), w(0x56), w(0x3e), w(0x4b), w(0xc6), w(0xd2), \ + w(0x79), w(0x20), w(0x9a), w(0xdb), w(0xc0), w(0xfe), w(0x78), \ + w(0xcd), w(0x5a), w(0xf4), w(0x1f), w(0xdd), w(0xa8), w(0x33), \ + w(0x88), w(0x07), w(0xc7), w(0x31), w(0xb1), w(0x12), w(0x10), \ + w(0x59), w(0x27), w(0x80), w(0xec), w(0x5f), w(0x60), w(0x51), \ + w(0x7f), w(0xa9), w(0x19), w(0xb5), w(0x4a), w(0x0d), w(0x2d), \ + w(0xe5), w(0x7a), w(0x9f), w(0x93), w(0xc9), w(0x9c), w(0xef), \ + w(0xa0), w(0xe0), w(0x3b), w(0x4d), w(0xae), w(0x2a), w(0xf5), \ + w(0xb0), w(0xc8), w(0xeb), w(0xbb), w(0x3c), w(0x83), w(0x53), \ + w(0x99), w(0x61), w(0x17), w(0x2b), w(0x04), w(0x7e), w(0xba), \ + w(0x77), w(0xd6), w(0x26), w(0xe1), w(0x69), w(0x14), w(0x63), \ + w(0x55), w(0x21), w(0x0c), w(0x7d) \ + } /* clang-format on */ /* X Macro trick. See https://en.wikipedia.org/wiki/X_Macro */ #define SSE2NEON_AES_H0(x) (x) -static const uint8_t SSE2NEON_sbox[256] = SSE2NEON_AES_DATA(SSE2NEON_AES_H0); +static const uint8_t _sse2neon_sbox[256] = SSE2NEON_AES_SBOX(SSE2NEON_AES_H0); +static const uint8_t _sse2neon_rsbox[256] = SSE2NEON_AES_RSBOX(SSE2NEON_AES_H0); #undef SSE2NEON_AES_H0 -// In the absence of crypto extensions, implement aesenc using regular neon +/* x_time function and matrix multiply function */ +#if !defined(__aarch64__) && !defined(_M_ARM64) +#define SSE2NEON_XT(x) (((x) << 1) ^ ((((x) >> 7) & 1) * 0x1b)) +#define SSE2NEON_MULTIPLY(x, y) \ + (((y & 1) * x) ^ ((y >> 1 & 1) * SSE2NEON_XT(x)) ^ \ + ((y >> 2 & 1) * SSE2NEON_XT(SSE2NEON_XT(x))) ^ \ + ((y >> 3 & 1) * SSE2NEON_XT(SSE2NEON_XT(SSE2NEON_XT(x)))) ^ \ + ((y >> 4 & 1) * SSE2NEON_XT(SSE2NEON_XT(SSE2NEON_XT(SSE2NEON_XT(x)))))) +#endif + +// In the absence of crypto extensions, implement aesenc using regular NEON // intrinsics instead. See: // https://www.workofard.com/2017/01/accelerated-aes-for-the-arm64-linux-kernel/ // https://www.workofard.com/2017/07/ghash-for-low-end-cores/ and -// https://github.com/ColinIanKing/linux-next-mirror/blob/b5f466091e130caaf0735976648f72bd5e09aa84/crypto/aegis128-neon-inner.c#L52 -// for more information Reproduced with permission of the author. -FORCE_INLINE __m128i _mm_aesenc_si128(__m128i EncBlock, __m128i RoundKey) +// for more information. +FORCE_INLINE __m128i _mm_aesenc_si128(__m128i a, __m128i RoundKey) { -#if defined(__aarch64__) - static const uint8_t shift_rows[] = {0x0, 0x5, 0xa, 0xf, 0x4, 0x9, - 0xe, 0x3, 0x8, 0xd, 0x2, 0x7, - 0xc, 0x1, 0x6, 0xb}; - static const uint8_t ror32by8[] = {0x1, 0x2, 0x3, 0x0, 0x5, 0x6, 0x7, 0x4, - 0x9, 0xa, 0xb, 0x8, 0xd, 0xe, 0xf, 0xc}; +#if defined(__aarch64__) || defined(_M_ARM64) + static const uint8_t shift_rows[] = { + 0x0, 0x5, 0xa, 0xf, 0x4, 0x9, 0xe, 0x3, + 0x8, 0xd, 0x2, 0x7, 0xc, 0x1, 0x6, 0xb, + }; + static const uint8_t ror32by8[] = { + 0x1, 0x2, 0x3, 0x0, 0x5, 0x6, 0x7, 0x4, + 0x9, 0xa, 0xb, 0x8, 0xd, 0xe, 0xf, 0xc, + }; uint8x16_t v; - uint8x16_t w = vreinterpretq_u8_m128i(EncBlock); + uint8x16_t w = vreinterpretq_u8_m128i(a); - // shift rows + /* shift rows */ w = vqtbl1q_u8(w, vld1q_u8(shift_rows)); - // sub bytes - v = vqtbl4q_u8(vld1q_u8_x4(SSE2NEON_sbox), w); - v = vqtbx4q_u8(v, vld1q_u8_x4(SSE2NEON_sbox + 0x40), w - 0x40); - v = vqtbx4q_u8(v, vld1q_u8_x4(SSE2NEON_sbox + 0x80), w - 0x80); - v = vqtbx4q_u8(v, vld1q_u8_x4(SSE2NEON_sbox + 0xc0), w - 0xc0); - - // mix columns - w = (v << 1) ^ (uint8x16_t)(((int8x16_t) v >> 7) & 0x1b); + /* sub bytes */ + // Here, we separate the whole 256-bytes table into 4 64-bytes tables, and + // look up each of the table. After each lookup, we load the next table + // which locates at the next 64-bytes. In the meantime, the index in the + // table would be smaller than it was, so the index parameters of + // `vqtbx4q_u8()` need to be added the same constant as the loaded tables. + v = vqtbl4q_u8(_sse2neon_vld1q_u8_x4(_sse2neon_sbox), w); + // 'w-0x40' equals to 'vsubq_u8(w, vdupq_n_u8(0x40))' + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0x40), w - 0x40); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0x80), w - 0x80); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0xc0), w - 0xc0); + + /* mix columns */ + w = (v << 1) ^ (uint8x16_t) (((int8x16_t) v >> 7) & 0x1b); w ^= (uint8x16_t) vrev32q_u16((uint16x8_t) v); w ^= vqtbl1q_u8(v ^ w, vld1q_u8(ror32by8)); - // add round key + /* add round key */ return vreinterpretq_m128i_u8(w) ^ RoundKey; -#else /* ARMv7-A NEON implementation */ -#define SSE2NEON_AES_B2W(b0, b1, b2, b3) \ - (((uint32_t)(b3) << 24) | ((uint32_t)(b2) << 16) | ((uint32_t)(b1) << 8) | \ - (b0)) +#else /* ARMv7-A implementation for a table-based AES */ +#define SSE2NEON_AES_B2W(b0, b1, b2, b3) \ + (((uint32_t) (b3) << 24) | ((uint32_t) (b2) << 16) | \ + ((uint32_t) (b1) << 8) | (uint32_t) (b0)) +// muliplying 'x' by 2 in GF(2^8) #define SSE2NEON_AES_F2(x) ((x << 1) ^ (((x >> 7) & 1) * 0x011b /* WPOLY */)) +// muliplying 'x' by 3 in GF(2^8) #define SSE2NEON_AES_F3(x) (SSE2NEON_AES_F2(x) ^ x) #define SSE2NEON_AES_U0(p) \ SSE2NEON_AES_B2W(SSE2NEON_AES_F2(p), p, p, SSE2NEON_AES_F3(p)) @@ -6023,11 +8648,14 @@ FORCE_INLINE __m128i _mm_aesenc_si128(__m128i EncBlock, __m128i RoundKey) SSE2NEON_AES_B2W(p, SSE2NEON_AES_F3(p), SSE2NEON_AES_F2(p), p) #define SSE2NEON_AES_U3(p) \ SSE2NEON_AES_B2W(p, p, SSE2NEON_AES_F3(p), SSE2NEON_AES_F2(p)) + + // this generates a table containing every possible permutation of + // shift_rows() and sub_bytes() with mix_columns(). static const uint32_t ALIGN_STRUCT(16) aes_table[4][256] = { - SSE2NEON_AES_DATA(SSE2NEON_AES_U0), - SSE2NEON_AES_DATA(SSE2NEON_AES_U1), - SSE2NEON_AES_DATA(SSE2NEON_AES_U2), - SSE2NEON_AES_DATA(SSE2NEON_AES_U3), + SSE2NEON_AES_SBOX(SSE2NEON_AES_U0), + SSE2NEON_AES_SBOX(SSE2NEON_AES_U1), + SSE2NEON_AES_SBOX(SSE2NEON_AES_U2), + SSE2NEON_AES_SBOX(SSE2NEON_AES_U3), }; #undef SSE2NEON_AES_B2W #undef SSE2NEON_AES_F2 @@ -6037,11 +8665,15 @@ FORCE_INLINE __m128i _mm_aesenc_si128(__m128i EncBlock, __m128i RoundKey) #undef SSE2NEON_AES_U2 #undef SSE2NEON_AES_U3 - uint32_t x0 = _mm_cvtsi128_si32(EncBlock); - uint32_t x1 = _mm_cvtsi128_si32(_mm_shuffle_epi32(EncBlock, 0x55)); - uint32_t x2 = _mm_cvtsi128_si32(_mm_shuffle_epi32(EncBlock, 0xAA)); - uint32_t x3 = _mm_cvtsi128_si32(_mm_shuffle_epi32(EncBlock, 0xFF)); + uint32_t x0 = _mm_cvtsi128_si32(a); // get a[31:0] + uint32_t x1 = + _mm_cvtsi128_si32(_mm_shuffle_epi32(a, 0x55)); // get a[63:32] + uint32_t x2 = + _mm_cvtsi128_si32(_mm_shuffle_epi32(a, 0xAA)); // get a[95:64] + uint32_t x3 = + _mm_cvtsi128_si32(_mm_shuffle_epi32(a, 0xFF)); // get a[127:96] + // finish the modulo addition step in mix_columns() __m128i out = _mm_set_epi32( (aes_table[0][x3 & 0xff] ^ aes_table[1][(x0 >> 8) & 0xff] ^ aes_table[2][(x1 >> 16) & 0xff] ^ aes_table[3][x2 >> 24]), @@ -6056,51 +8688,254 @@ FORCE_INLINE __m128i _mm_aesenc_si128(__m128i EncBlock, __m128i RoundKey) #endif } +// Perform one round of an AES decryption flow on data (state) in a using the +// round key in RoundKey, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdec_si128 +FORCE_INLINE __m128i _mm_aesdec_si128(__m128i a, __m128i RoundKey) +{ +#if defined(__aarch64__) + static const uint8_t inv_shift_rows[] = { + 0x0, 0xd, 0xa, 0x7, 0x4, 0x1, 0xe, 0xb, + 0x8, 0x5, 0x2, 0xf, 0xc, 0x9, 0x6, 0x3, + }; + static const uint8_t ror32by8[] = { + 0x1, 0x2, 0x3, 0x0, 0x5, 0x6, 0x7, 0x4, + 0x9, 0xa, 0xb, 0x8, 0xd, 0xe, 0xf, 0xc, + }; + + uint8x16_t v; + uint8x16_t w = vreinterpretq_u8_m128i(a); + + // inverse shift rows + w = vqtbl1q_u8(w, vld1q_u8(inv_shift_rows)); + + // inverse sub bytes + v = vqtbl4q_u8(_sse2neon_vld1q_u8_x4(_sse2neon_rsbox), w); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_rsbox + 0x40), w - 0x40); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_rsbox + 0x80), w - 0x80); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_rsbox + 0xc0), w - 0xc0); + + // inverse mix columns + // multiplying 'v' by 4 in GF(2^8) + w = (v << 1) ^ (uint8x16_t) (((int8x16_t) v >> 7) & 0x1b); + w = (w << 1) ^ (uint8x16_t) (((int8x16_t) w >> 7) & 0x1b); + v ^= w; + v ^= (uint8x16_t) vrev32q_u16((uint16x8_t) w); + + w = (v << 1) ^ (uint8x16_t) (((int8x16_t) v >> 7) & + 0x1b); // muliplying 'v' by 2 in GF(2^8) + w ^= (uint8x16_t) vrev32q_u16((uint16x8_t) v); + w ^= vqtbl1q_u8(v ^ w, vld1q_u8(ror32by8)); + + // add round key + return vreinterpretq_m128i_u8(w) ^ RoundKey; + +#else /* ARMv7-A NEON implementation */ + /* FIXME: optimized for NEON */ + uint8_t i, e, f, g, h, v[4][4]; + uint8_t *_a = (uint8_t *) &a; + for (i = 0; i < 16; ++i) { + v[((i / 4) + (i % 4)) % 4][i % 4] = _sse2neon_rsbox[_a[i]]; + } + + // inverse mix columns + for (i = 0; i < 4; ++i) { + e = v[i][0]; + f = v[i][1]; + g = v[i][2]; + h = v[i][3]; + + v[i][0] = SSE2NEON_MULTIPLY(e, 0x0e) ^ SSE2NEON_MULTIPLY(f, 0x0b) ^ + SSE2NEON_MULTIPLY(g, 0x0d) ^ SSE2NEON_MULTIPLY(h, 0x09); + v[i][1] = SSE2NEON_MULTIPLY(e, 0x09) ^ SSE2NEON_MULTIPLY(f, 0x0e) ^ + SSE2NEON_MULTIPLY(g, 0x0b) ^ SSE2NEON_MULTIPLY(h, 0x0d); + v[i][2] = SSE2NEON_MULTIPLY(e, 0x0d) ^ SSE2NEON_MULTIPLY(f, 0x09) ^ + SSE2NEON_MULTIPLY(g, 0x0e) ^ SSE2NEON_MULTIPLY(h, 0x0b); + v[i][3] = SSE2NEON_MULTIPLY(e, 0x0b) ^ SSE2NEON_MULTIPLY(f, 0x0d) ^ + SSE2NEON_MULTIPLY(g, 0x09) ^ SSE2NEON_MULTIPLY(h, 0x0e); + } + + return vreinterpretq_m128i_u8(vld1q_u8((uint8_t *) v)) ^ RoundKey; +#endif +} + +// Perform the last round of an AES encryption flow on data (state) in a using +// the round key in RoundKey, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenclast_si128 FORCE_INLINE __m128i _mm_aesenclast_si128(__m128i a, __m128i RoundKey) { +#if defined(__aarch64__) + static const uint8_t shift_rows[] = { + 0x0, 0x5, 0xa, 0xf, 0x4, 0x9, 0xe, 0x3, + 0x8, 0xd, 0x2, 0x7, 0xc, 0x1, 0x6, 0xb, + }; + + uint8x16_t v; + uint8x16_t w = vreinterpretq_u8_m128i(a); + + // shift rows + w = vqtbl1q_u8(w, vld1q_u8(shift_rows)); + + // sub bytes + v = vqtbl4q_u8(_sse2neon_vld1q_u8_x4(_sse2neon_sbox), w); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0x40), w - 0x40); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0x80), w - 0x80); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0xc0), w - 0xc0); + + // add round key + return vreinterpretq_m128i_u8(v) ^ RoundKey; + +#else /* ARMv7-A implementation */ + uint8_t v[16] = { + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 0)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 5)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 10)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 15)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 4)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 9)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 14)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 3)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 8)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 13)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 2)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 7)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 12)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 1)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 6)], + _sse2neon_sbox[vgetq_lane_u8(vreinterpretq_u8_m128i(a), 11)], + }; + + return vreinterpretq_m128i_u8(vld1q_u8(v)) ^ RoundKey; +#endif +} + +// Perform the last round of an AES decryption flow on data (state) in a using +// the round key in RoundKey, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdeclast_si128 +FORCE_INLINE __m128i _mm_aesdeclast_si128(__m128i a, __m128i RoundKey) +{ +#if defined(__aarch64__) + static const uint8_t inv_shift_rows[] = { + 0x0, 0xd, 0xa, 0x7, 0x4, 0x1, 0xe, 0xb, + 0x8, 0x5, 0x2, 0xf, 0xc, 0x9, 0x6, 0x3, + }; + + uint8x16_t v; + uint8x16_t w = vreinterpretq_u8_m128i(a); + + // inverse shift rows + w = vqtbl1q_u8(w, vld1q_u8(inv_shift_rows)); + + // inverse sub bytes + v = vqtbl4q_u8(_sse2neon_vld1q_u8_x4(_sse2neon_rsbox), w); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_rsbox + 0x40), w - 0x40); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_rsbox + 0x80), w - 0x80); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_rsbox + 0xc0), w - 0xc0); + + // add round key + return vreinterpretq_m128i_u8(v) ^ RoundKey; + +#else /* ARMv7-A NEON implementation */ /* FIXME: optimized for NEON */ - uint8_t v[4][4] = { - [0] = {SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 0)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 5)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 10)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 15)]}, - [1] = {SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 4)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 9)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 14)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 3)]}, - [2] = {SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 8)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 13)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 2)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 7)]}, - [3] = {SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 12)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 1)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 6)], - SSE2NEON_sbox[vreinterpretq_nth_u8_m128i(a, 11)]}, + uint8_t v[4][4]; + uint8_t *_a = (uint8_t *) &a; + for (int i = 0; i < 16; ++i) { + v[((i / 4) + (i % 4)) % 4][i % 4] = _sse2neon_rsbox[_a[i]]; + } + + return vreinterpretq_m128i_u8(vld1q_u8((uint8_t *) v)) ^ RoundKey; +#endif +} + +// Perform the InvMixColumns transformation on a and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesimc_si128 +FORCE_INLINE __m128i _mm_aesimc_si128(__m128i a) +{ +#if defined(__aarch64__) + static const uint8_t ror32by8[] = { + 0x1, 0x2, 0x3, 0x0, 0x5, 0x6, 0x7, 0x4, + 0x9, 0xa, 0xb, 0x8, 0xd, 0xe, 0xf, 0xc, }; - for (int i = 0; i < 16; i++) - vreinterpretq_nth_u8_m128i(a, i) = - v[i / 4][i % 4] ^ vreinterpretq_nth_u8_m128i(RoundKey, i); - return a; + uint8x16_t v = vreinterpretq_u8_m128i(a); + uint8x16_t w; + + // multiplying 'v' by 4 in GF(2^8) + w = (v << 1) ^ (uint8x16_t) (((int8x16_t) v >> 7) & 0x1b); + w = (w << 1) ^ (uint8x16_t) (((int8x16_t) w >> 7) & 0x1b); + v ^= w; + v ^= (uint8x16_t) vrev32q_u16((uint16x8_t) w); + + // multiplying 'v' by 2 in GF(2^8) + w = (v << 1) ^ (uint8x16_t) (((int8x16_t) v >> 7) & 0x1b); + w ^= (uint8x16_t) vrev32q_u16((uint16x8_t) v); + w ^= vqtbl1q_u8(v ^ w, vld1q_u8(ror32by8)); + return vreinterpretq_m128i_u8(w); + +#else /* ARMv7-A NEON implementation */ + uint8_t i, e, f, g, h, v[4][4]; + vst1q_u8((uint8_t *) v, vreinterpretq_u8_m128i(a)); + for (i = 0; i < 4; ++i) { + e = v[i][0]; + f = v[i][1]; + g = v[i][2]; + h = v[i][3]; + + v[i][0] = SSE2NEON_MULTIPLY(e, 0x0e) ^ SSE2NEON_MULTIPLY(f, 0x0b) ^ + SSE2NEON_MULTIPLY(g, 0x0d) ^ SSE2NEON_MULTIPLY(h, 0x09); + v[i][1] = SSE2NEON_MULTIPLY(e, 0x09) ^ SSE2NEON_MULTIPLY(f, 0x0e) ^ + SSE2NEON_MULTIPLY(g, 0x0b) ^ SSE2NEON_MULTIPLY(h, 0x0d); + v[i][2] = SSE2NEON_MULTIPLY(e, 0x0d) ^ SSE2NEON_MULTIPLY(f, 0x09) ^ + SSE2NEON_MULTIPLY(g, 0x0e) ^ SSE2NEON_MULTIPLY(h, 0x0b); + v[i][3] = SSE2NEON_MULTIPLY(e, 0x0b) ^ SSE2NEON_MULTIPLY(f, 0x0d) ^ + SSE2NEON_MULTIPLY(g, 0x09) ^ SSE2NEON_MULTIPLY(h, 0x0e); + } + + return vreinterpretq_m128i_u8(vld1q_u8((uint8_t *) v)); +#endif } +// Assist in expanding the AES cipher key by computing steps towards generating +// a round key for encryption cipher using data from a and an 8-bit round +// constant specified in imm8, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aeskeygenassist_si128 +// // Emits the Advanced Encryption Standard (AES) instruction aeskeygenassist. // This instruction generates a round key for AES encryption. See // https://kazakov.life/2017/11/01/cryptocurrency-mining-on-ios-devices/ // for details. -// -// https://msdn.microsoft.com/en-us/library/cc714138(v=vs.120).aspx -FORCE_INLINE __m128i _mm_aeskeygenassist_si128(__m128i key, const int rcon) +FORCE_INLINE __m128i _mm_aeskeygenassist_si128(__m128i a, const int rcon) { - uint32_t X1 = _mm_cvtsi128_si32(_mm_shuffle_epi32(key, 0x55)); - uint32_t X3 = _mm_cvtsi128_si32(_mm_shuffle_epi32(key, 0xFF)); +#if defined(__aarch64__) + uint8x16_t _a = vreinterpretq_u8_m128i(a); + uint8x16_t v = vqtbl4q_u8(_sse2neon_vld1q_u8_x4(_sse2neon_sbox), _a); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0x40), _a - 0x40); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0x80), _a - 0x80); + v = vqtbx4q_u8(v, _sse2neon_vld1q_u8_x4(_sse2neon_sbox + 0xc0), _a - 0xc0); + + uint32x4_t v_u32 = vreinterpretq_u32_u8(v); + uint32x4_t ror_v = vorrq_u32(vshrq_n_u32(v_u32, 8), vshlq_n_u32(v_u32, 24)); + uint32x4_t ror_xor_v = veorq_u32(ror_v, vdupq_n_u32(rcon)); + + return vreinterpretq_m128i_u32(vtrn2q_u32(v_u32, ror_xor_v)); + +#else /* ARMv7-A NEON implementation */ + uint32_t X1 = _mm_cvtsi128_si32(_mm_shuffle_epi32(a, 0x55)); + uint32_t X3 = _mm_cvtsi128_si32(_mm_shuffle_epi32(a, 0xFF)); for (int i = 0; i < 4; ++i) { - ((uint8_t *) &X1)[i] = SSE2NEON_sbox[((uint8_t *) &X1)[i]]; - ((uint8_t *) &X3)[i] = SSE2NEON_sbox[((uint8_t *) &X3)[i]]; + ((uint8_t *) &X1)[i] = _sse2neon_sbox[((uint8_t *) &X1)[i]]; + ((uint8_t *) &X3)[i] = _sse2neon_sbox[((uint8_t *) &X3)[i]]; } return _mm_set_epi32(((X3 >> 8) | (X3 << 24)) ^ rcon, X3, ((X1 >> 8) | (X1 << 24)) ^ rcon, X1); +#endif } -#undef SSE2NEON_AES_DATA +#undef SSE2NEON_AES_SBOX +#undef SSE2NEON_AES_RSBOX + +#if defined(__aarch64__) +#undef SSE2NEON_XT +#undef SSE2NEON_MULTIPLY +#endif #else /* __ARM_FEATURE_CRYPTO */ // Implements equivalent of 'aesenc' by combining AESE (with an empty key) and @@ -6111,12 +8946,24 @@ FORCE_INLINE __m128i _mm_aeskeygenassist_si128(__m128i key, const int rcon) // for more details. FORCE_INLINE __m128i _mm_aesenc_si128(__m128i a, __m128i b) { - return vreinterpretq_m128i_u8( - vaesmcq_u8(vaeseq_u8(vreinterpretq_u8_m128i(a), vdupq_n_u8(0))) ^ - vreinterpretq_u8_m128i(b)); + return vreinterpretq_m128i_u8(veorq_u8( + vaesmcq_u8(vaeseq_u8(vreinterpretq_u8_m128i(a), vdupq_n_u8(0))), + vreinterpretq_u8_m128i(b))); +} + +// Perform one round of an AES decryption flow on data (state) in a using the +// round key in RoundKey, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdec_si128 +FORCE_INLINE __m128i _mm_aesdec_si128(__m128i a, __m128i RoundKey) +{ + return vreinterpretq_m128i_u8(veorq_u8( + vaesimcq_u8(vaesdq_u8(vreinterpretq_u8_m128i(a), vdupq_n_u8(0))), + vreinterpretq_u8_m128i(RoundKey))); } -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_aesenclast_si128 +// Perform the last round of an AES encryption flow on data (state) in a using +// the round key in RoundKey, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenclast_si128 FORCE_INLINE __m128i _mm_aesenclast_si128(__m128i a, __m128i RoundKey) { return _mm_xor_si128(vreinterpretq_m128i_u8(vaeseq_u8( @@ -6124,11 +8971,33 @@ FORCE_INLINE __m128i _mm_aesenclast_si128(__m128i a, __m128i RoundKey) RoundKey); } +// Perform the last round of an AES decryption flow on data (state) in a using +// the round key in RoundKey, and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdeclast_si128 +FORCE_INLINE __m128i _mm_aesdeclast_si128(__m128i a, __m128i RoundKey) +{ + return vreinterpretq_m128i_u8( + veorq_u8(vaesdq_u8(vreinterpretq_u8_m128i(a), vdupq_n_u8(0)), + vreinterpretq_u8_m128i(RoundKey))); +} + +// Perform the InvMixColumns transformation on a and store the result in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesimc_si128 +FORCE_INLINE __m128i _mm_aesimc_si128(__m128i a) +{ + return vreinterpretq_m128i_u8(vaesimcq_u8(vreinterpretq_u8_m128i(a))); +} + +// Assist in expanding the AES cipher key by computing steps towards generating +// a round key for encryption cipher using data from a and an 8-bit round +// constant specified in imm8, and store the result in dst." +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aeskeygenassist_si128 FORCE_INLINE __m128i _mm_aeskeygenassist_si128(__m128i a, const int rcon) { // AESE does ShiftRows and SubBytes on A uint8x16_t u8 = vaeseq_u8(vreinterpretq_u8_m128i(a), vdupq_n_u8(0)); +#ifndef _MSC_VER uint8x16_t dest = { // Undo ShiftRows step from AESE and extract X1 and X3 u8[0x4], u8[0x1], u8[0xE], u8[0xB], // SubBytes(X1) @@ -6138,156 +9007,209 @@ FORCE_INLINE __m128i _mm_aeskeygenassist_si128(__m128i a, const int rcon) }; uint32x4_t r = {0, (unsigned) rcon, 0, (unsigned) rcon}; return vreinterpretq_m128i_u8(dest) ^ vreinterpretq_m128i_u32(r); +#else + // We have to do this hack because MSVC is strictly adhering to the CPP + // standard, in particular C++03 8.5.1 sub-section 15, which states that + // unions must be initialized by their first member type. + + // As per the Windows ARM64 ABI, it is always little endian, so this works + __n128 dest{ + ((uint64_t) u8.n128_u8[0x4] << 0) | ((uint64_t) u8.n128_u8[0x1] << 8) | + ((uint64_t) u8.n128_u8[0xE] << 16) | + ((uint64_t) u8.n128_u8[0xB] << 24) | + ((uint64_t) u8.n128_u8[0x1] << 32) | + ((uint64_t) u8.n128_u8[0xE] << 40) | + ((uint64_t) u8.n128_u8[0xB] << 48) | + ((uint64_t) u8.n128_u8[0x4] << 56), + ((uint64_t) u8.n128_u8[0xC] << 0) | ((uint64_t) u8.n128_u8[0x9] << 8) | + ((uint64_t) u8.n128_u8[0x6] << 16) | + ((uint64_t) u8.n128_u8[0x3] << 24) | + ((uint64_t) u8.n128_u8[0x9] << 32) | + ((uint64_t) u8.n128_u8[0x6] << 40) | + ((uint64_t) u8.n128_u8[0x3] << 48) | + ((uint64_t) u8.n128_u8[0xC] << 56)}; + + dest.n128_u32[1] = dest.n128_u32[1] ^ rcon; + dest.n128_u32[3] = dest.n128_u32[3] ^ rcon; + + return dest; +#endif } #endif -/* Streaming Extensions */ +/* Others */ -// Guarantees that every preceding store is globally visible before any -// subsequent store. -// https://msdn.microsoft.com/en-us/library/5h2w73d1%28v=vs.90%29.aspx -FORCE_INLINE void _mm_sfence(void) +// Perform a carry-less multiplication of two 64-bit integers, selected from a +// and b according to imm8, and store the results in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_clmulepi64_si128 +FORCE_INLINE __m128i _mm_clmulepi64_si128(__m128i _a, __m128i _b, const int imm) { - __sync_synchronize(); + uint64x2_t a = vreinterpretq_u64_m128i(_a); + uint64x2_t b = vreinterpretq_u64_m128i(_b); + switch (imm & 0x11) { + case 0x00: + return vreinterpretq_m128i_u64( + _sse2neon_vmull_p64(vget_low_u64(a), vget_low_u64(b))); + case 0x01: + return vreinterpretq_m128i_u64( + _sse2neon_vmull_p64(vget_high_u64(a), vget_low_u64(b))); + case 0x10: + return vreinterpretq_m128i_u64( + _sse2neon_vmull_p64(vget_low_u64(a), vget_high_u64(b))); + case 0x11: + return vreinterpretq_m128i_u64( + _sse2neon_vmull_p64(vget_high_u64(a), vget_high_u64(b))); + default: + abort(); + } } -// Store 128-bits (composed of 4 packed single-precision (32-bit) floating- -// point elements) from a into memory using a non-temporal memory hint. -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_stream_ps -FORCE_INLINE void _mm_stream_ps(float *p, __m128 a) +FORCE_INLINE unsigned int _sse2neon_mm_get_denormals_zero_mode(void) { -#if __has_builtin(__builtin_nontemporal_store) - __builtin_nontemporal_store(a, (float32x4_t *) p); + union { + fpcr_bitfield field; +#if defined(__aarch64__) || defined(_M_ARM64) + uint64_t value; #else - vst1q_f32(p, vreinterpretq_f32_m128(a)); + uint32_t value; #endif -} + } r; -// Stores the data in a to the address p without polluting the caches. If the -// cache line containing address p is already in the cache, the cache will be -// updated. -// https://msdn.microsoft.com/en-us/library/ba08y07y%28v=vs.90%29.aspx -FORCE_INLINE void _mm_stream_si128(__m128i *p, __m128i a) -{ -#if __has_builtin(__builtin_nontemporal_store) - __builtin_nontemporal_store(a, p); +#if defined(__aarch64__) || defined(_M_ARM64) + r.value = _sse2neon_get_fpcr(); #else - vst1q_s64((int64_t *) p, vreinterpretq_s64_m128i(a)); + __asm__ __volatile__("vmrs %0, FPSCR" : "=r"(r.value)); /* read */ #endif + + return r.field.bit24 ? _MM_DENORMALS_ZERO_ON : _MM_DENORMALS_ZERO_OFF; } -// Load 128-bits of integer data from memory into dst using a non-temporal -// memory hint. mem_addr must be aligned on a 16-byte boundary or a -// general-protection exception may be generated. -// -// dst[127:0] := MEM[mem_addr+127:mem_addr] -// -// https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_stream_load_si128 -FORCE_INLINE __m128i _mm_stream_load_si128(__m128i *p) +// Count the number of bits set to 1 in unsigned 32-bit integer a, and +// return that count in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_popcnt_u32 +FORCE_INLINE int _mm_popcnt_u32(unsigned int a) { -#if __has_builtin(__builtin_nontemporal_store) - return __builtin_nontemporal_load(p); +#if defined(__aarch64__) || defined(_M_ARM64) +#if __has_builtin(__builtin_popcount) + return __builtin_popcount(a); +#elif defined(_MSC_VER) + return _CountOneBits(a); #else - return vreinterpretq_m128i_s64(vld1q_s64((int64_t *) p)); + return (int) vaddlv_u8(vcnt_u8(vcreate_u8((uint64_t) a))); #endif -} +#else + uint32_t count = 0; + uint8x8_t input_val, count8x8_val; + uint16x4_t count16x4_val; + uint32x2_t count32x2_val; -// Cache line containing p is flushed and invalidated from all caches in the -// coherency domain. : -// https://msdn.microsoft.com/en-us/library/ba08y07y(v=vs.100).aspx -FORCE_INLINE void _mm_clflush(void const *p) -{ - (void) p; - // no corollary for Neon? -} + input_val = vld1_u8((uint8_t *) &a); + count8x8_val = vcnt_u8(input_val); + count16x4_val = vpaddl_u8(count8x8_val); + count32x2_val = vpaddl_u16(count16x4_val); -// Allocate aligned blocks of memory. -// https://software.intel.com/en-us/ -// cpp-compiler-developer-guide-and-reference-allocating-and-freeing-aligned-memory-blocks -FORCE_INLINE void *_mm_malloc(size_t size, size_t align) -{ - void *ptr; - if (align == 1) - return malloc(size); - if (align == 2 || (sizeof(void *) == 8 && align == 4)) - align = sizeof(void *); - if (!posix_memalign(&ptr, align, size)) - return ptr; - return NULL; + vst1_u32(&count, count32x2_val); + return count; +#endif } -FORCE_INLINE void _mm_free(void *addr) +// Count the number of bits set to 1 in unsigned 64-bit integer a, and +// return that count in dst. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_popcnt_u64 +FORCE_INLINE int64_t _mm_popcnt_u64(uint64_t a) { - free(addr); +#if defined(__aarch64__) || defined(_M_ARM64) +#if __has_builtin(__builtin_popcountll) + return __builtin_popcountll(a); +#elif defined(_MSC_VER) + return _CountOneBits64(a); +#else + return (int64_t) vaddlv_u8(vcnt_u8(vcreate_u8(a))); +#endif +#else + uint64_t count = 0; + uint8x8_t input_val, count8x8_val; + uint16x4_t count16x4_val; + uint32x2_t count32x2_val; + uint64x1_t count64x1_val; + + input_val = vld1_u8((uint8_t *) &a); + count8x8_val = vcnt_u8(input_val); + count16x4_val = vpaddl_u8(count8x8_val); + count32x2_val = vpaddl_u16(count16x4_val); + count64x1_val = vpaddl_u32(count32x2_val); + vst1_u64(&count, count64x1_val); + return count; +#endif } -// Starting with the initial value in crc, accumulates a CRC32 value for -// unsigned 8-bit integer v. -// https://msdn.microsoft.com/en-us/library/bb514036(v=vs.100) -FORCE_INLINE uint32_t _mm_crc32_u8(uint32_t crc, uint8_t v) +FORCE_INLINE void _sse2neon_mm_set_denormals_zero_mode(unsigned int flag) { -#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) - __asm__ __volatile__("crc32cb %w[c], %w[c], %w[v]\n\t" - : [c] "+r"(crc) - : [v] "r"(v)); + // AArch32 Advanced SIMD arithmetic always uses the Flush-to-zero setting, + // regardless of the value of the FZ bit. + union { + fpcr_bitfield field; +#if defined(__aarch64__) || defined(_M_ARM64) + uint64_t value; #else - crc ^= v; - for (int bit = 0; bit < 8; bit++) { - if (crc & 1) - crc = (crc >> 1) ^ UINT32_C(0x82f63b78); - else - crc = (crc >> 1); - } + uint32_t value; #endif - return crc; -} + } r; -// Starting with the initial value in crc, accumulates a CRC32 value for -// unsigned 16-bit integer v. -// https://msdn.microsoft.com/en-us/library/bb531411(v=vs.100) -FORCE_INLINE uint32_t _mm_crc32_u16(uint32_t crc, uint16_t v) -{ -#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) - __asm__ __volatile__("crc32ch %w[c], %w[c], %w[v]\n\t" - : [c] "+r"(crc) - : [v] "r"(v)); +#if defined(__aarch64__) || defined(_M_ARM64) + r.value = _sse2neon_get_fpcr(); #else - crc = _mm_crc32_u8(crc, v & 0xff); - crc = _mm_crc32_u8(crc, (v >> 8) & 0xff); + __asm__ __volatile__("vmrs %0, FPSCR" : "=r"(r.value)); /* read */ #endif - return crc; -} -// Starting with the initial value in crc, accumulates a CRC32 value for -// unsigned 32-bit integer v. -// https://msdn.microsoft.com/en-us/library/bb531394(v=vs.100) -FORCE_INLINE uint32_t _mm_crc32_u32(uint32_t crc, uint32_t v) -{ -#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) - __asm__ __volatile__("crc32cw %w[c], %w[c], %w[v]\n\t" - : [c] "+r"(crc) - : [v] "r"(v)); + r.field.bit24 = (flag & _MM_DENORMALS_ZERO_MASK) == _MM_DENORMALS_ZERO_ON; + +#if defined(__aarch64__) || defined(_M_ARM64) + _sse2neon_set_fpcr(r.value); #else - crc = _mm_crc32_u16(crc, v & 0xffff); - crc = _mm_crc32_u16(crc, (v >> 16) & 0xffff); + __asm__ __volatile__("vmsr FPSCR, %0" ::"r"(r)); /* write */ #endif - return crc; } -// Starting with the initial value in crc, accumulates a CRC32 value for -// unsigned 64-bit integer v. -// https://msdn.microsoft.com/en-us/library/bb514033(v=vs.100) -FORCE_INLINE uint64_t _mm_crc32_u64(uint64_t crc, uint64_t v) +// Return the current 64-bit value of the processor's time-stamp counter. +// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=rdtsc +FORCE_INLINE uint64_t _rdtsc(void) { -#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) - __asm__ __volatile__("crc32cx %w[c], %w[c], %x[v]\n\t" - : [c] "+r"(crc) - : [v] "r"(v)); +#if defined(__aarch64__) || defined(_M_ARM64) + uint64_t val; + + /* According to ARM DDI 0487F.c, from Armv8.0 to Armv8.5 inclusive, the + * system counter is at least 56 bits wide; from Armv8.6, the counter + * must be 64 bits wide. So the system counter could be less than 64 + * bits wide and it is attributed with the flag 'cap_user_time_short' + * is true. + */ +#if defined(_MSC_VER) + val = _ReadStatusReg(ARM64_SYSREG(3, 3, 14, 0, 2)); #else - crc = _mm_crc32_u32((uint32_t)(crc), v & 0xffffffff); - crc = _mm_crc32_u32((uint32_t)(crc), (v >> 32) & 0xffffffff); + __asm__ __volatile__("mrs %0, cntvct_el0" : "=r"(val)); +#endif + + return val; +#else + uint32_t pmccntr, pmuseren, pmcntenset; + // Read the user mode Performance Monitoring Unit (PMU) + // User Enable Register (PMUSERENR) access permissions. + __asm__ __volatile__("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); + if (pmuseren & 1) { // Allows reading PMUSERENR for user mode code. + __asm__ __volatile__("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); + if (pmcntenset & 0x80000000UL) { // Is it counting? + __asm__ __volatile__("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); + // The counter is set up to count every 64th cycle + return (uint64_t) (pmccntr) << 6; + } + } + + // Fallback to syscall as we can't enable PMUSERENR in user mode. + struct timeval tv; + gettimeofday(&tv, NULL); + return (uint64_t) (tv.tv_sec) * 1000000 + tv.tv_usec; #endif - return crc; } #if defined(__GNUC__) || defined(__clang__) @@ -6295,7 +9217,7 @@ FORCE_INLINE uint64_t _mm_crc32_u64(uint64_t crc, uint64_t v) #pragma pop_macro("FORCE_INLINE") #endif -#if defined(__GNUC__) +#if defined(__GNUC__) && !defined(__clang__) #pragma GCC pop_options #endif diff --git a/libhmsbeagle/GPU/ActionCUDAPlugin.cpp b/libhmsbeagle/GPU/ActionCUDAPlugin.cpp new file mode 100644 index 000000000..9488990e6 --- /dev/null +++ b/libhmsbeagle/GPU/ActionCUDAPlugin.cpp @@ -0,0 +1,85 @@ +/** + * libhmsbeagle plugin system + * @author Xiang Ji + * @author Benjamin Redelings + * @author Marc Suchard + */ + +#include "libhmsbeagle/GPU/BeagleGPUActionImpl.h" +#include "ActionCUDAPlugin.h" + + +namespace beagle { + namespace gpu { + + ActionCUDAPlugin::ActionCUDAPlugin() : + Plugin("GPU-Action-CUDA", "GPU-Action-CUDA") + { + GPUInterface gpu; + bool anyGPUSupportsCUDA = false; + bool anyGPUSupportsDP = false; + if (gpu.Initialize()) { + int gpuDeviceCount = gpu.GetDeviceCount(); + anyGPUSupportsCUDA = (gpuDeviceCount > 0); + for (int i = 0; i < gpuDeviceCount; i++) { + int nameDescSize = 256; + char* dName = (char*) malloc(sizeof(char) * nameDescSize); + char* dDesc = (char*) malloc(sizeof(char) * nameDescSize); + gpu.GetDeviceName(i, dName, nameDescSize); + gpu.GetDeviceDescription(i, dDesc); + + BeagleResource resource; + resource.name = dName; + resource.description = dDesc; + resource.supportFlags = BEAGLE_FLAG_COMPUTATION_SYNCH | BEAGLE_FLAG_COMPUTATION_ASYNCH | + BEAGLE_FLAG_PRECISION_SINGLE | + BEAGLE_FLAG_SCALING_MANUAL | BEAGLE_FLAG_SCALING_ALWAYS | + BEAGLE_FLAG_SCALING_AUTO | BEAGLE_FLAG_SCALING_DYNAMIC | + BEAGLE_FLAG_THREADING_NONE | + BEAGLE_FLAG_VECTOR_NONE | + BEAGLE_FLAG_PROCESSOR_GPU | + BEAGLE_FLAG_SCALERS_LOG | BEAGLE_FLAG_SCALERS_RAW | + BEAGLE_FLAG_EIGEN_COMPLEX | BEAGLE_FLAG_EIGEN_REAL | + BEAGLE_FLAG_INVEVEC_STANDARD | BEAGLE_FLAG_INVEVEC_TRANSPOSED | + BEAGLE_FLAG_PREORDER_TRANSPOSE_MANUAL | BEAGLE_FLAG_PREORDER_TRANSPOSE_AUTO | + BEAGLE_FLAG_PARALLELOPS_GRID | BEAGLE_FLAG_PARALLELOPS_STREAMS | + BEAGLE_FLAG_COMPUTATION_ACTION | + BEAGLE_FLAG_FRAMEWORK_CUDA; + // Determine DP capability + if (gpu.GetSupportsDoublePrecision(i)) { + resource.supportFlags |= BEAGLE_FLAG_PRECISION_DOUBLE; + anyGPUSupportsDP = true; + } + + resource.requiredFlags = BEAGLE_FLAG_FRAMEWORK_CUDA; + + beagleResources.push_back(resource); + } + } + + // Optional for plugins: check if the hardware is compatible and only populate + // list with compatible factories +// if(beagleResources.size() > 0) { + if (anyGPUSupportsCUDA) { + using namespace cuda; + if (anyGPUSupportsDP) { + beagleFactories.push_back(new BeagleGPUActionImplFactory()); + } + beagleFactories.push_back(new BeagleGPUActionImplFactory()); + } + } + + ActionCUDAPlugin::~ActionCUDAPlugin() + { + } + + } // namespace gpu +} // namespace beagle + + +extern "C" { +void* plugin_init(void){ + return new beagle::gpu::ActionCUDAPlugin(); +} +} + diff --git a/libhmsbeagle/GPU/ActionCUDAPlugin.h b/libhmsbeagle/GPU/ActionCUDAPlugin.h new file mode 100644 index 000000000..cf6589257 --- /dev/null +++ b/libhmsbeagle/GPU/ActionCUDAPlugin.h @@ -0,0 +1,59 @@ +/** + * libhmsbeagle plugin system + * @author Xiang Ji + * @author Benjamin Redelings + * @author Marc Suchard + */ + +#ifndef __BEAGLE_ACTIONCUDAPLUGIN_H__ +#define __BEAGLE_ACTIONCUDAPLUGIN_H__ + +#ifdef HAVE_CONFIG_H +#include "libhmsbeagle/config.h" +#endif + +#include "libhmsbeagle/platform.h" +#include "libhmsbeagle/plugin/Plugin.h" + + + +namespace beagle { + namespace gpu { + + class BEAGLE_DLLEXPORT ActionCUDAPlugin : public beagle::plugin::Plugin + { + public: + ActionCUDAPlugin(); + ~ActionCUDAPlugin(); + private: + ActionCUDAPlugin( const ActionCUDAPlugin& cp ); // disallow copy by defining this private + }; + + } // namespace gpu +} // namespace beagle + +extern "C" { + BEAGLE_DLLEXPORT void* plugin_init(void); +} + + + + + + + + + + + + + + + + + + + + + +#endif //BEAGLE_ACTIONCUDAPLUGIN_H diff --git a/libhmsbeagle/GPU/BeagleGPUActionImpl.h b/libhmsbeagle/GPU/BeagleGPUActionImpl.h new file mode 100644 index 000000000..799edbb02 --- /dev/null +++ b/libhmsbeagle/GPU/BeagleGPUActionImpl.h @@ -0,0 +1,1302 @@ +/* + * BeagleGPUActionImpl.h + * BEAGLE + * + * Copyright 2024 Phylogenetic Likelihood Working Group + * + * This file is part of BEAGLE. + * + * BEAGLE is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of + * the License, or (at your option) any later version. + * + * BEAGLE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BEAGLE. If not, see + * . + * + * @author Xiang Ji + * @author Benjamin Redelings + * @author Marc Suchard + */ + + +#ifndef BEAGLE_BEAGLEGPUACTIONIMPL_H +#define BEAGLE_BEAGLEGPUACTIONIMPL_H + +#ifdef HAVE_CONFIG_H +#include "libhmsbeagle/config.h" +#endif + +#include "libhmsbeagle/GPU/BeagleGPUImpl.h" +#include +#include +#include +#include +#include +#include +#include // cudaMalloc, cudaMemcpy, etc. +#include // cusparseSpMV +#include +#include "cuda_ops.h" +#include + +using std::vector; +using std::tuple; +using Eigen::MatrixXi; + +#define CHECK_CUDA(func) \ +{ \ + cudaError_t status = (func); \ + if (status != cudaSuccess) { \ + printf("CUDA API failed at line %d with error: %s (%d)\n", \ + __LINE__, cudaGetErrorString(status), status); \ + return EXIT_FAILURE; \ + } \ +} + +#define CHECK_CUSPARSE(func) \ +{ \ + cusparseStatus_t status = (func); \ + if (status != CUSPARSE_STATUS_SUCCESS) { \ + printf("CUSPARSE API failed at line %d with error: %s (%d)\n", \ + __LINE__, cusparseGetErrorString(status), status); \ + return EXIT_FAILURE; \ + } \ +} + +// cublas API error checking +#define CUBLAS_CHECK(err) \ + do { \ + cublasStatus_t err_ = (err); \ + if (err_ != CUBLAS_STATUS_SUCCESS) { \ + std::printf("cublas error %d at %s:%d\n", err_, __FILE__, __LINE__); \ + throw std::runtime_error("cublas error"); \ + } \ + } while (0) + + +template +double normP1(const T& matrix) { + return (Eigen::RowVectorXd::Ones(matrix.rows()) * matrix.cwiseAbs()).maxCoeff(); +} + +template +tuple ArgNormP1(const T& matrix) +{ + int x=-1; + double v = matrix.colwise().template lpNorm<1>().maxCoeff(&x); + return {v,x}; +} + +template +auto normPInf(const T& matrix) { + return matrix.template lpNorm(); +} + +template +auto normPInf(Real* matrix, int nRows, int nCols) +{ + return cuda_max_abs(matrix, nRows * nCols); +} + +template +using SpMatrix = Eigen::SparseMatrix; + +template +using Triplet = Eigen::Triplet; + +template +using DnMatrix = Eigen::Matrix; + +template +using DnVector = Eigen::Matrix; + +template cusparseIndexType_t IndexType; +template <> cusparseIndexType_t IndexType = CUSPARSE_INDEX_32I; +template <> cusparseIndexType_t IndexType = CUSPARSE_INDEX_64I; + +template cudaDataType DataType; +template <> cudaDataType DataType = CUDA_R_32F; +template <> cudaDataType DataType = CUDA_R_64F; + +// A CSR matrix on the host. +template +struct HostCsr +{ + std::vector offsets; + std::vector columns; + std::vector values; + + int nonZeros() const {return (int) values.size();} +}; + +// B = Q - mu*I as an (n,n) CSR matrix with sorted columns, built directly from Q's triplets. Duplicate +// triplets are summed, as Eigen's setFromTriplets( ) does, and every row gets a diagonal entry. +// Two stable counting sorts (by column, then by row) leave each row sorted, in O(nnz + n) for any input +// order. (Going through Eigen took ~2 ms for 75K non-zeros.) +// If slot is non-null, it receives the position in B.values of each triplet, then of each row's -mu. +template +void buildShiftedCsr(int n, const int* rows, const int* cols, const Real* values, int nnz, Real mu, HostCsr& B, + std::vector* slot = nullptr) +{ + const int m = nnz + n; // the triplets, plus (i, i, -mu) for each row + auto rowOf = [&](int k) {return (k < nnz) ? rows[k] : k - nnz;}; + auto colOf = [&](int k) {return (k < nnz) ? cols[k] : k - nnz;}; + auto valueOf = [&](int k) {return (k < nnz) ? values[k] : -mu;}; + + // 1. Order the entries by column. + std::vector start(n + 1, 0); + for (int k = 0; k < m; k++) + start[colOf(k) + 1]++; + for (int j = 0; j < n; j++) + start[j + 1] += start[j]; + std::vector byColumn(m); + for (int k = 0; k < m; k++) + byColumn[start[colOf(k)]++] = k; + + // 2. Stably order them by row, so each row is sorted by column. + B.offsets.assign(n + 1, 0); + for (int k = 0; k < m; k++) + B.offsets[rowOf(k) + 1]++; + for (int i = 0; i < n; i++) + B.offsets[i + 1] += B.offsets[i]; + std::vector next(B.offsets.begin(), B.offsets.end() - 1); + B.columns.resize(m); + B.values.resize(m); + if (slot) slot->resize(m); + for (int k: byColumn) + { + const int a = next[rowOf(k)]++; + B.columns[a] = colOf(k); + B.values[a] = valueOf(k); + if (slot) (*slot)[k] = a; + } + + // 3. Sum duplicates, compacting in place. + std::vector compacted(slot ? m : 0); + int out = 0; + for (int i = 0; i < n; i++) + { + const int begin = B.offsets[i]; + const int end = B.offsets[i + 1]; + B.offsets[i] = out; + for (int a = begin; a < end; a++) + { + if (out > B.offsets[i] and B.columns[out - 1] == B.columns[a]) + B.values[out - 1] += B.values[a]; + else + { + B.columns[out] = B.columns[a]; + B.values[out++] = B.values[a]; + } + if (slot) compacted[a] = out - 1; + } + } + B.offsets[n] = out; + B.columns.resize(out); + B.values.resize(out); + if (slot) + for (int& a: *slot) + a = compacted[a]; +} + +// Builds B = Q - mu*I like buildShiftedCsr( ), and the structure of B^T. It remembers where each triplet +// went, so when Q has the same triplet pattern as last time (the usual case: only the rates change), it only +// scatters the values, in O(nnz), adding them in the same order as a full build. +template +struct ShiftedCsrBuilder +{ + std::vector rows; // the triplet pattern of the last full build + std::vector cols; + std::vector slot; // see buildShiftedCsr( ) + std::vector transposeOffsets; // B^T in CSR: offsets and columns; + std::vector transposeColumns; + std::vector transposeSlot; // its values are B.values[transposeSlot[j]] + + // Returns true if the structure of B (and so of B^T) changed. + bool build(int n, const int* rowIndices, const int* colIndices, const Real* values, int nnz, Real mu, HostCsr& B) + { + const bool samePattern = (int) B.offsets.size() == n + 1 and (int) rows.size() == nnz and + std::equal(rows.begin(), rows.end(), rowIndices) and std::equal(cols.begin(), cols.end(), colIndices); + if (samePattern) + { + std::fill(B.values.begin(), B.values.end(), Real(0)); + for (int k = 0; k < nnz; k++) + B.values[slot[k]] += values[k]; + for (int i = 0; i < n; i++) + B.values[slot[nnz + i]] += -mu; + return false; + } + + rows.assign(rowIndices, rowIndices + nnz); + cols.assign(colIndices, colIndices + nnz); + buildShiftedCsr(n, rowIndices, colIndices, values, nnz, mu, B, &slot); + + // B^T by a counting sort on the columns; rows are visited in order, so each row of B^T is sorted. + transposeOffsets.assign(n + 1, 0); + for (int c: B.columns) + transposeOffsets[c + 1]++; + for (int j = 0; j < n; j++) + transposeOffsets[j + 1] += transposeOffsets[j]; + std::vector next(transposeOffsets.begin(), transposeOffsets.end() - 1); + transposeColumns.resize(B.nonZeros()); + transposeSlot.resize(B.nonZeros()); + for (int i = 0; i < n; i++) + for (int a = B.offsets[i]; a < B.offsets[i + 1]; a++) + { + const int b = next[B.columns[a]]++; + transposeColumns[b] = i; + transposeSlot[b] = a; + } + return true; + } +}; + +// max_i sum_j |B(i,j)| = ||B^T||_1 +template +double normPInf(int n, const HostCsr& B) +{ + double result = 0; + for (int i = 0; i < n; i++) { + double sum = 0; + for (int k = B.offsets[i]; k < B.offsets[i + 1]; k++) + sum += std::abs(B.values[k]); + result = std::max(result, sum); + } + return result; +} + +// max_j sum_i |B(i,j)| +template +double normP1(int n, const HostCsr& B) +{ + std::vector sums(n, 0.0); + for (int k = 0; k < B.nonZeros(); k++) + sums[B.columns[k]] += std::abs(B.values[k]); + return n ? *std::max_element(sums.begin(), sums.end()) : 0.0; +} + +template +struct DnMatrixDevice +{ + cublasHandle_t cublasHandle = nullptr; + // Lets assume any cusparseHandle_t comes from a sparse matrix. + cusparseDnMatDescr_t descr = nullptr; + Real* ptr = nullptr; + size_t size1 = 0; + size_t size2 = 0; + cusparseOrder_t order = CUSPARSE_ORDER_COL; + size_t size() const {return size1*size2;} + size_t byte_size() const {return size()*sizeof(Real);} + + void copyFrom(const DnMatrixDevice& D) + { + assert(order == D.order); + assert(size1 == D.size1); + assert(size2 == D.size2); + MemcpyDeviceToDevice(ptr, D.ptr, size()); + } + + // Disallow copying -- only one object can "own" the descriptor. + DnMatrixDevice& operator=(const DnMatrixDevice&) = delete; + // Allow moving. + DnMatrixDevice& operator=(DnMatrixDevice&& D) noexcept + { + std::swap(cublasHandle, D.cublasHandle); + std::swap(descr, D.descr); + std::swap(ptr, D.ptr); + std::swap(size1, D.size1); + std::swap(size2, D.size2); + std::swap(order, D.order); + return *this; + } + + DnMatrixDevice& operator*=(Real d) + { + cublasStatus_t status; + if constexpr (std::is_same::value) { + status = cublasSscal(cublasHandle, size(), &d, ptr, 1); + } else { + status = cublasDscal(cublasHandle, size(), &d, ptr, 1); + } + + if (status != CUBLAS_STATUS_SUCCESS) + { + std::cerr<<"cublas error "<::operator*=\n"; + exit(1); + } + return *this; + } + + DnMatrixDevice& operator+=(const DnMatrixDevice& D) + { + cublasStatus_t status; + assert(D.size1 == size1); + assert(D.size2 == size2); + assert(D.cublasHandle == cublasHandle); + Real one = 1; + if constexpr (std::is_same::value) { + status = cublasSaxpy(cublasHandle, size(), &one, D.ptr, 1, ptr, 1); + } else { + status = cublasDaxpy(cublasHandle, size(), &one, D.ptr, 1, ptr, 1); + } + + if (status != CUBLAS_STATUS_SUCCESS) + { + std::cerr<<"cublas error "<::operator+=\n"; + exit(1); + } + return *this; + } + + // Disallow copying. + DnMatrixDevice(const DnMatrixDevice&) = delete; + // Allow moving. + DnMatrixDevice(DnMatrixDevice&& D) noexcept + { + operator=(std::move(D)); + } + + DnMatrixDevice() = default; + DnMatrixDevice(cublasHandle_t cb, Real* p, size_t s1, size_t s2, cusparseOrder_t o = CUSPARSE_ORDER_COL) + :cublasHandle(cb), ptr(p), size1(s1), size2(s2), order(o) + { + auto status = (order == CUSPARSE_ORDER_COL) + ? cusparseCreateDnMat(&descr, size1, size2, size1, ptr, DataType, CUSPARSE_ORDER_COL) + : cusparseCreateDnMat(&descr, size1, size2, size2, ptr, DataType, CUSPARSE_ORDER_ROW); + + if (status != CUSPARSE_STATUS_SUCCESS) + { + std::cerr<<"cusparseCreateDnMat( ) failed!"; + std::exit(1); + } + } + DnMatrixDevice(cublasHandle_t cb, size_t s1, size_t s2, cusparseOrder_t o = CUSPARSE_ORDER_COL) + :DnMatrixDevice(cb, cudaDeviceNew(s1*s2), s1, s2, o) + { + } + + ~DnMatrixDevice() + { + // This class does not own the memory, so does not call cudaFree. + if (descr) + { + cusparseDestroyDnMat(descr); + descr = nullptr; + } + } +}; + +enum class sparseFormat { none, csr, csc }; + +template +struct SpMatrixDevice +{ + cublasHandle_t cublasHandle = nullptr; + cusparseHandle_t cusparseHandle = nullptr; + cusparseSpMatDescr_t descr = nullptr; + int size1 = 0; // rows + int size2 = 0; // columns + int num_non_zeros = 0; + Real* values = nullptr; + int* inner = nullptr; + int* offsets = nullptr; + sparseFormat format = sparseFormat::none; + + int outer_dim_size() const + { + // With CSR, we return the number of row. + if (format == sparseFormat::csr) + return size1; + // With CSC, we return the number of columns; + else if (format == sparseFormat::csc) + return size2; + else + std::abort(); + } + + int rows() const {return size1;} + int cols() const {return size2;} + + // Disallow copying -- only one object can "own" the descriptor. + SpMatrixDevice& operator=(const SpMatrixDevice&) = delete; + // Allow moving. + SpMatrixDevice& operator=(SpMatrixDevice&& D) noexcept + { + std::swap(cublasHandle, D.cublasHandle); + std::swap(cusparseHandle, D.cusparseHandle); + std::swap(descr, D.descr); + std::swap(size1, D.size1); + std::swap(size2, D.size2); + std::swap(num_non_zeros, D.num_non_zeros); + std::swap(values, D.values); + std::swap(inner, D.inner); + std::swap(offsets, D.offsets); + std::swap(format, D.format); + return *this; + } + + SpMatrixDevice& operator*=(Real d) + { + cublasStatus_t status; + if constexpr (std::is_same::value) { + status = cublasSscal(cublasHandle, num_non_zeros, &d, values, 1); + } else { + status = cublasDscal(cublasHandle, num_non_zeros, &d, values, 1); + } + + if (status != CUBLAS_STATUS_SUCCESS) + { + std::cerr<<"cublas error "<::operator*=\n"; + exit(1); + } + return *this; + } + + // Disallow copying. + SpMatrixDevice(const SpMatrixDevice&) = delete; + // Allow moving. + SpMatrixDevice(SpMatrixDevice&& D) noexcept + { + operator=(std::move(D)); + } + + void setValues(Real *newValues) { + values = newValues; + } + + SpMatrixDevice() = default; + SpMatrixDevice(cublasHandle_t h1, cusparseHandle_t h2, int s1, int s2, int n, Real* v, int* c, int* o, sparseFormat f) + :cublasHandle(h1), cusparseHandle(h2), size1(s1), size2(s2), num_non_zeros(n), values(v), inner(c), offsets(o), format(f) + { + cusparseStatus_t status; + if (format == sparseFormat::csc) + { + status = cusparseCreateCsc(&descr, s1, s2, num_non_zeros, offsets, inner, values, + IndexType, IndexType, CUSPARSE_INDEX_BASE_ZERO, DataType); + } + else + { + status = cusparseCreateCsr(&descr, s1, s2, num_non_zeros, offsets, inner, values, + IndexType, IndexType, CUSPARSE_INDEX_BASE_ZERO, DataType); + } + + if (status != CUSPARSE_STATUS_SUCCESS) + { + std::cerr<<"cusparseCreateSpMat( ) failed!"; + std::exit(1); + } + } + + ~SpMatrixDevice() + { + if (descr) + { + cusparseDestroySpMat(descr); + descr = nullptr; + } + } +}; + +template +void dotProduct(Real* out, cublasHandle_t handle, int n, Real* v1, Real* v2) +{ + if constexpr (std::is_same::value) + { + cublasSdot(handle, n, v1, 1, v2, 1, out); + } + else + { + cublasDdot(handle, n, v1, 1, v2, 1, out); + } +}; + +template +auto normPInf(const DnMatrixDevice& M) +{ + return normPInf(M.ptr, M.size1, M.size2); +} + +template +int spMM(cusparseHandle_t handle, cusparseDnMatDescr_t C, Real alpha, cusparseSpMatDescr_t A, cusparseDnMatDescr_t B, Real beta, void*& buffer, size_t& buffersize) +{ + size_t new_buffersize; + CHECK_CUSPARSE(cusparseSpMM_bufferSize(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, CUSPARSE_OPERATION_NON_TRANSPOSE, + &alpha, A, B, &beta, C, DataType, + CUSPARSE_SPMM_ALG_DEFAULT, &new_buffersize)); + + if(new_buffersize > buffersize) + { + cudaDeviceDelete(buffer); + buffer = cudaMallocWrapped(new_buffersize); + buffersize = new_buffersize; + } + + // integrationTmp = alpha * A * destP + CHECK_CUSPARSE(cusparseSpMM(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, CUSPARSE_OPERATION_NON_TRANSPOSE, + &alpha, A, B, &beta, C, DataType, + CUSPARSE_SPMM_ALG_DEFAULT, buffer)); //row-major layout provides higher performance (?) + return 0; +} + +template +int spMM(DnMatrixDevice& C, Real alpha, const SpMatrixDevice& A, const DnMatrixDevice& B, Real beta, void*& buffer, size_t& buffersize) +{ + return spMM(A.cusparseHandle, C.descr, alpha, A.descr, B.descr, beta, buffer, buffersize); +} + +// Create an io-manipulator so that we can write std::cerr< +class byRowDense +{ + const DnMatrixDevice& D; + bool multiline = false; +public: + + friend std::ostream& operator<<(std::ostream& o, const byRowDense& pr) + { + auto& D = pr.D; + bool multiline = pr.multiline; + + auto hPtr = MemcpyDeviceToHostVector(D.ptr, D.size()); + + if (not multiline) o<<"Rows ["; + for(int row=0;row& d, bool m=false):D(d),multiline(m) {} +}; + +// Create an io-manipulator so that we can write std::cerr< +class byColDense +{ + const DnMatrixDevice& D; +public: + + friend std::ostream& operator<<(std::ostream& o, const byColDense& pr) + { + auto& D = pr.D; + + auto hPtr = MemcpyDeviceToHostVector(D.ptr, D.size()); + + o<<"Cols[ "; + for(int col=0;col& d):D(d) {} +}; + +std::ostream& operator<<(std::ostream& o, sparseFormat f) +{ + if (f == sparseFormat::csr) + o<<"csr"; + else if (f == sparseFormat::csc) + o<<"csc"; + else + o<<"sparseFormat=unknown"; + return o; +} + +// Create an io-manipulator so that we can write std::cerr< +class byRowSparse +{ + const SpMatrixDevice& S; + bool multiline = false; +public: + + friend std::ostream& operator<<(std::ostream& o, const byRowSparse& pr) + { + auto& S = pr.S; + bool multiline = pr.multiline; + + auto values = MemcpyDeviceToHostVector(S.values, S.num_non_zeros); + auto inner = MemcpyDeviceToHostVector(S.inner, S.num_non_zeros); + auto offsets = MemcpyDeviceToHostVector(S.offsets, S.outer_dim_size() + 1); + + std::vector< std::vector > D(S.size1, std::vector(S.size2, 0)); + for(int o=0; o< S.outer_dim_size();o++) + { + for(int index=offsets[o];index& s, bool m = false):S(s),multiline(m) {} +}; + +template +byRowDense byRow(const DnMatrixDevice& D, bool m = false) +{ + return byRowDense(D, m); +} + +template +byRowSparse byRow(const SpMatrixDevice& D, bool m = false) +{ + return byRowSparse(D, m); +} + +template +byColDense byCol(const DnMatrixDevice& D) +{ + return byColDense(D); +} + +template +std::ostream& operator<<(std::ostream& o, const DnMatrixDevice& D) +{ + return o< +std::ostream& operator<<(std::ostream& o, const SpMatrixDevice& D) +{ + return o< +struct asDeviceVec +{ + const Real* data; + int length; + + asDeviceVec(const Real* d, int l):data(d),length(l) { } +}; + +template +std::ostream& operator<<(std::ostream& o, const asDeviceVec& D) +{ + auto H = MemcpyDeviceToHostVector(D.data, D.length); + + o<<"[ "; + for(auto& h: H) + o< +std::ostream& operator<<(std::ostream& o, const std::vector& H) +{ + o<<"[ "; + for(auto& h: H) + o< +struct BlockNormEstimator +{ + int n = 0; + int t = 0; + int pTop = 0; + + Real* X0 = nullptr; // (n, t) + Real* Y = nullptr; // (n, pTop*t): columns (p-1)*t .. p*t-1 are B^p X0 + Real* chain[2] = {nullptr, nullptr}; // up to (n, (pTop-1)*t) each + Real* sums1 = nullptr; // pTop*t column sums of Y + Real* sums2 = nullptr; // (pTop-1)*t column sums of step 4 + int* unitRows = nullptr; // (pTop-1)*t + Real* rowMax = nullptr; // (pTop-1)*n, for step 3 + Real* norms = nullptr; // pTop+1 + + void allocate(int n_, int t_, int pTop_) + { + n = n_; + t = std::min(t_, n); + pTop = pTop_; + assert(t <= 32); // cuda_select_unit_columns( ) + X0 = cudaDeviceNew((size_t) n * t); + Y = cudaDeviceNew((size_t) n * t * pTop); + chain[0] = cudaDeviceNew((size_t) n * t * (pTop - 1)); + chain[1] = cudaDeviceNew((size_t) n * t * (pTop - 1)); + sums1 = cudaDeviceNew(t * pTop); + sums2 = cudaDeviceNew(t * (pTop - 1)); + unitRows = cudaDeviceNew(t * (pTop - 1)); + rowMax = cudaDeviceNew((size_t) n * (pTop - 1)); + norms = cudaDeviceNew(pTop + 1); + initialize_norm_x_matrix(X0, n, t); + } + + // Returns ||B^p||_1 estimates for p = 2..pTop at index p. (Indices 0 and 1 are not set.) + // B and B^T are (n, n) in CSR. + std::vector estimate(const int* bOffsets, const int* bColumns, const Real* bValues, + const int* btOffsets, const int* btColumns, const Real* btValues, cudaStream_t stream) + { + const int nBlocks = pTop - 1; + const int ldY = pTop * t; + + // 1. Y_p = B^p X0 + for (int p = 1; p <= pTop; p++) + { + const Real* x = (p == 1) ? X0 : Y + (p - 2) * t; + cuda_norm_chain_step(n, bOffsets, bColumns, bValues, x, (p == 1) ? t : ldY, Y + (p - 1) * t, ldY, + t, 0, (Real*)nullptr, 0, nullptr, stream); + } + cuda_column_abs_sums(Y, n, pTop * t, ldY, sums1, stream); + + // 2. Z_p = (B^T)^p sign(Y_p), in block pTop - p. Each step's output has `columns` columns. + Real* in = chain[0]; + Real* out = chain[1]; + int columns = t; + cuda_norm_chain_step(n, btOffsets, btColumns, btValues, (Real*)nullptr, 0, in, columns, 0, t, Y + (pTop - 1) * t, ldY, nullptr, stream); + for (int k = 1; k <= pTop; k++) + { + const bool append = (k < nBlocks); + const Real* sign = append ? Y + (pTop - k - 1) * t : nullptr; + const int outColumns = columns + (append ? t : 0); + cuda_norm_chain_step(n, btOffsets, btColumns, btValues, in, columns, out, outColumns, columns, append ? t : 0, + sign, ldY, nullptr, stream); + std::swap(in, out); + columns = outColumns; + } + assert(columns == nBlocks * t); + + // 3. Unit vectors for the second iteration. + cuda_select_unit_columns(in, n, t, nBlocks, columns, rowMax, unitRows, stream); + + // 4. B^p X_p, in block pTop - p. + columns = t; + cuda_norm_chain_step(n, bOffsets, bColumns, bValues, (Real*)nullptr, 0, out, columns, 0, t, (Real*)nullptr, 0, unitRows, stream); + std::swap(in, out); + for (int k = 1; k <= pTop; k++) + { + const bool append = (k < nBlocks); + const int outColumns = columns + (append ? t : 0); + cuda_norm_chain_step(n, bOffsets, bColumns, bValues, in, columns, out, outColumns, columns, append ? t : 0, + (Real*)nullptr, 0, append ? unitRows + k * t : nullptr, stream); + std::swap(in, out); + columns = outColumns; + } + cuda_column_abs_sums(in, n, nBlocks * t, columns, sums2, stream); + + cuda_combine_norm_estimates(sums1, sums2, t, pTop, norms, stream); + + std::vector result(pTop + 1, 0); + auto status = cudaMemcpyAsync(result.data(), norms, (pTop + 1) * sizeof(Real), cudaMemcpyDeviceToHost, stream); + if (status == cudaSuccess) + status = cudaStreamSynchronize(stream); + if (status != cudaSuccess) + throw std::runtime_error(std::string("BlockNormEstimator: ") + cudaGetErrorString(status)); + return result; + } + + BlockNormEstimator() = default; + BlockNormEstimator(const BlockNormEstimator&) = delete; + BlockNormEstimator& operator=(const BlockNormEstimator&) = delete; + + ~BlockNormEstimator() + { + cudaDeviceDelete(X0); + cudaDeviceDelete(Y); + cudaDeviceDelete(chain[0]); + cudaDeviceDelete(chain[1]); + cudaDeviceDelete(sums1); + cudaDeviceDelete(sums2); + cudaDeviceDelete(unitRows); + cudaDeviceDelete(rowMax); + cudaDeviceDelete(norms); + } +}; + + +//template +//using MapType = DnMatrix; + +namespace beagle { +namespace gpu { + +#ifdef CUDA + namespace cuda { +#else + namespace opencl { +#endif + +BEAGLE_GPU_TEMPLATE +class BeagleGPUActionImpl : public BeagleGPUImpl +{ +public: + const char* getName(); + + long long getFlags(); + + int getInstanceDetails(BeagleInstanceDetails* retunInfo); + + int createInstance(int tipCount, + int partialsBufferCount, + int compactBufferCount, + int stateCount, + int patternCount, + int eigenDecompositionCount, + int matrixCount, + int categoryCount, + int scaleBufferCount, + int globalResourceNumber, + int pluginResourceNumber, + long long preferenceFlags, + long long requirementFlags); + + int setTipStates(int tipIndex, const int* inStates); + + int setTipPartials(int tipIndex, + const Real* inPartials); + + int setPartials(int bufferIndex, + const Real* inPartials); + + int getPartials(int bufferIndex, + int scaleIndex, + double* outPartials) override; + + // Pre-order partials are the stationary frequencies. (Only count == 1, as in the CPU implementation.) + int setRootPrePartials(const int* bufferIndices, const int* stateFrequenciesIndices, int count) override; + + // A derivative matrix for calculateEdgeDerivatives( ), at an index of its own or replacing setSparseMatrix( )'s Q there. + int setSparseDifferentialMatrix(int matrixIndex, const int* rowIndices, const int* colIndices, const double* values, + int numNonZeros) override; + + int setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const Real* values, + int numNonZeros); + + int updatePartials(const int* operations, + int operationCount, + int cumulativeScalingIndex); + + // The base versions read past the end of the scaling buffers unless the pattern count is padded to their + // block size, which the action layout does not do. + int accumulateScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex) override; + int removeScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex) override; + + // Action instances have no dense transition matrices (see createInstance), so these are not available. + // (The base versions of the first three call the dense, non-virtual upPartials/upPrePartials.) + // Pre-order: dest = exp(t Q^T) (exp(t_sibling Q) sibling o parent), see calcPrePartials( ). + int updatePrePartials(const int* operations, int operationCount, int cumulativeScalingIndex) override; + int updatePartialsByPartition(const int*, int) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int updatePrePartialsByPartition(const int*, int) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int setEigenDecomposition(int, const double*, const double*, const double*) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int setTransitionMatrix(int, const double*, double) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int setTransitionMatrices(const int*, const double*, const double*, int) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int getTransitionMatrix(int, double*) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int convolveTransitionMatrices(const int*, const int*, const int*, int) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int transposeTransitionMatrices(const int*, const int*, int) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int updateTransitionMatricesWithModelCategories(int*, const int*, const int*, const int*, const double*, int) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int updateTransitionMatricesWithMultipleModels(const int*, const int*, const int*, const int*, const int*, const double*, int) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int calculateEdgeLogLikelihoods(const int*, const int*, const int*, const int*, const int*, const int*, const int*, const int*, + int, double*, double*, double*) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + int calculateEdgeLogLikelihoodsByPartition(const int*, const int*, const int*, const int*, const int*, const int*, const int*, const int*, + const int*, int, int, double*, double*, double*, double*, double*, double*) override { return BEAGLE_ERROR_NO_IMPLEMENTATION; } + + // Per pattern: sum_c w_c r_c pre^T D post / sum_c w_c pre^T post, with D the derivative matrix (Q itself for + // an index set by setSparseMatrix( )). Categories use rate set 0, as in the CPU implementation. + int calculateEdgeDerivatives(const int* postBufferIndices, const int* preBufferIndices, const int* derivativeMatrixIndices, + const int* categoryWeightsIndices, const int* categoryRatesIndices, const int* cumulativeScaleIndices, + int count, double* outDerivatives, double* outSumDerivatives, double* outSumSquaredDerivatives) override; + + // Adds sum_p (patternWeight_p / pre^T post) sum_c w_c r_c t pre(c, i, p) post(c, j, p) to outSumDerivatives[i * S + j], + // but only for the (i, j) in the sparsity pattern of Q (the union over the eigen indices that are set), which is + // where substitution-model derivatives are non-zero. (The CPU implementation computes all S^2 entries.) + // outSumSquaredDerivatives is not used, as in the CPU implementation. + int calculateCrossProducts(const int* postBufferIndices, const int* preBufferIndices, const int* categoryRatesIndices, + const int* categoryWeightsIndices, const double* edgeLengths, int count, + double* outSumDerivatives, double* outSumSquaredDerivatives) override; + +protected: + + // Per eigen index: B = Q - mu*I. + std::vector> hBs; + // ||B^T||_1 and the d_p of B^T, for the actions of pre-order (estimated on first use after setSparseMatrix( )). + std::vector hBt1Norms; + std::vector> hdsT; + std::vector hdsTCurrent; + std::vector> csrBuilders; + std::vector hMuBs; + std::vector hB1Norms; + const int mMax = 55; + std::vector> hds; + std::map thetaConstants = { + //The first 30 values are from table A.3 of Computing Matrix Functions. + // For double precision, tol = 2^(-53) + // TODO: maybe calculate this + {1, 2.29E-16}, + {2, 2.58E-8}, + {3, 1.39E-5}, + {4, 3.40E-4}, + {5, 2.40E-3}, + {6, 9.07E-3}, + {7, 2.38E-2}, + {8, 5.00E-2}, + {9, 8.96E-2}, + {10, 1.44E-1}, + {11, 2.14E-1}, + {12, 3.00E-1}, + {13, 4.00E-1}, + {14, 5.14E-1}, + {15, 6.41E-1}, + {16, 7.81E-1}, + {17, 9.31E-1}, + {18, 1.09}, + {19, 1.26}, + {20, 1.44}, + {21, 1.62}, + {22, 1.82}, + {23, 2.01}, + {24, 2.22}, + {25, 2.43}, + {26, 2.64}, + {27, 2.86}, + {28, 3.08}, + {29, 3.31}, + {30, 3.54}, + //The rest are from table 3.1 of Computing the Action of the Matrix Exponential. + {35, 4.7}, + {40, 6.0}, + {45, 7.2}, + {50, 8.5}, + {55, 9.9}, + }; + + // Per eigen index: B = Q - mu*I on the device. The edge multiplier goes into the term coefficients. + std::vector> dBs; + BlockNormEstimator normEstimator; + + // Partials are stored pattern-fastest, [category][state][pattern] (see cuda_ops.h); hPartialsTransposed + // converts to and from BEAGLE's [category][pattern][state]. + std::vector hPartialsTransposed; + // Independent operations (e.g. one level of the tree) are computed together, up to maxBatchOperations. + int maxBatchOperations = 1; + // The actions of both children's edges, [operation][child][category] blocks of (kPaddedStateCount, kPaddedPatternCount). + Real* dActionResults = nullptr; + // 2 or 3 Horner work matrices; each holds one (kPaddedStateCount, kPaddedPatternCount) block per operation, + // child and category (see calcPartialsPartials( )). + Real* dActionScratch = nullptr; + // Per-pattern partial results of the product and root kernels. + Real* dReductionScratch = nullptr; + + // Post-order caches each child's action exp(t Q) partials, which pre-order needs for the sibling. A cached action + // is used only if the buffer, the matrix (edge length, Q) and Q are all unchanged since it was computed; generation + // counters track that, so a rejected proposal that BEAST undoes by flipping indices or re-sending edge lengths + // cannot leave a stale action behind. + std::vector partialsGenerations; // per partials buffer: bumped whenever it is written + std::vector matrixGenerations; // per matrix index: bumped by updateTransitionMatrices( ) + std::vector qGenerations; // per eigen index: bumped by setSparseMatrix( ) + struct ActionCacheEntry + { + Real* data = nullptr; // kCategoryCount matrices + bool valid = false; + int matrixIndex = -1; + uint64_t partialsGeneration = 0; + uint64_t matrixGeneration = 0; + uint64_t qGeneration = 0; + }; + std::vector actionCache; // per partials buffer + bool cacheActions = false; // turned on by the first pre-order update + + // Derivative matrices, indexed like setSparseMatrix( ) and setSparseDifferentialMatrix( ). eigenIndex >= 0 means Q + // of that eigen index (B + mu I); otherwise the matrix is stored here. + struct DerivativeMatrix + { + int eigenIndex = -1; + int* offsets = nullptr; + int* columns = nullptr; + Real* values = nullptr; + }; + std::vector derivativeMatrices; + Real* dDerivativeScratch = nullptr; + Real* dDerivativeOutput = nullptr; + size_t derivativeOutputSize = 0; + std::vector hDerivativeOutput; + // Cross products: the pattern (when it is not one eigen index's) and the values. + int* dCrossOffsets = nullptr; + int* dCrossColumns = nullptr; + Real* dCrossValues = nullptr; + size_t crossCapacity = 0; + + // All work is issued on the GPUInterface's stream 0, so it is ordered with the base class's + // copies and kernels (two different blocking streams would not be). See setCudaDevice( ). + cudaStream_t stream = nullptr; + + // Per eigen index: B^T in CSR, and the positions in B's values of its values. + std::vector dBtOffsets; + std::vector dBtColumns; + std::vector dBtSlots; + std::vector dBtValues; + + std::vector dBsCsrOffsetsCache; + std::vector dBsCsrColumnsCache; + std::vector dBsCsrValuesCache; + std::vector currentCacheNNZs; + + cublasHandle_t cublasHandle = nullptr; + cusparseHandle_t cusparseHandle = nullptr; + + std::vector hEigenMaps; + std::vector hEdgeMultipliers; + + + using BeagleGPUImpl::kTipCount; + using BeagleGPUImpl::kPartialsBufferCount; + using BeagleGPUImpl::kStateCount; + using BeagleGPUImpl::kEigenDecompCount; + using BeagleGPUImpl::kCategoryCount; + using BeagleGPUImpl::kMatrixCount; + using BeagleGPUImpl::kPartialsSize; + + + using BeagleGPUImpl::kPaddedStateCount; + using BeagleGPUImpl::gpu; + using BeagleGPUImpl::kPaddedPatternCount; + using BeagleGPUImpl::kFlags; + using BeagleGPUImpl::kMatrixSize; + using BeagleGPUImpl::kernels; + using BeagleGPUImpl::dScalingFactors; + using BeagleGPUImpl::kScaleBufferCount; + using BeagleGPUImpl::dPartials; + using BeagleGPUImpl::dPartialsOrigin; + using BeagleGPUImpl::hCategoryRates; + + // For calculateRootLogLikelihoods + using BeagleGPUImpl::dAccumulatedScalingFactors; + using BeagleGPUImpl::dIntegrationTmp; + using BeagleGPUImpl::dWeights; + using BeagleGPUImpl::dFrequencies; + using BeagleGPUImpl::dSumLogLikelihood; + using BeagleGPUImpl::dPatternWeights; + using BeagleGPUImpl::hLogLikelihoodsCache; + using BeagleGPUImpl::kSumSitesBlockCount; + using BeagleGPUImpl::kPatternCount; + using BeagleGPUImpl::kScaleBufferSize; + using BeagleGPUImpl::dPtrQueue; + using BeagleGPUImpl::hPtrQueue; + using BeagleGPUImpl::dMaxScalingFactors; + using BeagleGPUImpl::dIndexMaxScalingFactors; + + int addScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex, bool subtract); + + int upPartials(bool byPartition, + const int *operations, + int operationCount, + int cumulativeScalingIndex); + + int upPrePartials(bool byPartition, + const int *operations, + int operationCount, + int cumulativeScalingIndex); + + int calculateRootLogLikelihoods(const int* bufferIndices, + const int* categoryWeightsIndices, + const int* stateFrequenciesIndices, + const int* cumulativeScaleIndices, + int count, + double* outSumLogLikelihood); + + ~BeagleGPUActionImpl(); + +private: + char* getInstanceName(); + + int updateTransitionMatrices(int eigenIndex, + const int* probabilityIndices, + const int* firstDerivativeIndices, + const int* secondDerivativeIndices, + const Real* edgeLengths, + int count); + double getPMax() const; + + // Make CUDA runtime, cuBLAS, cuSPARSE and Thrust calls target this instance's device, + // and cuBLAS/cuSPARSE use the GPUInterface's stream. + void setCudaDevice(); + + // Copy BEAGLE-layout partials (for one category if tipPartials, else for all) into dPartials[bufferIndex]. + void uploadPartials(int bufferIndex, const Real* inPartials, bool tipPartials); + + // Post-order: destination = action(children[0], edges[0]) o action(children[1], edges[1]). + // Pre-order: children[0] is the parent's pre-order buffer and children[1] the sibling's post-order buffer; + // edges[0] is the destination's edge and edges[1] the sibling's. + struct PartialsOperation + { + int destination; + int children[2]; + int edges[2]; + Real* scalingFactors; // nullptr means no rescaling + Real* fixedScalingFactors = nullptr; // otherwise, divide by these existing factors (a read scaling index) + }; + + // Groups operations into batches of independent ones (one tree level, up to maxBatchOperations each), in an + // order that respects their dependencies through the partials and scaling buffers. + std::vector> scheduleBatches(const std::vector& operations) const; + + // The operations must be independent: no operation reads or writes another one's destination. + void calcPartialsPartials(const std::vector& operations, Real* cumulativeScalingBuffer); + void calcPrePartials(const std::vector& operations, Real* cumulativeScalingBuffer); + + // Whether actionCache[buffer] holds exp(t Q) partials for the buffer's current contents and matrixIndex. + bool actionCached(int buffer, int matrixIndex) const; + // Where post-order may put a child's action so that it is cached, or nullptr. + Real* actionCacheSlot(int buffer, int matrixIndex); + + // Makes hdsT[eigenIndex] current. + void estimateTransposedNorms(int eigenIndex); + + // out = exp(multiplier * Q_eigenIndex) * in for one (kPaddedStateCount, kPaddedPatternCount) matrix. + // in is not modified; scratch is 2 or 3 matrices of work space with row stride scratchStride. + struct ActionGroup + { + const Real* in; + Real* out; + Real* scratch[3]; + int scratchCount; + int scratchStride; + int eigenIndex; + double multiplier; + bool transpose; // use Q^T + }; + + // Points group.scratch at the work blocks of group number g (< 2 * kCategoryCount * maxBatchOperations). + void setActionScratch(ActionGroup& group, size_t g); + + // With fewer than 32 patterns, the Horner work blocks are interleaved (see calcPartialsPartials( )). + bool interleavedScratch() const { return kPaddedPatternCount < 32; } + + // Computes all the actions, batching the Taylor terms of the groups that share Q into one launch each. + void computeActions(const std::vector& groups); + + std::tuple getStatistics2(double t, int nCol, double edgeMultiplier, + int eigenIndex, bool transpose = false) const; + + double getDValue(int p, int eigenIndex, bool transpose = false) const; + + int PrintfDeviceVector(Real* dPtr, int length, double checkValue, int *signal, Real r); + int PrintfDeviceVector(int* dPtr, int length, double checkValue, int *signal, Real r); + int PrintfDeviceVector(cusparseDnMatDescr_t dPtr, int length, double checkValue, int *signal, Real r); + +}; + +BEAGLE_GPU_TEMPLATE +class BeagleGPUActionImplFactory : public BeagleGPUImplFactory { + virtual BeagleImpl* createImpl(int tipCount, + int partialsBufferCount, + int compactBufferCount, + int stateCount, + int patternCount, + int eigenBufferCount, + int matrixBufferCount, + int categoryCount, + int scaleBufferCount, + int resourceNumber, + int pluginResourceNumber, + long long preferenceFlags, + long long requirementFlags, + int* errorCode); + + virtual const char* getName(); + virtual long long getFlags(); +}; + +} // namspace device +} // namespace gpu +} // namespace beagle + +#include "libhmsbeagle/GPU/BeagleGPUActionImpl.hpp" + +#endif + diff --git a/libhmsbeagle/GPU/BeagleGPUActionImpl.hpp b/libhmsbeagle/GPU/BeagleGPUActionImpl.hpp new file mode 100644 index 000000000..e3daebb2d --- /dev/null +++ b/libhmsbeagle/GPU/BeagleGPUActionImpl.hpp @@ -0,0 +1,1908 @@ +/* + * BeagleGPUImpl.cpp + * BEAGLE + * + * Copyright 2024 Phylogenetic Likelihood Working Group + * + * This file is part of BEAGLE. + * + * BEAGLE is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of + * the License, or (at your option) any later version. + * + * BEAGLE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BEAGLE. If not, see + * . + * + * @author Xiang Ji + * @author Benjamin Redelings + * @author Marc Suchard + */ +#ifdef HAVE_CONFIG_H +#include "libhmsbeagle/config.h" +#endif + +#ifndef BEAGLE_BEAGLEGPUACTIONIMPL_HPP +#define BEAGLE_BEAGLEGPUACTIONIMPL_HPP + + +// Duplicated from CPU code +std::independent_bits_engine engine; + +bool random_bool() +{ + return engine(); +} +double random_plus_minus_1_func(double x) +{ + if (random_bool()) + return 1; + else + return -1; +} + +// Algorithm 2.4 from Higham and Tisseur (2000), A BLOCK ALGORITHM FOR MATRIX 1-NORM ESTIMATION, +// WITH AN APPLICATION TO 1-NORM PSEUDOSPECTRA. +// See OneNormEst in https://eprints.maths.manchester.ac.uk/2195/1/thesis-main.pdf +// This seems to have a bug where it checks if columns in S are parallel to EVERY column of S_old. +// See also https://github.com/gnu-octave/octave/blob/default/scripts/linear-algebra/normest1.m +// See dlacn1.f +template +Real normest1(const SpMatrix& A, int p, int t=2, int itmax=5) +{ + assert(p >= 0); + assert(t != 0); // negative means t = n + assert(itmax >= 1); + + if (p == 0) return 1.0; + + // A is (n,n); + assert(A.rows() == A.cols()); + int n = A.cols(); + + // Handle t too large + t = std::min(n,t); + + // Interpret negative t as t == n + if (t < 0) t = n; + + // Defer to normP1 if p=1 and n is small or we want an exact answer. + if (p == 1 and (n <= 4 or t == n)) + return normP1(A); + + // (0) Choose starting matrix X that is (n,t) with columns of unit 1-norm. + DnMatrix X(n,t); + // We choose the first column to be all 1s. + X.col(0).setOnes(); + // The other columns have randomly chosen {-1,+1} entries. + X = X.unaryExpr( &random_plus_minus_1_func ); + // Divide by n so that the norm of each column is 1. + X /= n; + + // 3. + std::vector ind_hist(n,0); + std::vector indices(n,0); + int ind_best = -1; + Real est_old = 0; + DnMatrix S = DnMatrix::Ones(n,t); + DnMatrix S_old = DnMatrix::Ones(n,t); + MatrixXi prodS(t,t); + DnMatrix Y(n,t); + DnMatrix Z(n,t); + DnVector h(n); + + for(int k=1; k<=itmax; k++) + { + // std::cerr<<"iter "< est_old or k == 2) + { + // Note that j is in [0,t-1], but indices[j] is in [0,n-1]. + ind_best = indices[j]; + // w = Y.col(ind_best); + } + // std::cerr<<" est = "<= 2) + { + // std::cerr<<" The new estimate ("<= est_old); + + // S = sign(Y), 0.0 -> 1.0 + S = Y.unaryExpr([](const Real& x) {return (x>=0) ? 1.0 : -1.0 ;}); + + // prodS is (t,t) + prodS = (S_old.transpose() * S).matrix().cwiseAbs().template cast() ; + + // (2) If each columns in S is parallel to SOME column of S_old + if (prodS.colwise().maxCoeff().sum() == n * t and k >= 2) + { + // std::cerr<<" All columns of S parallel to S_old\n"; + return est; + } + + if (t > 1) + { + // If S(j) is parallel to S_old(i), replace S(j) with random column + for(int j=0;j() ; + for(int i=0;i (n,t) + + // Maximize across each the t entries in each row of Z. + h = Z.cwiseAbs().rowwise().maxCoeff(); // (n,t) -> (n,1) + + // (4) of Algorithm 2.4 + if (k >= 2 and h.maxCoeff() == h[ind_best]) + { + // std::cerr<<" The best column ("< h[j];}); + + // (5) of Algorithm 2.4 + int n_found = 0; + for(int i=0;i= 2); + // std::cerr<<" All columns were found in the column history.\n"; + return est; + } + + // find the first t indices that are not in ind_hist + int l=0; + for(int i=0;i(t, indices.size()); + + X = DnMatrix::Zero(n, tmax); + for(int j=0; j < tmax; j++) + X(indices[j], j) = 1; // X(:,j) = e(indices[j]) + + for(int i: indices) + ind_hist[i] = true; + + S_old = S; + } + + return est_old; +} + + +namespace beagle { +namespace gpu { + +#ifdef CUDA + namespace cuda { +#else + namespace opencl { +#endif + +BEAGLE_GPU_TEMPLATE +const char* BeagleGPUActionImpl::getName() +{ + return BeagleGPUActionImplFactory::getName(); +} + + +BEAGLE_GPU_TEMPLATE +long long BeagleGPUActionImpl::getFlags() +{ + auto flags = BeagleGPUImpl::getFlags(); + + flags |= BEAGLE_FLAG_COMPUTATION_ACTION; + + return flags; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::createInstance(int tipCount, + int partialsBufferCount, + int compactBufferCount, + int stateCount, + int patternCount, + int eigenDecompositionCount, + int matrixCount, + int categoryCount, + int scaleBufferCount, + int globalResourceNumber, + int pluginResourceNumber, + long long preferenceFlags, + long long requirementFlags) +{ + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUActionImpl::createInstance\n"); +#endif + + // The action flag makes the base class skip its dense (S x S) eigen and transition-matrix buffers. + int returnCode = BeagleGPUImpl::createInstance(tipCount, partialsBufferCount, 0, stateCount, patternCount, + eigenDecompositionCount, matrixCount, categoryCount, scaleBufferCount, globalResourceNumber, pluginResourceNumber, + preferenceFlags | BEAGLE_FLAG_COMPUTATION_ACTION, requirementFlags); + if (returnCode != BEAGLE_SUCCESS) + return returnCode; + + setCudaDevice(); + + hBs.resize(kEigenDecompCount); + csrBuilders.resize(kEigenDecompCount); + hBt1Norms.resize(kEigenDecompCount); + hdsT.resize(kEigenDecompCount); + hdsTCurrent.assign(kEigenDecompCount, false); + partialsGenerations.assign(kPartialsBufferCount, 0); + matrixGenerations.assign(kMatrixCount, 0); + qGenerations.assign(kEigenDecompCount, 0); + actionCache.resize(kPartialsBufferCount); + derivativeMatrices.resize(kEigenDecompCount + kMatrixCount); + hMuBs.resize(kEigenDecompCount); + hB1Norms.resize(kEigenDecompCount); + hds.resize(kEigenDecompCount); + + CUBLAS_CHECK(cublasCreate(&cublasHandle)); + CHECK_CUSPARSE(cusparseCreate(&cusparseHandle)); + setCudaDevice(); + + dBsCsrOffsetsCache.resize(kEigenDecompCount); + dBsCsrColumnsCache.resize(kEigenDecompCount); + dBsCsrValuesCache.resize(kEigenDecompCount); + dBs = std::vector>(kEigenDecompCount); + // getStatistics2( ) uses d_p for p = 2 .. pMax+1. + normEstimator.allocate(kPaddedStateCount, 5, getPMax() + 1); + + currentCacheNNZs = std::vector(kEigenDecompCount, kPaddedStateCount); + dBtOffsets.assign(kEigenDecompCount, nullptr); + dBtColumns.assign(kEigenDecompCount, nullptr); + dBtSlots.assign(kEigenDecompCount, nullptr); + dBtValues.assign(kEigenDecompCount, nullptr); + for (int i = 0; i < kEigenDecompCount; i++) { + dBsCsrOffsetsCache[i] = cudaDeviceNew(kPaddedStateCount + 1); + dBtOffsets[i] = cudaDeviceNew(kPaddedStateCount + 1); + dBsCsrColumnsCache[i] = cudaDeviceNew(currentCacheNNZs[i]); + dBsCsrValuesCache[i] = cudaDeviceNew(currentCacheNNZs[i]); + } + + + const size_t partialsSize = (size_t) kPaddedStateCount * kPaddedPatternCount * kCategoryCount; + // Batching operations only pays off when each is small, so cap the extra memory at about 64 MB. + // (2 results and 2 or 3 scratch blocks per child and category of each operation.) + const int scratchCount = interleavedScratch() ? 3 : 2; + maxBatchOperations = std::max(1, std::min(kMaxPartialsProducts, (64 << 20) / ((2 + 2 * scratchCount) * partialsSize * sizeof(Real)))); + dActionResults = cudaDeviceNew(2 * partialsSize * maxBatchOperations); + dActionScratch = cudaDeviceNew(2 * scratchCount * partialsSize * maxBatchOperations); + const int reductionRows = kCategoryCount * kPaddedStateCount; + dReductionScratch = cudaDeviceNew((size_t) cuda_row_chunk_count(reductionRows, kPaddedPatternCount) * kPaddedPatternCount * maxBatchOperations); + + hEigenMaps.resize(kMatrixCount); + hEdgeMultipliers.resize(kMatrixCount * kCategoryCount); + + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +BeagleGPUActionImpl::~BeagleGPUActionImpl() +{ + cudaSetDevice(gpu->GetCudaDeviceOrdinal()); + cudaStreamSynchronize(stream); + + cudaFree(dActionResults); + cudaFree(dActionScratch); + cudaFree(dReductionScratch); + for (auto& entry: actionCache) + cudaFree(entry.data); + for (auto& matrix: derivativeMatrices) { + cudaFree(matrix.offsets); + cudaFree(matrix.columns); + cudaFree(matrix.values); + } + cudaFree(dDerivativeScratch); + cudaFree(dDerivativeOutput); + cudaFree(dCrossOffsets); + cudaFree(dCrossColumns); + cudaFree(dCrossValues); + + for (int i = 0; i < kEigenDecompCount; i++) { + cudaFree(dBsCsrOffsetsCache[i]); + cudaFree(dBtOffsets[i]); + cudaFree(dBtColumns[i]); + cudaFree(dBtSlots[i]); + cudaFree(dBtValues[i]); + cudaFree(dBsCsrColumnsCache[i]); + cudaFree(dBsCsrValuesCache[i]); + } + cublasDestroy(cublasHandle); + cusparseDestroy(cusparseHandle); +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::getInstanceDetails(BeagleInstanceDetails* returnInfo) { + BeagleGPUImpl::getInstanceDetails(returnInfo); + returnInfo->implName = getInstanceName(); + return BEAGLE_SUCCESS; +} + +#ifdef CUDA +template<> +char* BeagleGPUActionImpl::getInstanceName() { + return (char*) "Action-CUDA-Double"; +} + +template<> +char* BeagleGPUActionImpl::getInstanceName() { + return (char*) "Action-CUDA-Single"; +} +#elif defined(FW_OPENCL) + template<> +char* BeagleGPUActionImpl::getInstanceName() { + return (char*) "Action-OpenCL-Double"; +} + +template<> +char* BeagleGPUActionImpl::getInstanceName() { + return (char*) "Action-OpenCL-Single"; +} +#endif + + + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::setTipStates(int tipIndex, const int* inStates) +{ + std::cerr<<"\nBEAGLE: When using action-based likelihood computations, setTipStates( ) is not allowed.\n"; + std::cerr<<" Use setTipPartials( ) instead.\n\n"; + + // There does not appear to be a simple method of throwing C++ exceptions into Java through the JNI. + // However, throwing this exception makes Java print a stack trace that shows where the setTipStates( ) + // call is coming from. + throw std::runtime_error("This message will not be seen"); + + std::abort(); +} + +BEAGLE_GPU_TEMPLATE +void BeagleGPUActionImpl::uploadPartials(int bufferIndex, const Real* inPartials, bool tipPartials) +{ + // BEAGLE's layout is [category][pattern][state]; tip partials have one category. Padding stays 0. + hPartialsTransposed.assign(kPartialsSize, 0); + for (int category = 0; category < kCategoryCount; category++) { + const Real* in = inPartials + (tipPartials ? 0 : (size_t) category * kPatternCount * kStateCount); + Real* out = hPartialsTransposed.data() + (size_t) category * kPaddedStateCount * kPaddedPatternCount; + for (int pattern = 0; pattern < kPatternCount; pattern++) + for (int state = 0; state < kStateCount; state++) + out[(size_t) state * kPaddedPatternCount + pattern] = in[(size_t) pattern * kStateCount + state]; + } + gpu->MemcpyHostToDevice(dPartials[bufferIndex], hPartialsTransposed.data(), sizeof(Real) * kPartialsSize); + partialsGenerations[bufferIndex]++; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::setTipPartials(int tipIndex, const Real* inPartials) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUActionImpl::setTipPartials\n"); +#endif + + // The base class assigns the tip's device buffer; then overwrite it in the action layout. + int returnCode = BeagleGPUImpl::setTipPartials(tipIndex, inPartials); + if (returnCode != BEAGLE_SUCCESS) + return returnCode; + uploadPartials(tipIndex, inPartials, true); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUActionImpl::setTipPartials\n"); +#endif + + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::setPartials(int bufferIndex, const Real* inPartials) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUActionImpl::setPartials\n"); +#endif + + int returnCode = BeagleGPUImpl::setPartials(bufferIndex, inPartials); + if (returnCode != BEAGLE_SUCCESS) + return returnCode; + uploadPartials(bufferIndex, inPartials, false); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUActionImpl::setPartials\n"); +#endif + + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::getPartials(int bufferIndex, int scaleIndex, double* outPartials) { + if (bufferIndex < 0 || bufferIndex >= kPartialsBufferCount) + return BEAGLE_ERROR_OUT_OF_RANGE; + + hPartialsTransposed.resize(kPartialsSize); + gpu->MemcpyDeviceToHost(hPartialsTransposed.data(), dPartials[bufferIndex], sizeof(Real) * kPartialsSize); + for (int category = 0; category < kCategoryCount; category++) { + const Real* in = hPartialsTransposed.data() + (size_t) category * kPaddedStateCount * kPaddedPatternCount; + double* out = outPartials + (size_t) category * kPatternCount * kStateCount; + for (int pattern = 0; pattern < kPatternCount; pattern++) + for (int state = 0; state < kStateCount; state++) + out[(size_t) pattern * kStateCount + state] = in[(size_t) state * kPaddedPatternCount + pattern]; + } + return BEAGLE_SUCCESS; +} + + + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::updatePartials(const int* operations, + int operationCount, + int cumulativeScalingIndex) { + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUActionImpl::updatePartials\n"); +#endif + + setCudaDevice(); + + bool byPartition = false; + int returnCode = upPartials(byPartition, + operations, + operationCount, + cumulativeScalingIndex); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUActionImpl::updatePartials\n"); +#endif + + return returnCode; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::accumulateScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex) +{ + return addScaleFactors(scalingIndices, count, cumulativeScalingIndex, false); +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::removeScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex) +{ + return addScaleFactors(scalingIndices, count, cumulativeScalingIndex, true); +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::addScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex, bool subtract) +{ + // Automatic and dynamic scaling keep extra state in the base class. + if (kFlags & (BEAGLE_FLAG_SCALING_AUTO | BEAGLE_FLAG_SCALING_DYNAMIC)) { + return subtract ? BeagleGPUImpl::removeScaleFactors(scalingIndices, count, cumulativeScalingIndex) + : BeagleGPUImpl::accumulateScaleFactors(scalingIndices, count, cumulativeScalingIndex); + } + if (cumulativeScalingIndex < 0 || cumulativeScalingIndex >= kScaleBufferCount) + return BEAGLE_ERROR_OUT_OF_RANGE; + + setCudaDevice(); + const bool scalersLog = (kFlags & BEAGLE_FLAG_SCALERS_LOG) != 0; + ScaleFactorBatch batch; + for (int n = 0; n < count; n++) { + if (scalingIndices[n] < 0 || scalingIndices[n] >= kScaleBufferCount) + return BEAGLE_ERROR_OUT_OF_RANGE; + batch.factors[batch.count++] = (const Real*) dScalingFactors[scalingIndices[n]]; + if (batch.count == 64 or n == count - 1) { + cuda_accumulate_scale_factors(batch, kPaddedPatternCount, (Real*) dScalingFactors[cumulativeScalingIndex], scalersLog, + subtract, stream); + batch.count = 0; + } + } + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +void BeagleGPUActionImpl::setCudaDevice() +{ + // GPUInterface uses the driver API and pops its context after each call, so without this + // runtime-API work would go to device 0. + auto status = cudaSetDevice(gpu->GetCudaDeviceOrdinal()); + if (status != cudaSuccess) + throw std::runtime_error(std::string("cudaSetDevice: ") + cudaGetErrorString(status)); + + auto beagleStream = (cudaStream_t) gpu->GetCudaStream(); + if (cublasHandle and beagleStream != stream) + { + stream = beagleStream; + CUBLAS_CHECK(cublasSetStream(cublasHandle, stream)); + if (cusparseSetStream(cusparseHandle, stream) != CUSPARSE_STATUS_SUCCESS) + throw std::runtime_error("cusparseSetStream failed"); + } +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::upPartials(bool byPartition, + const int *operations, + int operationCount, + int cumulativeScalingIndex) +{ + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUActionImpl::upPartials\n"); +#endif + + Real* cumulativeScalingBuffer = 0; + if (cumulativeScalingIndex != BEAGLE_OP_NONE) + cumulativeScalingBuffer = (Real*)dScalingFactors[cumulativeScalingIndex]; + + std::vector parsed(operationCount); + for (int op = 0; op < operationCount; op++) { + const int numOps = BEAGLE_OP_COUNT; + + const int destinationPartialIndex = operations[op * numOps]; + const int writeScalingIndex = operations[op * numOps + 1]; + const int readScalingIndex = operations[op * numOps + 2]; + const int firstChildPartialIndex = operations[op * numOps + 3]; + const int firstChildSubstitutionMatrixIndex = operations[op * numOps + 4]; + const int secondChildPartialIndex = operations[op * numOps + 5]; + const int secondChildSubstitutionMatrixIndex = operations[op * numOps + 6]; + + int rescale = BEAGLE_OP_NONE; + Real* scalingFactors = nullptr; + + if (kFlags & BEAGLE_FLAG_SCALING_AUTO) { + int sIndex = destinationPartialIndex - kTipCount; + + rescale = 2; + scalingFactors = (Real*)dScalingFactors[sIndex]; + } else if (kFlags & BEAGLE_FLAG_SCALING_ALWAYS) { + rescale = 1; + scalingFactors = (Real*)dScalingFactors[destinationPartialIndex - kTipCount]; + } else if ((kFlags & BEAGLE_FLAG_SCALING_MANUAL) && writeScalingIndex >= 0) { + rescale = 1; + scalingFactors = (Real*)dScalingFactors[writeScalingIndex]; + } else if ((kFlags & BEAGLE_FLAG_SCALING_MANUAL) && readScalingIndex >= 0) { + rescale = 0; + scalingFactors = (Real*)dScalingFactors[readScalingIndex]; + } + + PartialsOperation& operation = parsed[op]; + operation.destination = destinationPartialIndex; + operation.children[0] = firstChildPartialIndex; + operation.children[1] = secondChildPartialIndex; + operation.edges[0] = firstChildSubstitutionMatrixIndex; + operation.edges[1] = secondChildSubstitutionMatrixIndex; + operation.scalingFactors = (rescale == 1) ? scalingFactors : nullptr; + operation.fixedScalingFactors = (rescale == 0) ? scalingFactors : nullptr; + } + + for (const auto& batch: scheduleBatches(parsed)) { + calcPartialsPartials(batch, cumulativeScalingBuffer); + if (kFlags & BEAGLE_FLAG_SCALING_ALWAYS) { + for (const auto& operation: batch) { + int parScalingIndex = operation.destination - kTipCount; + int child1ScalingIndex = operation.children[0] - kTipCount; + int child2ScalingIndex = operation.children[1] - kTipCount; + if (child1ScalingIndex >= 0 && child2ScalingIndex >= 0) { + int scalingIndices[2] = {child1ScalingIndex, child2ScalingIndex}; + accumulateScaleFactors(scalingIndices, 2, parScalingIndex); + } else if (child1ScalingIndex >= 0) { + int scalingIndices[1] = {child1ScalingIndex}; + accumulateScaleFactors(scalingIndices, 1, parScalingIndex); + } else if (child2ScalingIndex >= 0) { + int scalingIndices[1] = {child2ScalingIndex}; + accumulateScaleFactors(scalingIndices, 1, parScalingIndex); + } + } + } + } + +#ifdef BEAGLE_DEBUG_SYNCH + gpu->SynchronizeHost(); +#endif + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUActionImpl::upPartials\n"); +#endif + + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +std::vector::PartialsOperation>> +BeagleGPUActionImpl::scheduleBatches(const std::vector& operations) const +{ + // Each operation goes to the earliest level after every earlier operation that writes a buffer it reads, or + // reads or writes a buffer (partials or scaling) it writes. The operations of a level are independent. + const int operationCount = (int) operations.size(); + std::vector levels(operationCount); + std::vector writeLevel(kPartialsBufferCount, -1); + std::vector readLevel(kPartialsBufferCount, -1); + std::map scalingWriteLevel; + int levelCount = 0; + + for (int op = 0; op < operationCount; op++) { + const PartialsOperation& operation = operations[op]; + int level = std::max(writeLevel[operation.destination], readLevel[operation.destination]) + 1; + for (int child: operation.children) + level = std::max(level, writeLevel[child] + 1); + if (operation.fixedScalingFactors) { + auto it = scalingWriteLevel.find(operation.fixedScalingFactors); + if (it != scalingWriteLevel.end()) + level = std::max(level, it->second + 1); + } + if (operation.scalingFactors) { + auto it = scalingWriteLevel.find(operation.scalingFactors); + if (it != scalingWriteLevel.end()) + level = std::max(level, it->second + 1); + scalingWriteLevel[operation.scalingFactors] = level; + } + writeLevel[operation.destination] = level; + for (int child: operation.children) + readLevel[child] = std::max(readLevel[child], level); + levels[op] = level; + levelCount = std::max(levelCount, level + 1); + } + + std::vector> batches; + for (int level = 0; level < levelCount; level++) { + std::vector batch; + for (int op = 0; op < operationCount; op++) { + if (levels[op] != level) + continue; + if ((int) batch.size() == maxBatchOperations) { + batches.push_back(batch); + batch.clear(); + } + batch.push_back(operations[op]); + } + if (not batch.empty()) + batches.push_back(batch); + } + return batches; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::updatePrePartials(const int* operations, + int operationCount, + int cumulativeScalingIndex) +{ + setCudaDevice(); + return upPrePartials(false, operations, operationCount, cumulativeScalingIndex); +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::upPrePartials(bool byPartition, + const int *operations, + int operationCount, + int cumulativeScalingIndex) +{ + // From now on post-order keeps the children's actions for the siblings of later pre-order updates. + cacheActions = true; + + Real* cumulativeScalingBuffer = nullptr; + if (cumulativeScalingIndex != BEAGLE_OP_NONE) + cumulativeScalingBuffer = (Real*)dScalingFactors[cumulativeScalingIndex]; + + // [dest, writeScaling, readScaling, parent (pre-order), dest's matrix, sibling (post-order), sibling's matrix]. + // As in the CPU implementation, only manual scaling indices are used (not automatic or always-rescaling). + std::vector parsed(operationCount); + for (int op = 0; op < operationCount; op++) { + const int* x = operations + op * BEAGLE_OP_COUNT; + PartialsOperation& operation = parsed[op]; + operation.destination = x[0]; + operation.children[0] = x[3]; + operation.children[1] = x[5]; + operation.edges[0] = x[4]; + operation.edges[1] = x[6]; + operation.scalingFactors = (x[1] >= 0) ? (Real*)dScalingFactors[x[1]] : nullptr; + operation.fixedScalingFactors = (x[1] < 0 and x[2] >= 0) ? (Real*)dScalingFactors[x[2]] : nullptr; + for (int buffer: {x[0], x[3], x[5]}) + if (buffer < 0 or buffer >= kPartialsBufferCount or dPartials[buffer] == 0) + return BEAGLE_ERROR_OUT_OF_RANGE; + } + + for (const auto& batch: scheduleBatches(parsed)) + calcPrePartials(batch, cumulativeScalingBuffer); + +#ifdef BEAGLE_DEBUG_SYNCH + gpu->SynchronizeHost(); +#endif + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +bool BeagleGPUActionImpl::actionCached(int buffer, int matrixIndex) const +{ + const ActionCacheEntry& entry = actionCache[buffer]; + return entry.valid and entry.data and entry.matrixIndex == matrixIndex and + entry.partialsGeneration == partialsGenerations[buffer] and + entry.matrixGeneration == matrixGenerations[matrixIndex] and + entry.qGeneration == qGenerations[hEigenMaps[matrixIndex]]; +} + +BEAGLE_GPU_TEMPLATE +Real* BeagleGPUActionImpl::actionCacheSlot(int buffer, int matrixIndex) +{ + if (not cacheActions) + return nullptr; + ActionCacheEntry& entry = actionCache[buffer]; + if (not entry.data) { + const size_t size = (size_t) kCategoryCount * kPaddedStateCount * kPaddedPatternCount; + if (cudaMalloc((void**) &entry.data, size * sizeof(Real)) != cudaSuccess) { + // Out of memory: pre-order recomputes the siblings' actions instead. + cudaGetLastError(); + entry.data = nullptr; + return nullptr; + } + } + entry.valid = true; + entry.matrixIndex = matrixIndex; + entry.partialsGeneration = partialsGenerations[buffer]; + entry.matrixGeneration = matrixGenerations[matrixIndex]; + entry.qGeneration = qGenerations[hEigenMaps[matrixIndex]]; + return entry.data; +} + +BEAGLE_GPU_TEMPLATE +void BeagleGPUActionImpl::estimateTransposedNorms(int eigenIndex) +{ + if (hdsTCurrent[eigenIndex]) + return; + // The estimator for B^T: its transpose is B. + const auto& dB = dBs[eigenIndex]; + auto norms = normEstimator.estimate(dBtOffsets[eigenIndex], dBtColumns[eigenIndex], dBtValues[eigenIndex], + dB.offsets, dB.inner, dB.values, stream); + const int pTop = getPMax() + 1; + hdsT[eigenIndex].assign(pTop + 1, 1.0); + hdsT[eigenIndex][1] = hBt1Norms[eigenIndex]; + for (int p = 2; p <= pTop; p++) + hdsT[eigenIndex][p] = pow(norms[p], 1.0 / Real(p)); + hdsTCurrent[eigenIndex] = true; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::setRootPrePartials(const int* bufferIndices, + const int* stateFrequenciesIndices, + int count) +{ + if (count != 1) + return BEAGLE_ERROR_NO_IMPLEMENTATION; + const int buffer = bufferIndices[0]; + if (buffer < 0 or buffer >= kPartialsBufferCount or dPartials[buffer] == 0) + return BEAGLE_ERROR_OUT_OF_RANGE; + setCudaDevice(); + cuda_root_pre_partials((Real*) dPartials[buffer], (const Real*) dFrequencies[stateFrequenciesIndices[0]], + kPaddedStateCount, kCategoryCount, kPaddedPatternCount, kPatternCount, stream); + partialsGenerations[buffer]++; + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::setSparseDifferentialMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros) +{ + if (matrixIndex < 0 or matrixIndex >= (int) derivativeMatrices.size()) + return BEAGLE_ERROR_OUT_OF_RANGE; + setCudaDevice(); + + // Duplicates are summed; every row gets a (possibly zero) diagonal entry, which is harmless. + std::vector realValues(values, values + numNonZeros); + HostCsr D; + buildShiftedCsr(kPaddedStateCount, rowIndices, colIndices, realValues.data(), numNonZeros, Real(0), D); + + DerivativeMatrix& matrix = derivativeMatrices[matrixIndex]; + cudaDeviceDelete(matrix.offsets); + cudaDeviceDelete(matrix.columns); + cudaDeviceDelete(matrix.values); + matrix.offsets = cudaDeviceNew(kPaddedStateCount + 1); + matrix.columns = cudaDeviceNew(D.nonZeros()); + matrix.values = cudaDeviceNew(D.nonZeros()); + MemcpyHostToDevice(matrix.offsets, D.offsets.data(), kPaddedStateCount + 1); + MemcpyHostToDevice(matrix.columns, D.columns.data(), D.nonZeros()); + MemcpyHostToDevice(matrix.values, D.values.data(), D.nonZeros()); + matrix.eigenIndex = -1; + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::calculateEdgeDerivatives(const int* postBufferIndices, + const int* preBufferIndices, + const int* derivativeMatrixIndices, + const int* categoryWeightsIndices, + const int* categoryRatesIndices, + const int* cumulativeScaleIndices, + int count, + double* outDerivatives, + double* outSumDerivatives, + double* outSumSquaredDerivatives) +{ + if (count <= 0) + return BEAGLE_SUCCESS; + if (kCategoryCount > kMaxDerivativeCategories) + return BEAGLE_ERROR_NO_IMPLEMENTATION; + for (int node = 0; node < count; node++) { + const int d = derivativeMatrixIndices[node]; + if (d < 0 or d >= (int) derivativeMatrices.size() or + (derivativeMatrices[d].eigenIndex < 0 and derivativeMatrices[d].offsets == nullptr)) + return BEAGLE_ERROR_OUT_OF_RANGE; + for (int buffer: {postBufferIndices[node], preBufferIndices[node]}) + if (buffer < 0 or buffer >= kPartialsBufferCount or dPartials[buffer] == 0) + return BEAGLE_ERROR_OUT_OF_RANGE; + } + setCudaDevice(); + + if (not dDerivativeScratch) + dDerivativeScratch = cudaDeviceNew(cuda_edge_derivative_scratch_size(kPaddedStateCount, kCategoryCount, kPaddedPatternCount)); + // derivatives (count * kPatternCount), then the sums (count), then the sums of squares (count) + const size_t outputSize = (size_t) count * (kPatternCount + 2); + if (outputSize > derivativeOutputSize) { + cudaDeviceDelete(dDerivativeOutput); + dDerivativeOutput = cudaDeviceNew(outputSize); + derivativeOutputSize = outputSize; + } + Real* derivatives = dDerivativeOutput; + Real* sums = derivatives + (size_t) count * kPatternCount; + Real* sumSquares = sums + count; + + // As in the CPU implementation, the categories use rate set 0. + EdgeDerivativeBatch batch; + for (int c = 0; c < kCategoryCount; c++) + batch.categoryMultipliers[c] = (Real) hCategoryRates[0][c]; + const Real* categoryWeights = (const Real*) dWeights[categoryWeightsIndices[0]]; + + // Consecutive nodes with the same derivative matrix go in one batch. + for (int first = 0; first < count;) { + const int d = derivativeMatrixIndices[first]; + batch.count = 0; + while (first + batch.count < count and batch.count < kMaxEdgeDerivativeNodes and + derivativeMatrixIndices[first + batch.count] == d) { + batch.post[batch.count] = (const Real*) dPartials[postBufferIndices[first + batch.count]]; + batch.pre[batch.count] = (const Real*) dPartials[preBufferIndices[first + batch.count]]; + batch.count++; + } + const DerivativeMatrix& matrix = derivativeMatrices[d]; + const int e = matrix.eigenIndex; + // Q = B + mu I + const int* offsets = (e >= 0) ? dBs[e].offsets : matrix.offsets; + const int* columns = (e >= 0) ? dBs[e].inner : matrix.columns; + const Real* values = (e >= 0) ? dBs[e].values : matrix.values; + const Real shift = (e >= 0) ? hMuBs[e] : Real(0); + cuda_edge_derivatives(batch, kPaddedStateCount, kCategoryCount, kPaddedPatternCount, kPatternCount, + offsets, columns, values, shift, categoryWeights, (const Real*) dPatternWeights, + dDerivativeScratch, derivatives + (size_t) first * kPatternCount, sums + first, sumSquares + first, stream); + first += batch.count; + } + + hDerivativeOutput.resize(outputSize); + auto status = cudaMemcpyAsync(hDerivativeOutput.data(), dDerivativeOutput, outputSize * sizeof(Real), cudaMemcpyDeviceToHost, stream); + if (status == cudaSuccess) + status = cudaStreamSynchronize(stream); + if (status != cudaSuccess) + return BEAGLE_ERROR_GENERAL; + + const Real* h = hDerivativeOutput.data(); + if (outDerivatives) + std::copy(h, h + (size_t) count * kPatternCount, outDerivatives); + if (outSumDerivatives) + std::copy(h + (size_t) count * kPatternCount, h + (size_t) count * kPatternCount + count, outSumDerivatives); + if (outSumSquaredDerivatives) + std::copy(h + (size_t) count * (kPatternCount + 1), h + outputSize, outSumSquaredDerivatives); + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::calculateCrossProducts(const int* postBufferIndices, + const int* preBufferIndices, + const int* categoryRatesIndices, + const int* categoryWeightsIndices, + const double* edgeLengths, + int count, + double* outSumDerivatives, + double* outSumSquaredDerivatives) +{ + if (count <= 0) + return BEAGLE_SUCCESS; + if (kCategoryCount > kMaxDerivativeCategories) + return BEAGLE_ERROR_NO_IMPLEMENTATION; + for (int node = 0; node < count; node++) + for (int buffer: {postBufferIndices[node], preBufferIndices[node]}) + if (buffer < 0 or buffer >= kPartialsBufferCount or dPartials[buffer] == 0) + return BEAGLE_ERROR_OUT_OF_RANGE; + setCudaDevice(); + + // The pattern: the union of the patterns of the eigen indices that are set (normally they are all the same). + std::vector set; + for (int e = 0; e < kEigenDecompCount; e++) + if (not hBs[e].offsets.empty()) + set.push_back(e); + if (set.empty()) + return BEAGLE_ERROR_GENERAL; + const int n = kPaddedStateCount; + HostCsr pattern = hBs[set[0]]; + bool shared = true; + for (int e: set) + shared = shared and hBs[e].offsets == pattern.offsets and hBs[e].columns == pattern.columns; + if (not shared) { + std::vector> rows(n); + for (int e: set) + for (int i = 0; i < n; i++) + for (int k = hBs[e].offsets[i]; k < hBs[e].offsets[i + 1]; k++) + rows[i].insert(hBs[e].columns[k]); + pattern.offsets.assign(n + 1, 0); + pattern.columns.clear(); + for (int i = 0; i < n; i++) { + pattern.columns.insert(pattern.columns.end(), rows[i].begin(), rows[i].end()); + pattern.offsets[i + 1] = (int) pattern.columns.size(); + } + } + const int nnz = (int) pattern.columns.size(); + if ((size_t) nnz > crossCapacity) { + cudaDeviceDelete(dCrossColumns); + cudaDeviceDelete(dCrossValues); + dCrossColumns = cudaDeviceNew(nnz); + dCrossValues = cudaDeviceNew(nnz); + crossCapacity = nnz; + } + if (not dCrossOffsets) + dCrossOffsets = cudaDeviceNew(n + 1); + const int* offsets = shared ? dBs[set[0]].offsets : dCrossOffsets; + const int* columns = shared ? dBs[set[0]].inner : dCrossColumns; + if (not shared) { + MemcpyHostToDevice(dCrossOffsets, pattern.offsets.data(), n + 1); + MemcpyHostToDevice(dCrossColumns, pattern.columns.data(), nnz); + } + CHECK_CUDA(cudaMemsetAsync(dCrossValues, 0, nnz * sizeof(Real), stream)); + + // Per node: patternScale[p] = patternWeight[p] / sum_c w_c pre^T post, then the products scaled by w_c r_c t. + if (not dDerivativeScratch) + dDerivativeScratch = cudaDeviceNew(cuda_edge_derivative_scratch_size(kPaddedStateCount, kCategoryCount, kPaddedPatternCount)); + const size_t scaleSize = (size_t) kMaxEdgeDerivativeNodes * kPaddedPatternCount; + if (scaleSize > derivativeOutputSize) { + cudaDeviceDelete(dDerivativeOutput); + dDerivativeOutput = cudaDeviceNew(scaleSize); + derivativeOutputSize = scaleSize; + } + CHECK_CUDA(cudaMemsetAsync(dDerivativeOutput, 0, scaleSize * sizeof(Real), stream)); + + int ratesIndex = categoryRatesIndices ? categoryRatesIndices[0] : 0; + if (ratesIndex < 0 or ratesIndex >= kEigenDecompCount or hCategoryRates[ratesIndex] == nullptr) + ratesIndex = 0; + std::vector weights(kCategoryCount); + CHECK_CUDA(cudaMemcpyAsync(weights.data(), (const Real*) dWeights[categoryWeightsIndices[0]], kCategoryCount * sizeof(Real), + cudaMemcpyDeviceToHost, stream)); + CHECK_CUDA(cudaStreamSynchronize(stream)); + + EdgeDerivativeBatch batch; + for (int first = 0; first < count; first += batch.count) { + batch.count = std::min(count - first, kMaxEdgeDerivativeNodes); + for (int z = 0; z < batch.count; z++) { + batch.post[z] = (const Real*) dPartials[postBufferIndices[first + z]]; + batch.pre[z] = (const Real*) dPartials[preBufferIndices[first + z]]; + } + // Scales are written with stride kPatternCount; kPatternCount == kPaddedPatternCount for this plugin. + cuda_edge_derivatives(batch, kPaddedStateCount, kCategoryCount, kPaddedPatternCount, kPatternCount, + nullptr, nullptr, nullptr, Real(0), (const Real*) dWeights[categoryWeightsIndices[0]], + (const Real*) dPatternWeights, dDerivativeScratch, dDerivativeOutput, nullptr, nullptr, stream); + for (int z = 0; z < batch.count; z++) { + CategoryMultipliers multipliers; + for (int c = 0; c < kCategoryCount; c++) + multipliers.values[c] = weights[c] * (Real) (hCategoryRates[ratesIndex][c] * edgeLengths[first + z]); + cuda_cross_products(batch.pre[z], batch.post[z], kPaddedStateCount, kCategoryCount, kPaddedPatternCount, offsets, columns, + multipliers, dDerivativeOutput + (size_t) z * kPatternCount, dCrossValues, stream); + } + } + + std::vector values(nnz); + CHECK_CUDA(cudaMemcpyAsync(values.data(), dCrossValues, nnz * sizeof(Real), cudaMemcpyDeviceToHost, stream)); + CHECK_CUDA(cudaStreamSynchronize(stream)); + for (int i = 0; i < kStateCount; i++) + for (int k = pattern.offsets[i]; k < pattern.offsets[i + 1]; k++) + if (pattern.columns[k] < kStateCount) + outSumDerivatives[(size_t) i * kStateCount + pattern.columns[k]] += values[k]; + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::PrintfDeviceVector(int* dPtr, + int length, + double checkValue, + int *signal, + Real r) { + int* hPtr = (int*) malloc(sizeof(int) * length); + +// MemcpyDeviceToHost(hPtr, dPtr, sizeof(Real) * length); + CHECK_CUDA(cudaMemcpy(hPtr, dPtr, sizeof(int) * length, cudaMemcpyDeviceToHost)) + printfInt(hPtr, length); + + if (checkValue != -1) { + double sum = 0; + for(int i=0; i checkValue) && (hPtr[i]-checkValue > 1.0E-4)) { + fprintf(stderr,"Check value exception! (%d) %2.5d > %2.5e (diff = %2.5e)\n", + i,hPtr[i],checkValue, (hPtr[i]-checkValue)); + if( signal != 0 ) + *signal = 1; + } + if (hPtr[i] != hPtr[i]) { + fprintf(stderr,"NaN found!\n"); + if( signal != 0 ) + *signal = 1; + } + } + if (sum == 0) { + fprintf(stderr,"Zero-sum vector!\n"); + if( signal != 0 ) + *signal = 1; + } + } + free(hPtr); + return 0; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::PrintfDeviceVector(Real* dPtr, + int length, + double checkValue, + int *signal, + Real r) { + Real* hPtr = (Real*) malloc(sizeof(Real) * length); + +// MemcpyDeviceToHost(hPtr, dPtr, sizeof(Real) * length); + CHECK_CUDA(cudaMemcpy(hPtr, dPtr, sizeof(Real) * length, cudaMemcpyDeviceToHost)) + printfVector(hPtr, length); + + if (checkValue != -1) { + double sum = 0; + for(int i=0; i checkValue) && (hPtr[i]-checkValue > 1.0E-4)) { + fprintf(stderr,"Check value exception! (%d) %2.5e > %2.5e (diff = %2.5e)\n", + i,hPtr[i],checkValue, (hPtr[i]-checkValue)); + if( signal != 0 ) + *signal = 1; + } + if (hPtr[i] != hPtr[i]) { + fprintf(stderr,"NaN found!\n"); + if( signal != 0 ) + *signal = 1; + } + } + if (sum == 0) { + fprintf(stderr,"Zero-sum vector!\n"); + if( signal != 0 ) + *signal = 1; + } + } + free(hPtr); + return 0; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::PrintfDeviceVector(cusparseDnMatDescr_t dPtr, + int length, + double checkValue, + int *signal, + Real r) { + Real* hPtr = (Real*) malloc(sizeof(Real) * length); + +// MemcpyDeviceToHost(hPtr, dPtr, sizeof(Real) * length); +// CHECK_CUDA(cudaMemcpy(hPtr, dPtr, sizeof(Real) * length, cudaMemcpyDeviceToHost)) + CHECK_CUSPARSE(cusparseConstDnMatGetValues(dPtr, reinterpret_cast(hPtr))) + printfVector(hPtr, length); + + if (checkValue != -1) { + double sum = 0; + for(int i=0; i checkValue) && (hPtr[i]-checkValue > 1.0E-4)) { + fprintf(stderr,"Check value exception! (%d) %2.5e > %2.5e (diff = %2.5e)\n", + i,hPtr[i],checkValue, (hPtr[i]-checkValue)); + if( signal != 0 ) + *signal = 1; + } + if (hPtr[i] != hPtr[i]) { + fprintf(stderr,"NaN found!\n"); + if( signal != 0 ) + *signal = 1; + } + } + if (sum == 0) { + fprintf(stderr,"Zero-sum vector!\n"); + if( signal != 0 ) + *signal = 1; + } + } + free(hPtr); +} + +BEAGLE_GPU_TEMPLATE +void BeagleGPUActionImpl::setActionScratch(ActionGroup& group, size_t g) +{ + // With few patterns, the groups' blocks of the 3 scratch matrices are side by side (coalescing the gathers + // across groups); otherwise each group uses 2 contiguous blocks. See computeActions( ). + const size_t matrixSize = (size_t) kPaddedStateCount * kPaddedPatternCount; + const size_t scratchMatrixSize = (size_t) 2 * kCategoryCount * maxBatchOperations * matrixSize; + const bool interleaved = interleavedScratch(); + group.scratchStride = interleaved ? (int) (2 * kCategoryCount * maxBatchOperations * kPaddedPatternCount) : kPaddedPatternCount; + group.scratchCount = interleaved ? 3 : 2; + for (int k = 0; k < group.scratchCount; k++) + group.scratch[k] = dActionScratch + k * scratchMatrixSize + g * (interleaved ? kPaddedPatternCount : matrixSize); +} + +BEAGLE_GPU_TEMPLATE +void BeagleGPUActionImpl::calcPartialsPartials(const std::vector& operations, + Real* cumulativeScalingBuffer) { + const size_t matrixSize = (size_t) kPaddedStateCount * kPaddedPatternCount; + + // Each child's action goes to the action cache once pre-order is in use (unless the same child appears twice in + // this batch), otherwise to dActionResults. + std::vector groups; + std::vector actions(2 * operations.size()); + std::set cachedChildren; + for (size_t op = 0; op < operations.size(); op++) { + for (int child = 0; child < 2; child++) { + const int buffer = operations[op].children[child]; + const int edgeIndex = operations[op].edges[child]; + Real* out = nullptr; + if (cachedChildren.insert(buffer).second) + out = actionCacheSlot(buffer, edgeIndex); + if (not out) + out = dActionResults + (op * 2 + child) * kCategoryCount * matrixSize; + actions[op * 2 + child] = out; + for (int category = 0; category < kCategoryCount; category++) { + ActionGroup group; + group.in = (const Real*) dPartials[buffer] + category * matrixSize; + group.out = out + category * matrixSize; + setActionScratch(group, (op * 2 + child) * kCategoryCount + category); + group.eigenIndex = hEigenMaps[edgeIndex]; + group.multiplier = hEdgeMultipliers[edgeIndex * kCategoryCount + category]; + group.transpose = false; + groups.push_back(group); + } + } + } + computeActions(groups); + + // parent = left * right for all categories, then (optionally) rescale each pattern. + bool scalers_log = (kFlags & BEAGLE_FLAG_SCALERS_LOG)?true:false; + PartialsProductBatch products; + for (size_t op = 0; op < operations.size(); op++) { + auto& product = products.products[products.count++]; + product.left = actions[op * 2]; + product.right = actions[op * 2 + 1]; + product.parent = (Real*)dPartials[operations[op].destination]; + product.scalingFactors = operations[op].scalingFactors; + product.fixedScalingFactors = operations[op].fixedScalingFactors; + partialsGenerations[operations[op].destination]++; + } + cuda_partials_products(products, kCategoryCount * kPaddedStateCount, kPaddedPatternCount, + cumulativeScalingBuffer, scalers_log, dReductionScratch, stream); +} + +BEAGLE_GPU_TEMPLATE +void BeagleGPUActionImpl::calcPrePartials(const std::vector& operations, + Real* cumulativeScalingBuffer) { + const size_t matrixSize = (size_t) kPaddedStateCount * kPaddedPatternCount; + const size_t partialsSize = kCategoryCount * matrixSize; + // Per operation, two blocks of dActionResults: block 0 = the sibling's action o the parent, block 1 = the + // sibling's action when it is not cached, then the result before rescaling. + auto block = [&](size_t op, int k) { return dActionResults + (op * 2 + k) * partialsSize; }; + + // 1. The siblings' actions exp(t_sibling Q) sibling, from the cache when it is current. + std::vector groups; + std::vector siblingActions(operations.size()); + for (size_t op = 0; op < operations.size(); op++) { + const int sibling = operations[op].children[1]; + const int edgeIndex = operations[op].edges[1]; + if (actionCached(sibling, edgeIndex)) { + siblingActions[op] = actionCache[sibling].data; + continue; + } + siblingActions[op] = block(op, 1); + for (int category = 0; category < kCategoryCount; category++) { + ActionGroup group; + group.in = (const Real*) dPartials[sibling] + category * matrixSize; + group.out = block(op, 1) + category * matrixSize; + setActionScratch(group, (op * 2 + 1) * kCategoryCount + category); + group.eigenIndex = hEigenMaps[edgeIndex]; + group.multiplier = hEdgeMultipliers[edgeIndex * kCategoryCount + category]; + group.transpose = false; + groups.push_back(group); + } + } + computeActions(groups); + + // 2. sibling's action o parent's pre-order partials. + PartialsProductBatch products; + for (size_t op = 0; op < operations.size(); op++) { + auto& product = products.products[products.count++]; + product.left = siblingActions[op]; + product.right = (const Real*) dPartials[operations[op].children[0]]; + product.parent = block(op, 0); + product.scalingFactors = nullptr; + } + cuda_partials_products(products, kCategoryCount * kPaddedStateCount, kPaddedPatternCount, nullptr, false, + dReductionScratch, stream); + + // 3. exp(t Q^T) along the destination's edge; straight into the destination unless it is rescaled. + groups.clear(); + for (size_t op = 0; op < operations.size(); op++) { + const int edgeIndex = operations[op].edges[0]; + estimateTransposedNorms(hEigenMaps[edgeIndex]); + const bool scaled = operations[op].scalingFactors or operations[op].fixedScalingFactors; + Real* out = scaled ? block(op, 1) : (Real*) dPartials[operations[op].destination]; + for (int category = 0; category < kCategoryCount; category++) { + ActionGroup group; + group.in = block(op, 0) + category * matrixSize; + group.out = out + category * matrixSize; + setActionScratch(group, (op * 2) * kCategoryCount + category); + group.eigenIndex = hEigenMaps[edgeIndex]; + group.multiplier = hEdgeMultipliers[edgeIndex * kCategoryCount + category]; + group.transpose = true; + groups.push_back(group); + } + } + computeActions(groups); + + // 4. Rescale where requested, with new or existing scale factors. + bool scalers_log = (kFlags & BEAGLE_FLAG_SCALERS_LOG)?true:false; + products.count = 0; + for (size_t op = 0; op < operations.size(); op++) { + partialsGenerations[operations[op].destination]++; + if (not operations[op].scalingFactors and not operations[op].fixedScalingFactors) + continue; + auto& product = products.products[products.count++]; + product.left = block(op, 1); + product.right = nullptr; + product.parent = (Real*)dPartials[operations[op].destination]; + product.scalingFactors = operations[op].scalingFactors; + product.fixedScalingFactors = operations[op].fixedScalingFactors; + } + cuda_partials_products(products, kCategoryCount * kPaddedStateCount, kPaddedPatternCount, + cumulativeScalingBuffer, scalers_log, dReductionScratch, stream); +} + +BEAGLE_GPU_TEMPLATE +void BeagleGPUActionImpl::computeActions(const std::vector& groups) +{ + const size_t matrixSize = (size_t) kPaddedStateCount * kPaddedPatternCount; + + // exp(A) b = eta^s T_m(A/s)^s b, with A = multiplier * B (B = Q - mu I) and eta = exp(multiplier * mu / s). + // Each of the s steps evaluates b <- eta T_m(A/s) b by Horner's rule: + // w = b; for j = m .. 1: w = b + A/(s j) w; then b = eta w. + // A term reads w and b and writes a third matrix; the outputs of a step alternate between `result` (written + // by the last term, j = 1) and `other`. + // - With 3 scratch matrices, result and other are the two that are not b, except that the last term of the + // last step writes out. So the gathers read only scratch, whose groups are side by side. + // - With 2, out is also work space: the last step's result is out, and earlier steps write their results + // to scratch, so the last step's b is never out. This keeps the working set smaller (L2). + struct Schedule + { + const ActionGroup* group; + int nCols; + int m; + int s; + Real eta; + int step; + int term; + const Real* b; + const Real* w; + Real* result; + Real* other; + + int stride(const Real* matrix) const + { + for (int k = 0; k < group->scratchCount; k++) + if (matrix == group->scratch[k]) + return group->scratchStride; + return nCols; + } + + void startStep() + { + Real* free[2] = {nullptr, nullptr}; + int n = 0; + for (int k = 0; k < group->scratchCount; k++) + if (group->scratch[k] != b and n < 2) + free[n++] = group->scratch[k]; + if (group->scratchCount == 3) { + result = free[0]; + other = free[1]; + } else if (step == s - 1) { + result = group->out; + other = free[0]; + } else { + result = free[0]; + other = (n == 1) ? group->out : free[1]; + } + w = b; + term = m; + } + + Real* output() const + { + if (group->scratchCount == 3 and step == s - 1) + return (term == 1) ? group->out : (term % 2 == 0) ? result : other; + return (term % 2 == 1) ? result : other; + } + }; + + std::vector done(groups.size(), false); + for (size_t first = 0; first < groups.size(); first++) { + if (done[first]) + continue; + + // All the groups that share this group's matrix (B or B^T) run in lockstep: one launch per term. + const int eigenIndex = groups[first].eigenIndex; + const bool transpose = groups[first].transpose; + const auto& B = dBs[eigenIndex]; + const int* offsets = transpose ? dBtOffsets[eigenIndex] : B.offsets; + const int* columns = transpose ? dBtColumns[eigenIndex] : B.inner; + const Real* values = transpose ? dBtValues[eigenIndex] : B.values; + std::vector schedules; + for (size_t i = first; i < groups.size(); i++) { + if (done[i] or groups[i].eigenIndex != eigenIndex or groups[i].transpose != transpose) + continue; + done[i] = true; + const ActionGroup& group = groups[i]; + auto [m, s] = getStatistics2(1.0, kPaddedPatternCount, group.multiplier, eigenIndex, transpose); + if (m == 0) { + auto status = cudaMemcpyAsync(group.out, group.in, matrixSize * sizeof(Real), cudaMemcpyDeviceToDevice, stream); + if (status != cudaSuccess) + throw std::runtime_error(std::string("cudaMemcpyAsync: ") + cudaGetErrorString(status)); + continue; + } + Schedule schedule; + schedule.group = &group; + schedule.nCols = kPaddedPatternCount; + schedule.m = m; + schedule.s = s; + schedule.eta = exp(hMuBs[eigenIndex] * group.multiplier / s); + schedule.step = 0; + schedule.b = group.in; + schedule.startStep(); + schedules.push_back(schedule); + +#ifdef BEAGLE_DEBUG_FLOW + std::cerr << "action: m = " << m << " s = " << s << " multiplier = " << group.multiplier << " eigenIndex = " << eigenIndex << std::endl; +#endif + } + + for (bool active = true; active;) { + active = false; + TaylorTermBatch batch; + for (auto& schedule: schedules) { + if (schedule.step == schedule.s) + continue; + active = true; + + const int j = schedule.term; + Real* out = schedule.output(); + auto& term = batch.groups[batch.count++]; + term.x = schedule.w; + term.b = schedule.b; + term.out = out; + term.alpha = schedule.group->multiplier / ((Real) schedule.s * j); + term.scale = (j == 1) ? schedule.eta : 1; + term.ldx = schedule.stride(term.x); + term.ldb = schedule.stride(term.b); + term.ldOut = schedule.stride(term.out); + + if (batch.count == kMaxTaylorGroups) { + cuda_taylor_horner_terms(kPaddedStateCount, kPaddedPatternCount, offsets, columns, values, batch, stream); + batch.count = 0; + } + + schedule.w = out; + if (--schedule.term == 0) { + schedule.b = out; + if (++schedule.step < schedule.s) + schedule.startStep(); + } + } + cuda_taylor_horner_terms(kPaddedStateCount, kPaddedPatternCount, offsets, columns, values, batch, stream); + } + } +} + +BEAGLE_GPU_TEMPLATE +double BeagleGPUActionImpl::getPMax() const +{ + return floor(0.5 + 0.5 * sqrt(5.0 + 4.0 * mMax)); +} + +BEAGLE_GPU_TEMPLATE +double BeagleGPUActionImpl::getDValue(int p, int eigenIndex, bool transpose) const +{ + const auto& d = transpose ? hdsT[eigenIndex] : hds[eigenIndex]; + assert(p >= 0 and p < d.size()); + + return d[p]; +} + +std::ostream& showScalingInfo(std::ostream& o, std::uint64_t kFlags, const int* cumulativeScaleIndices, int kScaleBufferSize) +{ + int scale = 1; + if (kFlags & BEAGLE_FLAG_SCALING_AUTO) + ; + else if (kFlags & BEAGLE_FLAG_SCALING_ALWAYS) + ; + else if (cumulativeScaleIndices[0] != BEAGLE_OP_NONE) + ; + else + scale = 0; + + o<<"scale = "< +void gemv(cublasHandle_t handle, cublasOperation_t op, int size1, int size2, Real alpha, const Real* mat, int lda, const Real* vec, Real beta, Real* out) +{ + cublasStatus_t status; + + if constexpr (std::is_same::value) { + status = cublasSgemv(handle, op, + size1, size2, + &alpha, + mat, size1, //leading dimension + vec, 1, + &beta, + out, 1); + } + else + { + status = cublasDgemv(handle, op, + size1, size2, + &alpha, + mat, size1, //leading dimension + vec, 1, + &beta, + out, 1); + } + if (status != CUBLAS_STATUS_SUCCESS) + { + std::cerr<<"cublas error "<gemv( )."; + exit(1); + } +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::calculateRootLogLikelihoods(const int* bufferIndices, + const int* categoryWeightsIndices, + const int* stateFrequenciesIndices, + const int* cumulativeScaleIndices, + int count, + double* outSumLogLikelihood) { + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUActionImpl::calculateRootLogLikelihoods\n"); +#endif + + setCudaDevice(); + + int returnCode = BEAGLE_SUCCESS; + + const int rootNodeIndex = bufferIndices[0]; + const int categoryWeightsIndex = categoryWeightsIndices[0]; + const int stateFrequenciesIndex = stateFrequenciesIndices[0]; + + const Real* dCumulativeScalingFactor = nullptr; + bool scale = 1; + if (kFlags & BEAGLE_FLAG_SCALING_AUTO) + dCumulativeScalingFactor = (const Real*)dAccumulatedScalingFactors; + else if (kFlags & BEAGLE_FLAG_SCALING_ALWAYS) + dCumulativeScalingFactor = (const Real*)dScalingFactors[bufferIndices[0] - kTipCount]; + else if (cumulativeScaleIndices[0] != BEAGLE_OP_NONE) + dCumulativeScalingFactor = (const Real*)dScalingFactors[cumulativeScaleIndices[0]]; + else + scale = 0; + +#ifdef BEAGLE_DEBUG_VALUES + std::cerr<<"root partials = "<::createInstance + // scaling factor is char?? -- see BeagleGPUImpl<>::createInstance + // scaling factor is int?? -- see KernelIntegrateLikelihoodsAutoScaling + // See kernelIntegrateLikelihoodsAutoScaling in KernelsX.cu + std::cerr<<"BeagleGPUActionImpl< >::calculateRootLogLikelihoods -- FLAG_SCALING_AUTO not implemented!"; + std::abort(); + } + + Real* siteLogLikelihoods = (Real*)dIntegrationTmp; + Real* rootPartials = (Real*)dPartials[rootNodeIndex]; + Real* categoryWeights = (Real*)dWeights[categoryWeightsIndex]; + Real* stateFrequencies = (Real*)dFrequencies[stateFrequenciesIndex]; // these really should be category-dependent + + // siteLogLikelihoods[pattern] = log( sum_{category,state} likelihood(category,state,pattern) * categoryWeights[category] * statesFrequencies[state] ) + // + scaling factor + // dSumLogLikelihood[0] = sum_{pattern} patternWeights[pattern] * siteLogLikelihoods[pattern] + cuda_root_log_likelihoods(rootPartials, categoryWeights, stateFrequencies, scale ? dCumulativeScalingFactor : nullptr, + (Real*)dPatternWeights, kPaddedStateCount, kPaddedPatternCount, kPatternCount, kCategoryCount, + dReductionScratch, siteLogLikelihoods, (Real*)dSumLogLikelihood, stream); + +#ifdef BEAGLE_DEBUG_VALUES + std::cerr<<"site log likelihoods = "<PrintfDeviceVector(dIntegrationTmp, kPatternCount, r); +#endif + + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUActionImpl::calculateRootLogLikelihoods\n"); +#endif + + return returnCode; +} + + +BEAGLE_GPU_TEMPLATE +std::tuple BeagleGPUActionImpl::getStatistics2(double t, int nCol, + double edgeMultiplier, + int eigenIndex, bool transpose) const { + assert( t >= 0 ); + assert( nCol >= 0); + assert( edgeMultiplier >= 0 ); + assert( eigenIndex >= 0); + + const double norm1 = transpose ? hBt1Norms[eigenIndex] : hB1Norms[eigenIndex]; + + if (t * norm1 == 0.0) + return {0, 1}; + + int bestM = INT_MAX; + double bestS = INT_MAX; // Not all the values of s can fit in a 32-bit int. + + const double pMax = getPMax(); + // pMax is the largest positive integer such that p*(p-1) <= mMax + 1 + + // 1. The best (m,s) based only on ||B||_1 (in some sense the result for p=1). + for (auto& [thisM, thetaM]: thetaConstants) { + const double thisS = ceil(norm1 * edgeMultiplier / thetaM); + if (bestM == INT_MAX || ((double) thisM) * thisS < bestM * bestS) { + bestS = thisS; + bestM = thisM; + } + } + + // 2. Improve on it with the d_p. Condition 3.13 of Al-Mohy and Higham only decides whether computing + // the d_p is worth it; setSparseMatrix( ) has already computed all of them, so always use them + // (as the CPU implementation does once they are available). + for (int p = 2; p <= pMax; p++) { + for (int thisM = p * (p - 1) - 1; thisM < mMax + 1; thisM++) { + auto it = thetaConstants.find(thisM); + if (it != thetaConstants.end()) { + // equation 3.7 in Al-Mohy and Higham + const double dValueP = getDValue(p, eigenIndex, transpose); + const double dValuePPlusOne = getDValue(p + 1, eigenIndex, transpose); + const double alpha = std::max(dValueP, dValuePPlusOne) * edgeMultiplier; + // part of equation 3.10 + const double thisS = ceil(alpha / thetaConstants.at(thisM)); + if (bestM == INT_MAX || ((double) thisM) * thisS < bestM * bestS) { + bestS = thisS; + bestM = thisM; + } + } + } + } + bestS = std::max(std::min(bestS, INT_MAX), 1.0); + assert( bestS >= 1 ); + assert( bestS <= INT_MAX ); + + int m = bestM; + int s = (int) bestS; + + assert(m >= 0); + assert(s >= 1); + + return {m,s}; +} + + +BEAGLE_GPU_TEMPLATE +int BeagleGPUActionImpl::setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const Real* values, + int numNonZeros) +{ + setCudaDevice(); + + // mu = trace(Q) / kStateCount (duplicate triplets are summed) + Real mu_B = 0.0; + for (int k = 0; k < numNonZeros; k++) { + if (rowIndices[k] == colIndices[k] and rowIndices[k] < kStateCount) + mu_B += values[k]; + } + mu_B /= (Real) kStateCount; + + hMuBs[matrixIndex] = mu_B; + auto& builder = csrBuilders[matrixIndex]; + const bool structureChanged = builder.build(kPaddedStateCount, rowIndices, colIndices, values, numNonZeros, mu_B, hBs[matrixIndex]); + hB1Norms[matrixIndex] = normP1(kPaddedStateCount, hBs[matrixIndex]); + hBt1Norms[matrixIndex] = normPInf(kPaddedStateCount, hBs[matrixIndex]); + hdsTCurrent[matrixIndex] = false; + qGenerations[matrixIndex]++; + derivativeMatrices[matrixIndex].eigenIndex = matrixIndex; + +#ifdef BEAGLE_DEBUG_FLOW + std::cerr<<"B "<(currentNNZ); + dBsCsrValuesCache[matrixIndex] = cudaDeviceNew(currentNNZ); + } + cudaDeviceDelete(dBtColumns[matrixIndex]); + cudaDeviceDelete(dBtSlots[matrixIndex]); + cudaDeviceDelete(dBtValues[matrixIndex]); + dBtColumns[matrixIndex] = cudaDeviceNew(currentNNZ); + dBtSlots[matrixIndex] = cudaDeviceNew(currentNNZ); + dBtValues[matrixIndex] = cudaDeviceNew(currentNNZ); + + MemcpyHostToDevice(dBsCsrOffsetsCache[matrixIndex], hBs[matrixIndex].offsets.data(), kPaddedStateCount + 1); + MemcpyHostToDevice(dBsCsrColumnsCache[matrixIndex], hBs[matrixIndex].columns.data(), currentNNZ); + MemcpyHostToDevice(dBtOffsets[matrixIndex], builder.transposeOffsets.data(), kPaddedStateCount + 1); + MemcpyHostToDevice(dBtColumns[matrixIndex], builder.transposeColumns.data(), currentNNZ); + MemcpyHostToDevice(dBtSlots[matrixIndex], builder.transposeSlot.data(), currentNNZ); + + dBs[matrixIndex] = SpMatrixDevice(cublasHandle, cusparseHandle, + kPaddedStateCount, kPaddedStateCount, + currentNNZ, + dBsCsrValuesCache[matrixIndex], + dBsCsrColumnsCache[matrixIndex], + dBsCsrOffsetsCache[matrixIndex], + sparseFormat::csr); + } + MemcpyHostToDevice(dBsCsrValuesCache[matrixIndex], hBs[matrixIndex].values.data(), currentNNZ); + cuda_gather(dBsCsrValuesCache[matrixIndex], dBtSlots[matrixIndex], currentNNZ, dBtValues[matrixIndex], stream); + +#ifdef BEAGLE_DEBUG_FLOW + + std::cerr<<"\ndBsCsrOffsetsCache for "<< matrixIndex <<"="<::updateTransitionMatrices(int eigenIndex, + const int* probabilityIndices, + const int* firstDerivativeIndices, + const int* secondDerivativeIndices, + const Real* edgeLengths, + int count) +{ + for (int i = 0; i < count; i++) { + const int nodeIndex = probabilityIndices[i]; + hEigenMaps[nodeIndex] = eigenIndex; + matrixGenerations[nodeIndex]++; + + for (int category = 0; category < kCategoryCount; category++) { + const double categoryRate = hCategoryRates[0][category]; // XJ: because rate categories are only set for first eigen index + hEdgeMultipliers[nodeIndex * kCategoryCount + category] = edgeLengths[i] * categoryRate; + } + } + // TODO: check if need to copy it from host to device afterwards + return BEAGLE_SUCCESS; +} + +///-------------------------------- Factory -------------------------------------/// +BEAGLE_GPU_TEMPLATE +BeagleImpl* BeagleGPUActionImplFactory::createImpl(int tipCount, + int partialsBufferCount, + int compactBufferCount, + int stateCount, + int patternCount, + int eigenBufferCount, + int matrixBufferCount, + int categoryCount, + int scaleBufferCount, + int resourceNumber, + int pluginResourceNumber, + long long preferenceFlags, + long long requirementFlags, + int* errorCode) { + BeagleImpl * impl = new BeagleGPUActionImpl(); + try { + *errorCode = + impl->createInstance(tipCount, partialsBufferCount, compactBufferCount, stateCount, + patternCount, eigenBufferCount, matrixBufferCount, + categoryCount,scaleBufferCount, resourceNumber, pluginResourceNumber, preferenceFlags, requirementFlags); + if (*errorCode == BEAGLE_SUCCESS) { + return impl; + } + delete impl; + return NULL; + } + catch(...) + { + delete impl; + *errorCode = BEAGLE_ERROR_GENERAL; + throw; + } + delete impl; + *errorCode = BEAGLE_ERROR_GENERAL; + return NULL; +} + +#ifdef CUDA +template<> +const char* BeagleGPUActionImplFactory::getName() { + return "GPU-DP-CUDA-Action"; +} + +template<> +const char* BeagleGPUActionImplFactory::getName() { + return "GPU-SP-CUDA-Action"; +} +#elif defined(FW_OPENCL) +template<> +const char* BeagleGPUActionImplFactory::getName() { + return "DP-OpenCL-Action"; + +} +template<> +const char* BeagleGPUActionImplFactory::getName() { + return "SP-OpenCL-Action"; +} +#endif + +BEAGLE_GPU_TEMPLATE +long long BeagleGPUActionImplFactory::getFlags() { + return BeagleGPUImplFactory::getFlags() | BEAGLE_FLAG_COMPUTATION_ACTION; +} + +} // end of device namespace +} // end of gpu namespace +} // end of beagle namespace + + +#endif diff --git a/libhmsbeagle/GPU/BeagleGPUImpl.h b/libhmsbeagle/GPU/BeagleGPUImpl.h old mode 100644 new mode 100755 index d2761d884..a11c2c72e --- a/libhmsbeagle/GPU/BeagleGPUImpl.h +++ b/libhmsbeagle/GPU/BeagleGPUImpl.h @@ -5,21 +5,10 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . - * - * * @brief GPU implementation header * * @author Marc Suchard @@ -63,14 +52,14 @@ BEAGLE_GPU_TEMPLATE class BeagleGPUImpl : public BeagleImpl { -private: +protected: GPUInterface* gpu; KernelLauncher* kernels; - + int kInitialized; long long kFlags; - + int kTipCount; int kPartialsBufferCount; int kCompactBufferCount; @@ -79,17 +68,17 @@ class BeagleGPUImpl : public BeagleImpl { int kEigenDecompCount; int kMatrixCount; int kCategoryCount; - + int kTipPartialsBufferCount; int kInternalPartialsBufferCount; int kBufferCount; int kScaleBufferCount; - + int kPaddedStateCount; int kPaddedPatternCount; // total # of patterns with padding so that kPaddedPatternCount // * kPaddedStateCount is a multiple of 16 int kSumSitesBlockCount; - + int kPartialsSize; int kMatrixSize; int kEigenValuesSize; @@ -99,54 +88,54 @@ class BeagleGPUImpl : public BeagleImpl { int kLastTipPartialsBufferIndex; int kResultPaddedPatterns; - + GPUPtr dIntegrationTmp; GPUPtr dOutFirstDeriv; GPUPtr dOutSecondDeriv; GPUPtr dPartialsTmp; GPUPtr dFirstDerivTmp; GPUPtr dSecondDerivTmp; - + GPUPtr dSumLogLikelihood; GPUPtr dSumFirstDeriv; GPUPtr dSumSecondDeriv; GPUPtr dMultipleDerivatives; GPUPtr dMultipleDerivativeSum; - - GPUPtr dPatternWeights; - + + GPUPtr dPatternWeights; + GPUPtr dBranchLengths; - + GPUPtr dDistanceQueue; - + GPUPtr dPtrQueue; GPUPtr dDerivativeQueue; - + GPUPtr dMaxScalingFactors; GPUPtr dIndexMaxScalingFactors; - + GPUPtr dAccumulatedScalingFactors; - + GPUPtr* dEigenValues; GPUPtr* dEvec; GPUPtr* dIevc; - + GPUPtr* dWeights; - GPUPtr* dFrequencies; + GPUPtr* dFrequencies; GPUPtr* dScalingFactors; - + GPUPtr* dStates; - + GPUPtr* dPartials; GPUPtr* dMatrices; GPUPtr dMatricesOrigin; GPUPtr* dCompactBuffers; GPUPtr* dTipPartialsBuffers; - + bool kUsingMultiGrid; bool kDerivBuffersInitialised; int kMultipleDerivativesLength; // TODO Change to length (max node count used) @@ -202,32 +191,59 @@ class BeagleGPUImpl : public BeagleImpl { unsigned int* hPtrQueue; unsigned int* hDerivativeQueue; - + double** hCategoryRates; // Can keep in double-precision Real* hPatternWeightsCache; - + Real* hDistanceQueue; - + Real* hWeightsCache; Real* hFrequenciesCache; Real* hLogLikelihoodsCache; Real* hPartialsCache; int* hStatesCache; Real* hMatrixCache; - + int* hRescalingTrigger; GPUPtr dRescalingTrigger; - + GPUPtr* dScalingFactorsMaster; - + int* hStreamIndices; -public: + GPUPtr dBastaBuffers; + GPUPtr dBastaBlockResMemory; + GPUPtr dBastaFinalResMemory; + GPUPtr dBastaMemory; + GPUPtr dBlockSegmentKeysEnd; + GPUPtr dBastaLogL; + GPUPtr dBastaDistance; + GPUPtr dBastaOperationQueue; + GPUPtr dCoalescentBuffers; + GPUPtr dBastaInterval; + GPUPtr dBastaFlags; + int kCoalescentBufferLength; + int kCoalescentBufferCount; + int kBastaIntervalBlockCount; + + + Real* hBastaOperationQueue; + Real* hBastaSubintervals; + Real* hBastaFinalKeys; + Real* hBastaFinalSubintervals; + Real* hBastaInterval; + Real* hBastaLogL; + Real* hBastaDistance; + Real* hBastazeroes; + Real* hBastaFinalResMemory; + Real* hBastaMemory; + +public: BeagleGPUImpl(); - + virtual ~BeagleGPUImpl(); - + int createInstance(int tipCount, int partialsBufferCount, int compactBufferCount, @@ -241,7 +257,7 @@ class BeagleGPUImpl : public BeagleImpl { int pluginResourceNumber, long long preferenceFlags, long long requirementFlags); - + int getInstanceDetails(BeagleInstanceDetails* retunInfo); int setCPUThreadCount(int threadCount); @@ -255,47 +271,59 @@ class BeagleGPUImpl : public BeagleImpl { int setRootPrePartials(const int* bufferIndices, const int* stateFrequenciesIndices, int count); - + int setPartials(int bufferIndex, const double* inPartials); - + int getPartials(int bufferIndex, int scaleIndex, double* outPartials); - + int setEigenDecomposition(int eigenIndex, const double* inEigenVectors, const double* inInverseEigenVectors, const double* inEigenValues); + + int setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros); + + int setSparseDifferentialMatrix(int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros); int setStateFrequencies(int stateFrequenciesIndex, - const double* inStateFrequencies); - + const double* inStateFrequencies); + int setCategoryWeights(int categoryWeightsIndex, const double* inCategoryWeights); - + int setPatternWeights(const double* inPatternWeights); int setPatternPartitions(int partitionCount, const int* inPatternPartitions); - + int setCategoryRates(const double* inCategoryRates); int setCategoryRatesWithIndex(int categoryRatesIndex, const double* inCategoryRates); - + int setTransitionMatrix(int matrixIndex, const double* inMatrix, double paddedValue); int setDifferentialMatrix(int matrixIndex, const double* inMatrix); - + int setTransitionMatrices(const int* matrixIndices, const double* inMatrices, const double* paddedValues, - int count); - + int count); + int getTransitionMatrix(int matrixIndex, double* outMatrix); @@ -319,6 +347,10 @@ class BeagleGPUImpl : public BeagleImpl { const int* secondDerivativeIndices, const double* edgeLengths, int count); + + int updateTransitionMatricesGrad(const int* probabilityIndices, + const double* edgeLengths, + int count); int updateTransitionMatricesWithModelCategories(int* eigenIndices, const int* probabilityIndices, @@ -334,7 +366,7 @@ class BeagleGPUImpl : public BeagleImpl { const int* secondDerivativeIndices, const double* edgeLengths, int count); - + int updatePartials(const int* operations, int operationCount, int cumulativeScalingIndex); @@ -375,7 +407,7 @@ class BeagleGPUImpl : public BeagleImpl { int waitForPartials(const int* destinationPartials, int destinationPartialsCount); - + int accumulateScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex); @@ -384,7 +416,7 @@ class BeagleGPUImpl : public BeagleImpl { int count, int cumulativeScalingIndex, int partitionIndex); - + int removeScaleFactors(const int* scalingIndices, int count, int cumulativeScalingIndex); @@ -393,17 +425,17 @@ class BeagleGPUImpl : public BeagleImpl { int count, int cumulativeScalingIndex, int partitionIndex); - + int resetScaleFactors(int cumulativeScalingIndex); int resetScaleFactorsByPartition(int cumulativeScalingIndex, int partitionIndex); - + int copyScaleFactors(int destScalingIndex, int srcScalingIndex); - + int getScaleFactors(int srcScalingIndex, - double* scaleFactors); - + double* scaleFactors); + int calculateRootLogLikelihoods(const int* bufferIndices, const int* categoryWeightsIndices, const int* stateFrequenciesIndices, @@ -420,7 +452,7 @@ class BeagleGPUImpl : public BeagleImpl { int count, double* outSumLogLikelihoodByPartition, double* outSumLogLikelihood); - + int calculateEdgeLogLikelihoods(const int* parentBufferIndices, const int* childBufferIndices, const int* probabilityIndices, @@ -467,10 +499,50 @@ class BeagleGPUImpl : public BeagleImpl { double* outSumSecondDerivative); int getSiteLogLikelihoods(double* outLogLikelihoods); - + int getSiteDerivatives(double* outFirstDerivatives, double* outSecondDerivatives); + int updateInnerBastaPartials(const int * operations, const int * intervals, int i, int begin, int end, GPUPtr sizes, GPUPtr coalescent); + + int updateBastaPartials(const int* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex); + + int updateBastaPartialsGrad(const int* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex); + + int accumulateBastaPartials(const int* operations, + int operationCount, + const int* segments, + int segmentCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out); + + int accumulateBastaPartialsGrad(const int *operations, + const int operationCount, + const int *intervalStarts, + const int intervalStartsCount, + const double *intervalLengths, + const int populationSizesIndex, + const int coalescentIndex, + double *out); + + int allocateBastaBuffers(int bufferCount, + int bufferLength); + + int getBastaBuffer(int bufferIndex, + double* out); + private: char* getInstanceName(); diff --git a/libhmsbeagle/GPU/BeagleGPUImpl.hpp b/libhmsbeagle/GPU/BeagleGPUImpl.hpp old mode 100644 new mode 100755 index 12ee74bf9..42ed0e353 --- a/libhmsbeagle/GPU/BeagleGPUImpl.hpp +++ b/libhmsbeagle/GPU/BeagleGPUImpl.hpp @@ -7,19 +7,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Andrew Rambaut @@ -44,6 +34,7 @@ #include "libhmsbeagle/GPU/GPUInterface.h" #include "libhmsbeagle/GPU/Precision.h" #include "BeagleGPUImpl.h" +#include "libhmsbeagle/benchmark/BenchmarkHelper.h" namespace beagle { namespace gpu { @@ -53,9 +44,8 @@ namespace gpu { #else namespace opencl { #endif - -BEAGLE_GPU_TEMPLATE -BeagleGPUImpl::BeagleGPUImpl() { + BEAGLE_GPU_TEMPLATE + BeagleGPUImpl::BeagleGPUImpl() { gpu = NULL; kernels = NULL; @@ -87,6 +77,16 @@ BeagleGPUImpl::BeagleGPUImpl() { dMaxScalingFactors = (GPUPtr)NULL; dIndexMaxScalingFactors = (GPUPtr)NULL; + + dBastaMemory = (GPUPtr)NULL; + dBastaBlockResMemory = (GPUPtr)NULL; + dBastaFinalResMemory = (GPUPtr)NULL; + dBastaLogL = (GPUPtr)NULL; + dBastaDistance = (GPUPtr)NULL; + dBastaOperationQueue = (GPUPtr)NULL; + dCoalescentBuffers = (GPUPtr)NULL; + dBastaInterval = (GPUPtr)NULL; + dBastaFlags = (GPUPtr)NULL; dEigenValues = NULL; dEvec = NULL; dIevc = NULL; @@ -123,6 +123,16 @@ BeagleGPUImpl::BeagleGPUImpl() { dRescalingTrigger = (GPUPtr)NULL; dScalingFactorsMaster = NULL; + hBastaOperationQueue = NULL; + hBastaSubintervals = NULL; + hBastaFinalKeys = NULL; + hBastaFinalSubintervals = NULL; + hBastaMemory = NULL; + hBastaInterval = NULL; + hBastaLogL = NULL; + hBastaDistance = NULL; + hBastazeroes = NULL; + hBastaFinalResMemory = NULL; } BEAGLE_GPU_TEMPLATE @@ -136,10 +146,13 @@ BeagleGPUImpl::~BeagleGPUImpl() { } // TODO: free subpointers - gpu->FreeMemory(dMatrices[0]); // TODO Should try: gpu->FreeMemory(dMatricesOrigin); instead of above - gpu->FreeMemory(dEigenValues[0]); // TODO Here is where my Mac / Intel-GPU are throwing bad-exception - gpu->FreeMemory(dEvec[0]); // TODO Should be save and then release just d*Origin? - gpu->FreeMemory(dIevc[0]); + if (kMatrixCount > 0 && dMatrices[0]) + gpu->FreeMemory(dMatrices[0]); // TODO Should try: gpu->FreeMemory(dMatricesOrigin); instead of above + if(dEigenValues) { + gpu->FreeMemory(dEigenValues[0]); // TODO Here is where my Mac / Intel-GPU are throwing bad-exception + gpu->FreeMemory(dEvec[0]); // TODO Should be save and then release just d*Origin? + gpu->FreeMemory(dIevc[0]); + } gpu->FreeMemory(dWeights[0]); gpu->FreeMemory(dFrequencies[0]); @@ -254,6 +267,16 @@ BeagleGPUImpl::~BeagleGPUImpl() { free(hPartialsOffsets); free(hStatesOffsets); + + gpu->FreeMemory(dBastaBlockResMemory); + gpu->FreeMemory(dBastaFinalResMemory); + gpu->FreeMemory(dBastaMemory); + gpu->FreeMemory(dBastaLogL); + gpu->FreeMemory(dBastaDistance); + gpu->FreeMemory(dBastaOperationQueue); + gpu->FreeMemory(dBastaInterval); + gpu->FreeMemory(dBastaFlags); + gpu->FreeHostMemory(hPtrQueue); gpu->FreeHostMemory(hDerivativeQueue); @@ -270,6 +293,16 @@ BeagleGPUImpl::~BeagleGPUImpl() { gpu->FreeHostMemory(hLogLikelihoodsCache); gpu->FreeHostMemory(hMatrixCache); + gpu->FreeHostMemory(hBastaOperationQueue); + gpu->FreeHostMemory(hBastaSubintervals); + gpu->FreeHostMemory(hBastaFinalKeys); + gpu->FreeHostMemory(hBastaInterval); + gpu->FreeHostMemory(hBastaLogL); + gpu->FreeHostMemory(hBastaDistance); + gpu->FreeHostMemory(hBastaFinalSubintervals); + gpu->FreeHostMemory(hBastaMemory); + gpu->FreeHostMemory(hBastazeroes); + gpu->FreeHostMemory(hBastaFinalResMemory); } if (kernels) @@ -343,7 +376,7 @@ int BeagleGPUImpl::createInstance(int tipCount, } else if (kStateCount <= 256) { kPaddedStateCount = 256; } else { - kPaddedStateCount = kStateCount + kStateCount % 16; + kPaddedStateCount = kStateCount % 16 == 0 ? kStateCount : kStateCount + 16 - kStateCount % 16; } gpu = new GPUInterface(); @@ -568,25 +601,39 @@ int BeagleGPUImpl::createInstance(int tipCount, int hMatrixCacheSize = kMatrixSize * kCategoryCount * BEAGLE_CACHED_MATRICES_COUNT; if ((2 * kMatrixSize + kEigenValuesSize) > hMatrixCacheSize) hMatrixCacheSize = 2 * kMatrixSize + kEigenValuesSize; + // Action-based instances never form dense transition matrices. + if (preferenceFlags & BEAGLE_FLAG_COMPUTATION_ACTION) + hMatrixCacheSize = kEigenValuesSize; hLogLikelihoodsCache = (Real*) gpu->MallocHost(kPatternCount * sizeof(Real)); hMatrixCache = (Real*) gpu->CallocHost(hMatrixCacheSize, sizeof(Real)); - dEvec = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); - dIevc = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); - dEigenValues = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); + if (preferenceFlags & BEAGLE_FLAG_COMPUTATION_ACTION) { + dEvec = nullptr; + dIevc = nullptr; + dEigenValues = nullptr; + } else { + dEvec = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); + dIevc = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); + dEigenValues = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); + } dWeights = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); dFrequencies = (GPUPtr*) calloc(sizeof(GPUPtr),kEigenDecompCount); - dMatrices = (GPUPtr*) malloc(sizeof(GPUPtr) * kMatrixCount); + // Fill with 0s so 'free' does not choke if unallocated + dMatrices = (GPUPtr*) calloc(sizeof(GPUPtr), kMatrixCount); size_t ptrIncrement = gpu->AlignMemOffset(kMatrixSize * kCategoryCount * sizeof(Real)); kIndexOffsetMat = ptrIncrement/sizeof(Real); - dMatricesOrigin = gpu->AllocateMemory(kMatrixCount * ptrIncrement); - for (int i = 0; i < kMatrixCount; i++) { - dMatrices[i] = gpu->CreateSubPointer(dMatricesOrigin, ptrIncrement*i, ptrIncrement); + if (preferenceFlags & BEAGLE_FLAG_COMPUTATION_ACTION) { + // O(S^2) per matrix: exhausts device memory for large state spaces, and is unused by action. + dMatricesOrigin = (GPUPtr) NULL; + } else { + dMatricesOrigin = gpu->AllocateMemory(kMatrixCount * ptrIncrement); + for (int i = 0; i < kMatrixCount; i++) { + dMatrices[i] = gpu->CreateSubPointer(dMatricesOrigin, ptrIncrement*i, ptrIncrement); + } } - if (kScaleBufferCount > 0) { if (kFlags & BEAGLE_FLAG_SCALING_AUTO) { dScalingFactors = (GPUPtr*) malloc(sizeof(GPUPtr) * kScaleBufferCount); @@ -620,22 +667,26 @@ int BeagleGPUImpl::createInstance(int tipCount, } } - ptrIncrement = gpu->AlignMemOffset(kMatrixSize * sizeof(Real)); - kEvecOffset = ptrIncrement/sizeof(Real); - GPUPtr dEvecOrigin = gpu->AllocateMemory(kEigenDecompCount * ptrIncrement); - GPUPtr dIevcOrigin = gpu->AllocateMemory(kEigenDecompCount * ptrIncrement); - for(int i=0; iCreateSubPointer(dEvecOrigin, ptrIncrement*i, ptrIncrement); - dIevc[i] = gpu->CreateSubPointer(dIevcOrigin, ptrIncrement*i, ptrIncrement); - } + if(! (preferenceFlags & BEAGLE_FLAG_COMPUTATION_ACTION)) { + ptrIncrement = gpu->AlignMemOffset(kMatrixSize * sizeof(Real)); + kEvecOffset = ptrIncrement/sizeof(Real); + GPUPtr dEvecOrigin = gpu->AllocateMemory(kEigenDecompCount * ptrIncrement); + GPUPtr dIevcOrigin = gpu->AllocateMemory(kEigenDecompCount * ptrIncrement); + for(int i=0; iCreateSubPointer(dEvecOrigin, ptrIncrement*i, ptrIncrement); + dIevc[i] = gpu->CreateSubPointer(dIevcOrigin, ptrIncrement*i, ptrIncrement); + } + + ptrIncrement = gpu->AlignMemOffset(kEigenValuesSize * sizeof(Real)); + kEvalOffset = ptrIncrement/sizeof(Real); + GPUPtr dEigenValuesOrigin = gpu->AllocateMemory(kEigenDecompCount * ptrIncrement); + for(int i=0; iCreateSubPointer(dEigenValuesOrigin, ptrIncrement*i, ptrIncrement); + } - ptrIncrement = gpu->AlignMemOffset(kEigenValuesSize * sizeof(Real)); - kEvalOffset = ptrIncrement/sizeof(Real); - GPUPtr dEigenValuesOrigin = gpu->AllocateMemory(kEigenDecompCount * ptrIncrement); - for(int i=0; iCreateSubPointer(dEigenValuesOrigin, ptrIncrement*i, ptrIncrement); } + ptrIncrement = gpu->AlignMemOffset(kCategoryCount * sizeof(Real)); kWeightsOffset = ptrIncrement/sizeof(Real); GPUPtr dWeightsOrigin = gpu->AllocateMemory(kEigenDecompCount * ptrIncrement); @@ -726,7 +777,7 @@ int BeagleGPUImpl::createInstance(int tipCount, const int distanceQueueLength = std::max( kMatrixCount * kCategoryCount * 2, // for transition matrices kMatrixCount + kCategoryCount); // for cross-products - + dDistanceQueue = gpu->AllocateMemory(distanceQueueLength * sizeof(Real)); hDistanceQueue = (Real*) gpu->MallocHost(distanceQueueLength * sizeof(Real)); checkHostMemory(hDistanceQueue); @@ -754,13 +805,13 @@ int BeagleGPUImpl::createInstance(int tipCount, kUsingMultiGrid = false; - if (kPaddedStateCount == 4 && + if (kPaddedStateCount == 4 && (kDeviceType == BEAGLE_FLAG_PROCESSOR_CPU || #ifdef FW_OPENCL kDeviceCode == BEAGLE_OPENCL_DEVICE_AMD_GPU || -#endif - kPaddedPatternCount < BEAGLE_MULTI_GRID_MAX || - kFlags & BEAGLE_FLAG_PARALLELOPS_GRID) && +#endif + kPaddedPatternCount < BEAGLE_MULTI_GRID_MAX || + kFlags & BEAGLE_FLAG_PARALLELOPS_GRID) && !(kFlags & BEAGLE_FLAG_PARALLELOPS_STREAMS)) { kUsingMultiGrid = true; allocateMultiGridBuffers(); @@ -1151,6 +1202,24 @@ int BeagleGPUImpl::setEigenDecomposition(int eigenIndex, return BEAGLE_SUCCESS; } +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::setSparseMatrix(int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros) { + return BEAGLE_ERROR_NO_IMPLEMENTATION; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::setSparseDifferentialMatrix(int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros) { + return BEAGLE_ERROR_NO_IMPLEMENTATION; +} + BEAGLE_GPU_TEMPLATE int BeagleGPUImpl::setStateFrequencies(int stateFrequenciesIndex, const double* inStateFrequencies) { @@ -1897,6 +1966,14 @@ int BeagleGPUImpl::transposeTransitionMatrices( return BEAGLE_SUCCESS; } +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::updateTransitionMatricesGrad(const int* probabilityIndices, + const double* edgeLengths, + int count) { + return BEAGLE_ERROR_NO_IMPLEMENTATION; +} + + BEAGLE_GPU_TEMPLATE int BeagleGPUImpl::updateTransitionMatrices(int eigenIndex, const int* probabilityIndices, @@ -2209,6 +2286,605 @@ int BeagleGPUImpl::updatePrePartials(const int *operations, return returnCode; } +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::allocateBastaBuffers(int bufferCount, + int bufferLength) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUImpl::allocateBastaBuffers\n"); +#endif + + kCoalescentBufferLength = bufferLength; + kCoalescentBufferCount = bufferCount; + kBastaIntervalBlockCount = bufferLength / 4 + 1; + + dCoalescentBuffers = gpu->AllocateMemory(kCoalescentBufferLength * sizeof(Real)); + + dBastaLogL = gpu->AllocateMemory(kBastaIntervalBlockCount * sizeof(Real)); + dBastaDistance = gpu->AllocateMemory(kCoalescentBufferLength * sizeof(Real)); + dBastaInterval = gpu->AllocateMemory(kBufferCount * sizeof(Real)); + dBastaFlags = gpu->AllocateMemory(3 * kBufferCount * sizeof(Real)); + dBastaOperationQueue = gpu->AllocateMemory(kBufferCount * 8 * sizeof(Real)); + dBastaMemory = gpu->AllocateMemory(4 * kPaddedStateCount * kCoalescentBufferLength * sizeof(Real)); + dBastaBlockResMemory = gpu->AllocateMemory(4 * kPaddedStateCount * kCoalescentBufferLength * kBastaIntervalBlockCount * sizeof(Real)); + dBastaFinalResMemory = gpu->AllocateMemory(4 * kPaddedStateCount * kCoalescentBufferLength * kBastaIntervalBlockCount * sizeof(Real)); + // gBastaGradBuffers.resize(4 * kStateCount * kStateCount * kPartialsPaddedStateCount * kCoalescentBufferLength); + hBastaOperationQueue = (Real*) gpu->CallocHost(sizeof(Real), kBufferCount * 8); + hBastaFinalKeys = (Real*) gpu->CallocHost(sizeof(Real), kBufferCount); + hBastaInterval = (Real*) gpu->CallocHost(sizeof(Real), kBufferCount); + hBastaSubintervals = (Real*) gpu->CallocHost(sizeof(Real), 2 * kBufferCount); + hBastaFinalSubintervals = (Real*) gpu->CallocHost(sizeof(Real), 3 * kBufferCount); + hBastazeroes = (Real*) gpu->CallocHost(sizeof(Real), 4 * kPaddedStateCount * kCoalescentBufferLength); + hBastaFinalResMemory = (Real*) gpu->CallocHost(sizeof(Real), 4 * kPaddedStateCount * kBufferCount); + hBastaMemory = (Real*) gpu->CallocHost(sizeof(Real), 4 * kPaddedStateCount * kCoalescentBufferLength); + + hBastaLogL = (Real*) gpu->CallocHost(sizeof(Real), kBastaIntervalBlockCount); + hBastaDistance = (Real*) gpu->CallocHost(sizeof(Real), kCoalescentBufferLength); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUImpl::allocateBastaBuffers\n"); +#endif + + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::getBastaBuffer(int bufferIndex, + double* out) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUImpl::getBastaBuffer\n"); +#endif + + fprintf(stderr, "BeagleGPUImpl::getBastaBuffer\n"); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUImpl::getBastaBuffer\n"); +#endif + + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::updateBastaPartials(const int* operations, + const int count, + const int* intervals, + const int intervalCount, + const int populationSizesIndex, + const int coalescentIndex) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUImpl::updateBastaPartials\n"); +#endif + + GPUPtr coalescent = dCoalescentBuffers; + // std::fill(coalescent, coalescent + kCoalescentBufferLength, 0); + + const GPUPtr sizes = dFrequencies[populationSizesIndex]; + int returnCode = updateInnerBastaPartials(operations, intervals, intervalCount, 0, count, sizes, coalescent); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUImpl::updateBastaPartials\n"); +#endif + + return returnCode; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::updateInnerBastaPartials(const int* operations, + const int* intervals, + const int intervalCount, + const int begin, + const int end, + const GPUPtr sizes, + GPUPtr coalescent) { + std::vector newOperations; + + const int numOps = BEAGLE_BASTA_OP_COUNT; + const int operationCount = end - begin; + + + for (int i = 0; i < operationCount; ++i) { + hBastaOperationQueue[i * numOps] = hPartialsOffsets[operations[i * numOps]]; + hBastaOperationQueue[i * numOps + 1] = hPartialsOffsets[operations[i * numOps + 1]]; + hBastaOperationQueue[i * numOps + 2] = operations[i * numOps + 2] * kPaddedStateCount * kPaddedStateCount; + if (operations[i * numOps + 3] >= 0) { + hBastaOperationQueue[i * numOps + 3] = hPartialsOffsets[operations[i * numOps + 3]]; + hBastaOperationQueue[i * numOps + 4] = operations[i * numOps + 4] * kPaddedStateCount * kPaddedStateCount; + } else { + hBastaOperationQueue[i * numOps + 3] = operations[i * numOps + 3]; + hBastaOperationQueue[i * numOps + 4] = operations[i * numOps + 4]; + } + hBastaOperationQueue[i * numOps + 5] = hPartialsOffsets[operations[i * numOps + 5]]; + hBastaOperationQueue[i * numOps + 6] = hPartialsOffsets[operations[i * numOps + 6]]; + hBastaOperationQueue[i * numOps + 7] = operations[i * numOps + 7]; + } + + gpu->MemcpyHostToDevice(dBastaOperationQueue, hBastaOperationQueue, sizeof(Real) * operationCount * numOps); + + + // Real r = 0; + // fprintf(stderr, "e:\n"); + // gpu->PrintfDeviceVector(dBastaE, kPaddedStateCount * kCoalescentBufferLength, r); + // fprintf(stderr, "f:\n"); + // gpu->PrintfDeviceVector(dBastaF, kPaddedStateCount * kCoalescentBufferLength, r); + // fprintf(stderr, "g:\n"); + // gpu->PrintfDeviceVector(dBastaG, kPaddedStateCount * kCoalescentBufferLength, r); + // fprintf(stderr, "h:\n"); + // gpu->PrintfDeviceVector(dBastaH, kPaddedStateCount * kCoalescentBufferLength, r); + + for (int interval = 0; interval < intervalCount - 1; ++interval) { + // TODO execute in parallel (no race conditions) + const int start = intervals[interval]; + const int end = intervals[interval + 1]; + const int opCounts = end - start; + kernels->InnerBastaPartialsCoalescent(dPartialsOrigin, dMatricesOrigin, dBastaOperationQueue, + sizes, coalescent, interval, start, numOps, opCounts); + + } + + + // for (int op = begin; op < end; op++) { + // + // const int numOps = BEAGLE_BASTA_OP_COUNT; + // + // const int parIndex = operations[op * numOps]; + // const int child1Index = operations[op * numOps + 1]; + // const int child1TransMatIndex = operations[op * numOps + 2]; + // const int child2Index = operations[op * numOps + 3]; + // const int child2TransMatIndex = operations[op * numOps + 4]; + // const int accumulation1PartialIndex = operations[op * numOps + 5]; + // const int accumulation2PartialIndex = operations[op * numOps + 6]; + // const int intervalNumber = operations[op * numOps + 7]; + // + // GPUPtr matrices1 = dMatrices[child1TransMatIndex]; + // GPUPtr matrices2 = dMatrices[child2TransMatIndex]; + // + // GPUPtr partials1 = dPartials[child1Index]; + // GPUPtr partials2 = dPartials[child2Index]; + // GPUPtr partials3 = dPartials[parIndex]; + // GPUPtr accumulation1 = dPartials[accumulation1PartialIndex]; + // GPUPtr accumulation2 = dPartials[accumulation2PartialIndex]; + + // Real r = 1; + // fprintf(stderr, "partial1:\n"); + // gpu->PrintfDeviceVector(partials1, kPaddedStateCount, r); + // fprintf(stderr, "matice1:\n"); + // gpu->PrintfDeviceVector(matrices1, kMatrixSize, r); + // kernels->InnerBastaPartialsCoalescent(partials1, partials2, partials3, + // matrices1, matrices2, accumulation1, accumulation2, sizes, coalescent, intervalNumber, 1, child2Index); + //Real r = 0; + // fprintf(stderr, "The child1index is: %d\n", child1Index); + // fprintf(stderr, "partials1:\n"); + // gpu->PrintfDeviceVector(partials1, kPaddedStateCount, r); + // fprintf(stderr, "The parindex is: %d\n", parIndex); + // fprintf(stderr, "partials3:\n"); + // gpu->PrintfDeviceVector(partials3, kPaddedStateCount, r); + + // Real r = 0; + // fprintf(stderr, "The op is: %d\n", op); + // fprintf(stderr, "The index is: %d\n", child1TransMatIndex); + //fprintf(stderr,"matrices = \n"); + // fprintf(stderr, "partials:\n"); + // gpu->PrintfDeviceVector(dPartialsOrigin, 524 * kPaddedStateCount, r); + // // gpu->PrintfDeviceVector(dMatricesOrigin, kPaddedStateCount * kPaddedStateCount * 3, r); + // // gpu->PrintfDeviceVector(sizes, 4, r); + // gpu->PrintfDeviceVector(coalescent, 4 * kCoalescentBufferLength, r); + //} + +#ifdef BEAGLE_DEBUG_SYNCH + gpu->SynchronizeHost(); +#endif + return BEAGLE_SUCCESS; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::updateBastaPartialsGrad(const int* operations, + const int count, + const int* intervals, + const int intervalCount, + const int populationSizesIndex, + const int coalescentIndex) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUImpl::updateBastaPartials\n"); +#endif + + int returnCode = BEAGLE_ERROR_GENERAL; + + fprintf(stderr, "BeagleGPUImpl::updateBastaPartials\n"); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUImpl::updateBastaPartials\n"); +#endif + + return returnCode; +} + +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::accumulateBastaPartials(const int* operations, + int operationCount, + const int* intervalStarts, + int intervalStartsCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out) { +//#define BEAGLE_BASTA_SERIAL +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUImpl::accumulateBastaPartials\n"); +#endif + GPUPtr coalescent = dCoalescentBuffers; + const GPUPtr sizes = dFrequencies[populationSizesIndex]; + const int numOps = BEAGLE_BASTA_OP_COUNT; + const int blockSize = 4; + const int start = 0; + const int end = operationCount; + +#ifdef BEAGLE_BENCHMARK + auto start1 = std::chrono::high_resolution_clock::now(); +#endif + +#ifdef BEAGLE_BASTA_SERIAL + + gpu->MemcpyHostToDevice(dBastaMemory, hBastazeroes, + sizeof(Real) * 4 * kPaddedStateCount * kCoalescentBufferLength); + +#ifdef BEAGLE_BENCHMARK + auto end1 = std::chrono::high_resolution_clock::now();\ + std::string key1 = "zero out bastamemory";\ + std::map, int>>::iterator it1 = benchmarkDuration.find(key1);\ + if(it1 != benchmarkDuration.end()){\ + it1->second.second += 1;\ + it1->second.first += end1-start1;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key1, std::pair, int>(end1 - start1, 1)));\ + } + + auto start2 = std::chrono::high_resolution_clock::now(); +#endif + + kernels->reduceWithinIntervalSerial(dBastaOperationQueue, dPartialsOrigin, dBastaMemory, numOps, + start, end, kCoalescentBufferLength); + +#ifdef BEAGLE_BENCHMARK + gpu->SynchronizeHost(); + + auto end2 = std::chrono::high_resolution_clock::now();\ + std::string key2 = "kernel1";\ + std::map, int>>::iterator it2 = benchmarkDuration.find(key2);\ + if(it2 != benchmarkDuration.end()){\ + it2->second.second += 1;\ + it2->second.first += end2-start2;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key2, std::pair, int>(end2 - start2, 1)));\ + } + + std::map, int>>::iterator it;\ + std::cerr << "\nBENCHMARKS: " << __FILE__ << "\n" << "Function\tTime" << std::endl;\ + for (it = benchmarkDuration.begin(); it != benchmarkDuration.end(); it++) {\ + std::cerr << it->first << "\t" << std::chrono::duration_cast(it->second.first).count() << " ns" << "\t" << it->second.second << std::endl;\ + } + +#endif + +#else + + Real* hBastaFlags = hBastaSubintervals + operationCount; + + int currentSubinterval = 0; + int previousInterval = 0; + int numSubinterval = 0; + for (int i = 0; i < operationCount; ++i) { + hBastaInterval[i] = (Real) operations[i * numOps + 7]; + if (i % blockSize == 0 || hBastaInterval[i] != hBastaInterval[i - 1]) { + hBastaFlags[i] = 1; + } else { + hBastaFlags[i] = 0; + } + + int block = i / blockSize; + if (i > 0 && (hBastaInterval[i] != previousInterval || (i % blockSize == 0 && block > 0))) { + currentSubinterval++; + previousInterval = hBastaInterval[i]; + } + hBastaSubintervals[i] = currentSubinterval; + hBastaFinalKeys[currentSubinterval] = hBastaInterval[i]; + } + + numSubinterval = currentSubinterval + 1; + +#ifdef BEAGLE_BENCHMARK + auto end1 = std::chrono::high_resolution_clock::now();\ + std::string key1 = "flag1";\ + std::map, int>>::iterator it1 = benchmarkDuration.find(key1);\ + if(it1 != benchmarkDuration.end()){\ + it1->second.second += 1;\ + it1->second.first += end1-start1;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key1, std::pair, int>(end1 - start1, 1)));\ + } + + auto start2 = std::chrono::high_resolution_clock::now(); +#endif + + gpu->MemcpyHostToDevice(dBastaInterval, hBastaSubintervals, sizeof(Real) * 2 * operationCount); + + +#ifdef BEAGLE_BENCHMARK + auto end2 = std::chrono::high_resolution_clock::now();\ + std::string key2 = "copy: flag1";\ + std::map, int>>::iterator it2 = benchmarkDuration.find(key2);\ + if(it2 != benchmarkDuration.end()){\ + it2->second.second += 1;\ + it2->second.first += end2-start2;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key2, std::pair, int>(end2 - start2, 1)));\ + } + + + auto start3 = std::chrono::high_resolution_clock::now(); +#endif + + kernels->reduceWithinInterval(dBastaOperationQueue, dPartialsOrigin, dBastaBlockResMemory, dBastaInterval, numOps, + start, end, numSubinterval); + +#ifdef BEAGLE_BENCHMARK + gpu->SynchronizeHost(); + + auto end3 = std::chrono::high_resolution_clock::now();\ + std::string key3 = "kernel1";\ + std::map, int>>::iterator it3 = benchmarkDuration.find(key3);\ + if(it3 != benchmarkDuration.end()){\ + it3->second.second += 1;\ + it3->second.first += end3-start3;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key3, std::pair, int>(end3 - start3, 1)));\ + } + + auto start4 = std::chrono::high_resolution_clock::now(); +#endif + + Real* hBastaFinalFlags = hBastaFinalSubintervals + numSubinterval; + Real* hBastaAccumFinalKeys = hBastaFinalFlags + numSubinterval; + int currentSubintervalFinal = 0; + int previousIntervalFinal = 0; + int numSubintervalFinal = 0; + for (int i = 0; i < numSubinterval; ++i) { + if (i % blockSize == 0 || hBastaFinalKeys[i] != hBastaFinalKeys[i - 1]) { + hBastaFinalFlags[i] = 1; + } else { + hBastaFinalFlags[i] = 0; + } + + int block = i / blockSize; + if (i > 0 && (hBastaFinalKeys[i] != previousIntervalFinal || (i % blockSize == 0 && block > 0))) { + currentSubintervalFinal++; + previousIntervalFinal = hBastaFinalKeys[i]; + } + hBastaFinalSubintervals[i] = currentSubintervalFinal; + hBastaAccumFinalKeys[currentSubintervalFinal] = hBastaFinalKeys[i]; + } + + + numSubintervalFinal = currentSubintervalFinal + 1; + + +#ifdef BEAGLE_BENCHMARK + auto end4 = std::chrono::high_resolution_clock::now();\ + std::string key4 = "flag2";\ + std::map, int>>::iterator it4 = benchmarkDuration.find(key4);\ + if(it4 != benchmarkDuration.end()){\ + it4 ->second.second += 1;\ + it4 ->second.first += end4-start4;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key4, std::pair, int>(end4 - start4, 1)));\ + } + + auto start5 = std::chrono::high_resolution_clock::now(); +#endif + + gpu->MemcpyHostToDevice(dBastaFlags, hBastaFinalSubintervals, sizeof(Real) * 3 * numSubinterval); + +#ifdef BEAGLE_BENCHMARK + auto end5 = std::chrono::high_resolution_clock::now();\ + std::string key5 = "copy: flag2";\ + std::map, int>>::iterator it5 = benchmarkDuration.find(key5);\ + if(it5 != benchmarkDuration.end()){\ + it5 ->second.second += 1;\ + it5 ->second.first += end5-start5;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key5, std::pair, int>(end5 - start5, 1)));\ + } + + + auto start6 = std::chrono::high_resolution_clock::now(); +#endif + kernels->accumulateCarryOut(dBastaBlockResMemory, dBastaFinalResMemory, dBastaFlags, numSubinterval, numSubintervalFinal); + +#ifdef BEAGLE_BENCHMARK + gpu->SynchronizeHost();; + + auto end6 = std::chrono::high_resolution_clock::now();\ + std::string key6 = "kernel2";\ + std::map, int>>::iterator it6 = benchmarkDuration.find(key6);\ + if(it6 != benchmarkDuration.end()){\ + it6 ->second.second += 1;\ + it6 ->second.first += end6-start6;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key6, std::pair, int>(end6 - start6, 1)));\ + } + + auto start7 = std::chrono::high_resolution_clock::now(); +#endif + +#ifdef BEAGLE_BASTA_CPU_ACCUM + + Real* hBastaFinalEres = hBastaFinalResMemory; + Real* hBastaFinalFres = hBastaFinalEres + kPaddedStateCount * numSubintervalFinal; + Real* hBastaFinalGres = hBastaFinalFres + kPaddedStateCount * numSubintervalFinal; + Real* hBastaFinalHres = hBastaFinalGres + kPaddedStateCount * numSubintervalFinal; + + + gpu->MemcpyDeviceToHost(hBastaFinalResMemory, dBastaFinalResMemory, sizeof(Real) * 4 * kPaddedStateCount * numSubintervalFinal); + +#ifdef BEAGLE_BENCHMARK + auto end7 = std::chrono::high_resolution_clock::now();\ + std::string key7 = "copy intermediate result to cpu";\ + std::map, int>>::iterator it7 = benchmarkDuration.find(key7);\ + if(it7 != benchmarkDuration.end()){\ + it7 ->second.second += 1;\ + it7 ->second.first += end7-start7;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key7, std::pair, int>(end7 - start7, 1)));\ + } + + auto start8 = std::chrono::high_resolution_clock::now(); +#endif + memset(hBastaMemory, 0, 4 * kPaddedStateCount * kCoalescentBufferLength * sizeof(Real)); + // Set the pointers to the correct locations within the block + Real* hBastaE = hBastaMemory; + Real* hBastaF = hBastaE + kPaddedStateCount * kCoalescentBufferLength; + Real* hBastaG = hBastaF + kPaddedStateCount * kCoalescentBufferLength; + Real* hBastaH = hBastaG + kPaddedStateCount * kCoalescentBufferLength; + + for (int i = 0; i < numSubintervalFinal; ++i) { + int interval = hBastaAccumFinalKeys[i]; + for (int j = 0; j < kStateCount; ++j) { + hBastaE[interval * kPaddedStateCount + j] += hBastaFinalEres[i * kPaddedStateCount + j]; + hBastaF[interval * kPaddedStateCount + j] += hBastaFinalFres[i * kPaddedStateCount + j]; + hBastaG[interval * kPaddedStateCount + j] += hBastaFinalGres[i * kPaddedStateCount + j]; + hBastaH[interval * kPaddedStateCount + j] += hBastaFinalHres[i * kPaddedStateCount + j]; + } + } + +#ifdef BEAGLE_BENCHMARK + auto end8 = std::chrono::high_resolution_clock::now();\ + std::string key8 = "last cpu accumulation";\ + std::map, int>>::iterator it8 = benchmarkDuration.find(key8);\ + if(it8 != benchmarkDuration.end()){\ + it8 ->second.second += 1;\ + it8 ->second.first += end8-start8;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key8, std::pair, int>(end8 - start8, 1)));\ + } + + auto start9 = std::chrono::high_resolution_clock::now(); +#endif + + gpu->MemcpyHostToDevice(dBastaMemory, hBastaMemory, sizeof(Real) * 4 * kPaddedStateCount * kCoalescentBufferLength); + +#ifdef BEAGLE_BENCHMARK + auto end9 = std::chrono::high_resolution_clock::now();\ + std::string key9 = "copy: final result";\ + std::map, int>>::iterator it9 = benchmarkDuration.find(key9);\ + if(it9 != benchmarkDuration.end()){\ + it9 ->second.second += 1;\ + it9 ->second.first += end9-start9;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key9, std::pair, int>(end9 - start9, 1)));\ + } + + std::map, int>>::iterator it;\ + std::cerr << "\nBENCHMARKS: " << __FILE__ << "\n" << "Function\tTime" << std::endl;\ + for (it = benchmarkDuration.begin(); it != benchmarkDuration.end(); it++) {\ + std::cerr << it->first << "\t" << std::chrono::duration_cast(it->second.first).count() << " ns" << "\t" << it->second.second << std::endl;\ + } +#endif + +#else + // Fill with zeroes + gpu->MemcpyHostToDevice(dBastaMemory, hBastazeroes, + sizeof(Real) * 4 * kPaddedStateCount * kCoalescentBufferLength); + +#ifdef BEAGLE_BENCHMARK + auto end7 = std::chrono::high_resolution_clock::now();\ + std::string key7 = "zero out dbastamemory";\ + std::map, int>>::iterator it7 = benchmarkDuration.find(key7);\ + if(it7 != benchmarkDuration.end()){\ + it7 ->second.second += 1;\ + it7 ->second.first += end7-start7;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key7, std::pair, int>(end7 - start7, 1)));\ + } + + auto start8 = std::chrono::high_resolution_clock::now(); +#endif + + kernels->accumulateCarryOutFinal(dBastaFinalResMemory, dBastaMemory, dBastaFlags, numSubinterval, numSubintervalFinal, kCoalescentBufferLength); + +#ifdef BEAGLE_BENCHMARK + gpu->SynchronizeHost(); + + auto end8 = std::chrono::high_resolution_clock::now();\ + std::string key8 = "last gpu kernel for accumulation";\ + std::map, int>>::iterator it8 = benchmarkDuration.find(key8);\ + if(it8 != benchmarkDuration.end()){\ + it8 ->second.second += 1;\ + it8 ->second.first += end8-start8;\ + } else {\ + benchmarkDuration.insert(benchmarkDuration.end(), std::pair, int>>(key8, std::pair, int>(end8 - start8, 1)));\ + } + + + std::map, int>>::iterator it;\ + std::cerr << "\nBENCHMARKS: " << __FILE__ << "\n" << "Function\tTime" << std::endl;\ + for (it = benchmarkDuration.begin(); it != benchmarkDuration.end(); it++) {\ + std::cerr << it->first << "\t" << std::chrono::duration_cast(it->second.first).count() << " ns" << "\t" << it->second.second << std::endl;\ + } +#endif +#endif +#endif + for (int i = 0; i < kCoalescentBufferLength; ++i) { + hBastaDistance[i] = (Real) intervalLengths[i]; + } + + gpu->MemcpyHostToDevice(dBastaDistance, hBastaDistance, sizeof(Real) * kCoalescentBufferLength); + + + kernels->reduceAcrossIntervals(dBastaMemory, dBastaDistance, dBastaLogL, sizes, coalescent, + intervalStartsCount, kCoalescentBufferLength); + // fprintf(stderr, "The block count is: %d\n", kBastaIntervalBlockCount); + // fprintf(stderr, "logL:\n"); + // gpu->PrintfDeviceVector(dBastaLogL, kBastaIntervalBlockCount, r); + // fprintf(stderr, "sizes:\n"); + // gpu->PrintfDeviceVector(sizes, 4, r); + // fprintf(stderr, "coalescent:\n"); + // gpu->PrintfDeviceVector(coalescent, kCoalescentBufferLength, r); + gpu->MemcpyDeviceToHost(hBastaLogL, dBastaLogL, sizeof(Real) * kBastaIntervalBlockCount); + for (int i = 0; i < kBastaIntervalBlockCount; i++) { + out[0] += hBastaLogL[i]; + } + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUImpl::accumulateBastaPartials\n"); +#endif + + return BEAGLE_SUCCESS; +} + + +BEAGLE_GPU_TEMPLATE +int BeagleGPUImpl::accumulateBastaPartialsGrad(const int *operations, + const int operationCount, + const int *intervalStarts, + const int intervalStartsCount, + const double *intervalLengths, + const int populationSizesIndex, + const int coalescentIndex, + double *out) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tEntering BeagleGPUImpl::accumulateBastaPartials\n"); +#endif + + int returnCode = BEAGLE_ERROR_GENERAL; + + fprintf(stderr, "BeagleGPUImpl::accumulateBastaPartials\n"); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\tLeaving BeagleGPUImpl::accumulateBastaPartials\n"); +#endif + + return returnCode; +} + + BEAGLE_GPU_TEMPLATE int BeagleGPUImpl::calculateEdgeDerivative(const int *postBufferIndices, const int *preBufferIndices, @@ -2225,19 +2901,19 @@ int BeagleGPUImpl::calculateEdgeDerivative(const int *postBu #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\tEntering BeagleGPUImpl::calculateEdgeDerivative\n"); #endif - + if (dOutFirstDeriv == (GPUPtr)NULL) { dOutFirstDeriv = gpu->AllocateMemory(kPaddedPatternCount * kBufferCount * 2 * sizeof(Real)); } int returnCode = BEAGLE_ERROR_GENERAL; - + returnCode = calcEdgeFirstDerivatives(postBufferIndices, preBufferIndices, firstDerivativeIndices, &categoryWeightsIndex, cumulativeScaleIndices, count, outFirstDerivative, NULL, NULL); if (outDiagonalSecondDerivative != NULL) { - int diagonalSecondDerivativeReturnCode = + int diagonalSecondDerivativeReturnCode = calcEdgeFirstDerivatives(postBufferIndices, preBufferIndices, secondDerivativeIndices, &categoryWeightsIndex, cumulativeScaleIndices, count, @@ -3022,7 +3698,7 @@ int BeagleGPUImpl::upPrePartials(bool byPartition, // #ifdef BEAGLE_DEBUG_SYNCH - gpu->Synchronize(); + gpu->SynchronizeHost(); #endif return BEAGLE_SUCCESS; } @@ -3053,8 +3729,8 @@ int BeagleGPUImpl::accumulateScaleFactors(const int* scaling gpu->MemcpyHostToDevice(dPtrQueue, hPtrQueue, sizeof(unsigned int) * count); kernels->AccumulateFactorsAutoScaling(dScalingFactors[0], dPtrQueue, dAccumulatedScalingFactors, count, kPaddedPatternCount, kScaleBufferSize); - - } else { + + } else { for(int n = 0; n < count; n++) { hPtrQueue[n] = scalingIndices[n] * kScaleBufferSize; } @@ -4503,13 +5179,13 @@ int BeagleGPUImpl::calcCrossProducts(const int *postBufferIn } gpu->MemcpyHostToDevice(dDerivativeQueue, hDerivativeQueue, sizeof(unsigned int) * 2 * totalCount); - + const double* categoryRates = hCategoryRates[0]; // TODO parameterize index const GPUPtr categoryWeights = dWeights[0]; int lengthCount = 0; - for (int i = 0; i < totalCount; i++) { - hDistanceQueue[lengthCount++] = (Real) edgeLengths[i]; + for (int i = 0; i < totalCount; i++) { + hDistanceQueue[lengthCount++] = (Real) edgeLengths[i]; } for (int i = 0; i < kCategoryCount; i++) { hDistanceQueue[lengthCount++] = (Real) categoryRates[i]; @@ -4529,14 +5205,14 @@ int BeagleGPUImpl::calcCrossProducts(const int *postBufferIn dMultipleDerivatives, dStatesOrigin, dPartialsOrigin, - dDistanceQueue, + dDistanceQueue, dDerivativeQueue, - categoryWeights, dPatternWeights, - 0, statesTipsCount, totalCount, + categoryWeights, dPatternWeights, + 0, statesTipsCount, totalCount, kPaddedPatternCount, kCategoryCount, accumulate, nodeBlocks, patternBlocks, kStateCount); - accumulate = true; + accumulate = true; } kernels->PartialsPartialsCrossProducts( @@ -4560,7 +5236,7 @@ int BeagleGPUImpl::calcCrossProducts(const int *postBufferIn } for (int i = 0; i < kStateCount; ++i) { - beagleMemCpy(outCrossProducts + i * kStateCount, + beagleMemCpy(outCrossProducts + i * kStateCount, hTmp.data() + i * kPaddedStateCount, kStateCount); } diff --git a/libhmsbeagle/GPU/CMakeLists.txt b/libhmsbeagle/GPU/CMakeLists.txt index 22b3c1efe..eb237c9ce 100644 --- a/libhmsbeagle/GPU/CMakeLists.txt +++ b/libhmsbeagle/GPU/CMakeLists.txt @@ -1,13 +1,24 @@ -find_package(OpenCL) -if(OpenCL_FOUND AND BUILD_OPENCL) - message(STATUS "OpenCL Includes: ${OpenCL_INCLUDE_DIRS}") - message(STATUS "OpenCL Libraries: ${OpenCL_LIBRARIES}") - add_subdirectory("CMake_OpenCL") -endif(OpenCL_FOUND AND BUILD_OPENCL) +if(BUILD_OPENCL) + find_package(OpenCL) +# set(OpenCL_INCLUDE_DIRS /opt/rocm/opencl/include) +# set(OpenCL_LIBRARIES /opt/rocm/opencl/lib/libOpenCL.so) + if(OpenCL_FOUND OR (OpenCL_INCLUDE_DIRS AND OpenCL_LIBRARIES)) + message(STATUS "OpenCL Includes: ${OpenCL_INCLUDE_DIRS}") + message(STATUS "OpenCL Libraries: ${OpenCL_LIBRARIES}") + add_subdirectory("CMake_OpenCL") + endif(OpenCL_FOUND OR (OpenCL_INCLUDE_DIRS AND OpenCL_LIBRARIES)) +endif(BUILD_OPENCL) -find_package(CUDA) -if(CUDA_FOUND AND BUILD_CUDA) +if(BUILD_CUDA) + find_package(CUDA) + if(CUDA_FOUND) + message(STATUS "CUDA Includes: ${CUDA_INCLUDE_DIRS}") + add_subdirectory("CMake_CUDA") + endif(CUDA_FOUND) +endif(BUILD_CUDA) + +if(CUDA_FOUND AND BUILD_ACTION) message(STATUS "CUDA Includes: ${CUDA_INCLUDE_DIRS}") - add_subdirectory("CMake_CUDA") -endif(CUDA_FOUND AND BUILD_CUDA) + add_subdirectory("CMake_Action") +endif(CUDA_FOUND AND BUILD_ACTION) diff --git a/libhmsbeagle/GPU/CMake_Action/CMakeLists.txt b/libhmsbeagle/GPU/CMake_Action/CMakeLists.txt new file mode 100644 index 000000000..3d42ed45c --- /dev/null +++ b/libhmsbeagle/GPU/CMake_Action/CMakeLists.txt @@ -0,0 +1,72 @@ + +include_directories( + ${CUDA_INCLUDE_DIRS} +) + +add_definitions(-DCUDA) + +link_directories(${CUDA_TOOLKIT_ROOT_DIR}/lib + ${CUDA_TOOLKIT_ROOT_DIR}/lib/x64 + ${CUDA_TOOLKIT_ROOT_DIR}/lib64 +) + +if(WIN32) + set(NVCC "nvcc.exe") + set(NVCCFLAGS "-O3 -Wno-deprecated-gpu-targets") + set(NVCC_INC "-I../../..") + set(CMD_NAME createCUDAKernels.bat) +else(WIN32) + set(NVCC "${CUDA_TOOLKIT_ROOT_DIR}/bin/nvcc") + set(NVCCFLAGS "-O3 -Wno-deprecated-gpu-targets -ccbin ${CMAKE_CXX_COMPILER} -m64 -D_POSIX_C_SOURCE -std=c++11") + set(NVCC_INC "-I${CMAKE_SOURCE_DIR}") + set(CMD_NAME make_cuda_kernels.sh) +# set(CMAKE_CUDA_COMPILER ${NVCC}) +endif(WIN32) + +#set(CMAKE_CUDA_ARCHITECTURES "native") +enable_language(CUDA) +set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -O3 -Wno-deprecated-gpu-targets --extended-lambda -std=c++17") + + + +add_custom_command( + OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/../kernels/BeagleCUDA_kernels.h + COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/../kernels/${CMD_NAME} ${NVCC} "${NVCCFLAGS}" "${NVCC_INC}" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../kernels + DEPENDS "../kernels/kernels4.cu" "../kernels/kernels4Derivatives.cu" "../kernels/kernelsXDerivatives.cu" "../kernels/kernelsAll.cu" + COMMENT "Building CUDA kernels" + VERBATIM) + +#add_custom_target(CudaKernels DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../kernels/BeagleCUDA_kernels.h) + +add_library(hmsbeagle-action-cuda SHARED + ../BeagleGPUActionImpl.h + ../BeagleGPUActionImpl.hpp + ../GPUImplDefs.h + ../GPUImplHelper.cpp + ../GPUImplHelper.h + ../GPUInterfaceCUDA.cpp + ../KernelLauncher.cpp + ../KernelLauncher.h + ../KernelResource.cpp + ../KernelResource.h + ../ActionCUDAPlugin.cpp + ../ActionCUDAPlugin.h + ../cuda_ops.cu + ../Precision.h +) + +add_dependencies(hmsbeagle-action-cuda CudaKernels) + +target_link_libraries(hmsbeagle-action-cuda cuda ${CUDA_LIBRARIES} ${CUDA_cusparse_LIBRARY} ${CUDA_cublas_LIBRARY} Eigen3::Eigen) + +install(TARGETS hmsbeagle-action-cuda + DESTINATION ${BEAGLE_INSTALL_DIR} + COMPONENT action-cuda +) + +SET_TARGET_PROPERTIES(hmsbeagle-action-cuda + PROPERTIES + SOVERSION "${BEAGLE_PLUGIN_VERSION_EXTENDED}" + SUFFIX "${BEAGLE_PLUGIN_SUFFIX}" +) diff --git a/libhmsbeagle/GPU/GPUImplDefs.h b/libhmsbeagle/GPU/GPUImplDefs.h index 340b04264..0c2b58ac4 100644 --- a/libhmsbeagle/GPU/GPUImplDefs.h +++ b/libhmsbeagle/GPU/GPUImplDefs.h @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres diff --git a/libhmsbeagle/GPU/GPUImplHelper.cpp b/libhmsbeagle/GPU/GPUImplHelper.cpp index 886080d6b..6e505700f 100644 --- a/libhmsbeagle/GPU/GPUImplHelper.cpp +++ b/libhmsbeagle/GPU/GPUImplHelper.cpp @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres diff --git a/libhmsbeagle/GPU/GPUImplHelper.h b/libhmsbeagle/GPU/GPUImplHelper.h index 7dc97c12c..67406f6b5 100644 --- a/libhmsbeagle/GPU/GPUImplHelper.h +++ b/libhmsbeagle/GPU/GPUImplHelper.h @@ -5,19 +5,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres diff --git a/libhmsbeagle/GPU/GPUInterface.h b/libhmsbeagle/GPU/GPUInterface.h index 5c4490c15..bddb48e8a 100644 --- a/libhmsbeagle/GPU/GPUInterface.h +++ b/libhmsbeagle/GPU/GPUInterface.h @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Dat Huynh @@ -76,13 +66,14 @@ class GPUInterface { int numStreams; #ifdef CUDA CUdevice cudaDevice; + int cudaDeviceOrdinal; CUcontext cudaContext; CUmodule cudaModule; CUstream* cudaStreams; CUevent cudaEvent; const char* GetCUDAErrorDescription(int errorCode); #elif defined(FW_OPENCL) - cl_device_id openClDeviceId; // compute device id + cl_device_id openClDeviceId; // compute device id cl_context openClContext; // compute context cl_command_queue* openClCommandQueues; // compute command queue cl_event* openClEvents; // compute events @@ -93,30 +84,39 @@ class GPUInterface { public: GPUInterface(); - + ~GPUInterface(); - + int Initialize(); int GetDeviceCount(); - void SetDevice(int deviceNumber, - int paddedStateCount, - int categoryCount, +#ifdef CUDA + // Ordinal of the device chosen by SetDevice( ), for code that uses the CUDA runtime API. + int GetCudaDeviceOrdinal() { return cudaDeviceOrdinal; } + + // The stream that single-stream operations (copies, scale-factor kernels, ...) are issued on. + // ResizeStreamCount( ) replaces it. + CUstream GetCudaStream() { return cudaStreams[0]; } +#endif + + void SetDevice(int deviceNumber, + int paddedStateCount, + int categoryCount, int patternCount, int unpaddedPatternCount, int tipCount, long flags); - + void ResizeStreamCount(int newStreamCount); void SynchronizeHost(); void SynchronizeDevice(); void SynchronizeDeviceWithIndex(int streamRecordIndex, int streamWaitIndex); - + GPUFunction GetFunction(const char* functionName); - + void LaunchKernel(GPUFunction deviceFunction, Dim3Int block, Dim3Int grid, @@ -134,13 +134,13 @@ class GPUInterface { ...); // parameters void* MallocHost(size_t memSize); - + void* CallocHost(size_t size, size_t length); - + void* AllocatePinnedHostMemory(size_t memSize, bool writeCombined, bool mapped); - + #ifdef FW_OPENCL void* MapMemory(GPUPtr dPtr, size_t memSize); @@ -150,7 +150,7 @@ class GPUInterface { #endif GPUPtr AllocateMemory(size_t memSize); - + GPUPtr AllocateRealMemory(size_t length); GPUPtr AllocateIntMemory(size_t length); @@ -158,7 +158,7 @@ class GPUInterface { GPUPtr CreateSubPointer(GPUPtr dPtr, size_t offset, size_t size); size_t AlignMemOffset(size_t offset); - + void MemsetShort(GPUPtr dest, unsigned short val, size_t count); @@ -170,28 +170,28 @@ class GPUInterface { void MemcpyDeviceToHost(void* dest, const GPUPtr src, size_t memSize); - + void MemcpyDeviceToDevice(GPUPtr dest, GPUPtr src, size_t memSize); void FreeHostMemory(void* hPtr); - + void FreePinnedHostMemory(void* hPtr); - + void FreeMemory(GPUPtr dPtr); GPUPtr GetDeviceHostPointer(void* hPtr); - + size_t GetAvailableMemory(); - + void GetDeviceName(int deviceNumber, char* deviceName, int nameLength); - + void GetDeviceDescription(int deviceNumber, char* deviceDescription); - + long GetDeviceTypeFlag(int deviceNumber); BeagleDeviceImplementationCodes GetDeviceImplementationCode(int deviceNumber); @@ -202,11 +202,11 @@ class GPUInterface { void PrintfDeviceVector(GPUPtr dPtr, int length, Real r) { PrintfDeviceVector(dPtr,length,-1, 0, r); } - + template void PrintfDeviceVector(GPUPtr dPtr, int length, double checkValue, Real r); - + template void PrintfDeviceVector(GPUPtr dPtr, int length, @@ -245,7 +245,7 @@ class GPUInterface { void PrintfDeviceInt(GPUPtr dPtr, int length); - + KernelResource* kernelResource; #ifdef BEAGLE_DEBUG_OPENCL_CORES @@ -253,11 +253,11 @@ class GPUInterface { void ReleaseDevice(int deviceNumber); #endif - + protected: void InitializeKernelResource(int paddedStateCount, bool doublePrecision); - + std::map* resourceMap; bool supportDoublePrecision; diff --git a/libhmsbeagle/GPU/GPUInterfaceCUDA.cpp b/libhmsbeagle/GPU/GPUInterfaceCUDA.cpp index 570c2500c..c152ab22d 100644 --- a/libhmsbeagle/GPU/GPUInterfaceCUDA.cpp +++ b/libhmsbeagle/GPU/GPUInterfaceCUDA.cpp @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres @@ -126,6 +116,7 @@ GPUInterface::GPUInterface() { #endif cudaDevice = (CUdevice) 0; + cudaDeviceOrdinal = 0; cudaContext = NULL; cudaModule = NULL; cudaStreams = NULL; @@ -251,6 +242,8 @@ void GPUInterface::InitializeKernelResource(int paddedStateCount, case 128: LOAD_KERNEL_INTO_RESOURCE(128, SP, 128); break; case 192: LOAD_KERNEL_INTO_RESOURCE(192, SP, 192); break; case 256: LOAD_KERNEL_INTO_RESOURCE(256, SP, 256); break; + default: fprintf(stderr,"ACTION CUDA: Stupidly loading 4-state kernel since we can't find the right one\n"); + LOAD_KERNEL_INTO_RESOURCE( 4, DP, 4); } } @@ -260,7 +253,8 @@ void GPUInterface::SetDevice(int deviceNumber, int paddedStateCount, int categor fprintf(stderr,"\t\t\tEntering GPUInterface::SetDevice\n"); #endif - SAFE_CUDA(cuDeviceGet(&cudaDevice, (*resourceMap)[deviceNumber])); + cudaDeviceOrdinal = (*resourceMap)[deviceNumber]; + SAFE_CUDA(cuDeviceGet(&cudaDevice, cudaDeviceOrdinal)); // unsigned int ctxFlags = CU_CTX_SCHED_AUTO; diff --git a/libhmsbeagle/GPU/GPUInterfaceOpenCL.cpp b/libhmsbeagle/GPU/GPUInterfaceOpenCL.cpp index d0bee22ba..baf4b13ff 100644 --- a/libhmsbeagle/GPU/GPUInterfaceOpenCL.cpp +++ b/libhmsbeagle/GPU/GPUInterfaceOpenCL.cpp @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Daniel Ayres */ @@ -1051,7 +1041,7 @@ void GPUInterface::GetDeviceName(int deviceNumber, sizeof(cl_uint), &mpCount, NULL)); char mpCountStr[12]; - sprintf(mpCountStr, "%d", mpCount); + snprintf(mpCountStr, 12, "%d", mpCount); strcat(deviceName, " ("); strcat(deviceName, mpCountStr); (mpCount==1?strcat(deviceName, " compute unit)"):strcat(deviceName, " compute units)")); @@ -1098,7 +1088,7 @@ void GPUInterface::GetDeviceDescription(int deviceNumber, SAFE_CL(clGetDeviceInfo(tmpOpenClDevice, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(unsigned int), &mpCount, NULL)); - sprintf(deviceDescription, + snprintf(deviceDescription, 128, "Global memory (MB): %d | Clock speed (Ghz): %1.2f | Number of compute units: %d", int(totalGlobalMemory / 1024.0 / 1024.0), clockSpeed / 1000.0, mpCount); diff --git a/libhmsbeagle/GPU/KernelLauncher.cpp b/libhmsbeagle/GPU/KernelLauncher.cpp old mode 100644 new mode 100755 index 3a81bfe39..ff5d5fdb9 --- a/libhmsbeagle/GPU/KernelLauncher.cpp +++ b/libhmsbeagle/GPU/KernelLauncher.cpp @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres @@ -34,7 +24,6 @@ #include "libhmsbeagle/beagle.h" #include "libhmsbeagle/GPU/GPUImplDefs.h" #include "libhmsbeagle/GPU/KernelLauncher.h" -#include "libhmsbeagle/benchmark/BenchmarkHelper.h" /**************CODE***********/ @@ -53,7 +42,6 @@ KernelLauncher::KernelLauncher(GPUInterface* inGpu) { } KernelLauncher::~KernelLauncher() { - DEBUG_FINALIZE_TIME(); } void KernelLauncher::SetupKernelBlocksAndGrids() { @@ -82,10 +70,10 @@ void KernelLauncher::SetupKernelBlocksAndGrids() { kMatrixBlockSize = gpu->kernelResource->matrixBlockSize; kSumSitesBlockSize = SUM_SITES_BLOCK_SIZE; kFlags = gpu->kernelResource->flags; - + // Set up block/grid for transition matrices computation bgTransitionProbabilitiesBlock = Dim3Int(kMultiplyBlockSize, kMultiplyBlockSize); - bgTransitionProbabilitiesGrid = Dim3Int(kPaddedStateCount/kMultiplyBlockSize, + bgTransitionProbabilitiesGrid = Dim3Int(kPaddedStateCount/kMultiplyBlockSize, kPaddedStateCount/kMultiplyBlockSize); if(kPaddedStateCount % kMultiplyBlockSize != 0) { bgTransitionProbabilitiesGrid.x += 1; @@ -119,7 +107,7 @@ void KernelLauncher::SetupKernelBlocksAndGrids() { if (!kCPUImplementation && (kPatternCount % kPatternBlockSize != 0)) { bgPeelingGrid.x += 1; } - } + } // Set up block/grid for likelihood computation if (kPaddedStateCount == 4) { @@ -188,8 +176,8 @@ void KernelLauncher::SetupKernelBlocksAndGrids() { bgAccumulateGrid = Dim3Int(kPatternCount / kPatternBlockSize); if (kPatternCount % kPatternBlockSize != 0) - bgAccumulateGrid.x += 1; - + bgAccumulateGrid.x += 1; + // Set up block/grid for scaling partials if (kCPUImplementation) { bgScaleBlock = Dim3Int(kPatternBlockSize); @@ -197,28 +185,29 @@ void KernelLauncher::SetupKernelBlocksAndGrids() { } else { if (kSlowReweighing) { bgScaleBlock = Dim3Int(kPaddedStateCount); - bgScaleGrid = Dim3Int(kPatternCount); + bgScaleGrid = Dim3Int(kPatternCount); } else { if (kPaddedStateCount == 4) { bgScaleBlock = Dim3Int(16, kMatrixBlockSize); bgScaleGrid = Dim3Int(kPatternCount / 4, kCategoryCount/kMatrixBlockSize); if (kPatternCount % 4 != 0) { - bgScaleGrid.x += 1; // + bgScaleGrid.x += 1; // fprintf(stderr,"PATTERNS SHOULD BE PADDED! Inform Marc, please.\n"); - exit(-1); + fprintf(stderr,"Going ahead anyway..\n"); + // exit(-1); } - } else { + } else { bgScaleBlock = Dim3Int(kPaddedStateCount, kMatrixBlockSize); bgScaleGrid = Dim3Int(kPatternCount, kCategoryCount/kMatrixBlockSize); } if (kCategoryCount % kMatrixBlockSize != 0) bgScaleGrid.y += 1; - if (bgScaleGrid.y > 1) { + if (bgScaleGrid.y > 1) { fprintf(stderr, "Not yet implemented! Try slow reweighing.\n"); exit(-1); - } + } } - } + } // Set up block for site likelihood accumulation if (kCPUImplementation) { @@ -245,11 +234,26 @@ void KernelLauncher::SetupKernelBlocksAndGrids() { bgReorderPatternsBlock = Dim3Int(REORDER_BLOCK_SIZE_CPU); } else { bgReorderPatternsBlock = Dim3Int(kPaddedStateCount, REORDER_BLOCK_SIZE); - } + } bgReorderPatternsGrid = Dim3Int((kUnpaddedPatternCount + REORDER_BLOCK_SIZE - 1) / REORDER_BLOCK_SIZE, kCategoryCount); + //Set up block for basta partials + + bgBastaPeelingBlock = Dim3Int(kPaddedStateCount, 4); + bgBastaPeelingGrid = Dim3Int(30,1); + + bgBastaReductionBlock = Dim3Int(kPaddedStateCount, 4); + bgBastaReductionGrid = Dim3Int(18162, 1); + + bgBastaPreBlock = Dim3Int(32); + bgBastaPreGrid = Dim3Int(1); + + bgBastaSumBlock = Dim3Int(128); + bgBastaSumGrid = Dim3Int(400); } + + void KernelLauncher::LoadKernels() { #ifdef FW_OPENCL_TESTING @@ -271,9 +275,9 @@ void KernelLauncher::LoadKernels() { } fMatrixMulADBFirstDeriv = gpu->GetFunction("kernelMatrixMulADBFirstDeriv"); - + fMatrixMulADBSecondDeriv = gpu->GetFunction("kernelMatrixMulADBSecondDeriv"); - + if (kFlags & BEAGLE_FLAG_EIGEN_COMPLEX) { fMatrixMulADB = gpu->GetFunction("kernelMatrixMulADBComplex"); } else { @@ -281,11 +285,11 @@ void KernelLauncher::LoadKernels() { } fPartialsPartialsByPatternBlockCoherent = gpu->GetFunction( - "kernelPartialsPartialsNoScale"); - + "kernelPartialsPartialsNoScale"); + fPartialsPartialsByPatternBlockFixedScaling = gpu->GetFunction( "kernelPartialsPartialsFixedScale"); - + fPartialsPartialsByPatternBlockAutoScaling = gpu->GetFunction( "kernelPartialsPartialsAutoScale"); @@ -307,26 +311,21 @@ void KernelLauncher::LoadKernels() { fMultipleNodeSiteSquaredReduction = gpu->GetFunction( "kernelMultipleNodeSiteSquaredReduction"); - - fprintf(stderr, "A\n"); - fPartialsPartialsCrossProducts = gpu->GetFunction( "kernelPartialsPartialsCrossProducts"); fPartialsStatesCrossProducts = gpu->GetFunction( "kernelPartialsStatesCrossProducts"); - fprintf(stderr, "B\n"); - if (kPaddedStateCount == 4) { // TODO Temporary hack until kernels are written fPartialsPartialsByPatternBlockCheckScaling = gpu->GetFunction( "kernelPartialsPartialsCheckScale"); - + fPartialsPartialsByPatternBlockFixedCheckScaling = gpu->GetFunction( "kernelPartialsPartialsFixedCheckScale"); } - + fStatesPartialsByPatternBlockCoherent = gpu->GetFunction( "kernelStatesPartialsNoScale"); @@ -352,16 +351,16 @@ void KernelLauncher::LoadKernels() { fStatesPartialsEdgeLikelihoodsSecondDeriv = gpu->GetFunction( "kernelStatesPartialsEdgeLikelihoodsSecondDeriv"); - + fIntegrateLikelihoodsDynamicScalingSecondDeriv = gpu->GetFunction( "kernelIntegrateLikelihoodsFixedScaleSecondDeriv"); - + if (kFlags & BEAGLE_FLAG_SCALING_AUTO) { fIntegrateLikelihoodsDynamicScaling = gpu->GetFunction("kernelIntegrateLikelihoodsAutoScaling"); } else { fIntegrateLikelihoodsDynamicScaling = gpu->GetFunction("kernelIntegrateLikelihoodsFixedScale"); } - + if (kFlags & BEAGLE_FLAG_SCALERS_LOG) { fAccumulateFactorsDynamicScaling = gpu->GetFunction("kernelAccumulateFactorsScalersLog"); fRemoveFactorsDynamicScaling = gpu->GetFunction("kernelRemoveFactorsScalersLog"); @@ -394,10 +393,10 @@ void KernelLauncher::LoadKernels() { fPartialsDynamicScaling = gpu->GetFunction( "kernelPartialsDynamicScalingSlow"); fPartialsDynamicScalingAccumulate = gpu->GetFunction( - "kernelPartialsDynamicScalingAccumulate"); // TODO Write kernel + "kernelPartialsDynamicScalingAccumulate"); // TODO Write kernel } } - + if (kPaddedStateCount == 4) { // TODO Temporary fPartialsDynamicScalingAccumulateDifference = gpu->GetFunction( "kernelPartialsDynamicScalingAccumulateDifference"); @@ -405,28 +404,37 @@ void KernelLauncher::LoadKernels() { fPartialsDynamicScalingAccumulateReciprocal = gpu->GetFunction( "kernelPartialsDynamicScalingAccumulateReciprocal"); } - + fIntegrateLikelihoods = gpu->GetFunction("kernelIntegrateLikelihoods"); - + fIntegrateLikelihoodsSecondDeriv = gpu->GetFunction("kernelIntegrateLikelihoodsSecondDeriv"); - + fIntegrateLikelihoodsMulti = gpu->GetFunction("kernelIntegrateLikelihoodsMulti"); - + fIntegrateLikelihoodsFixedScaleMulti = gpu->GetFunction("kernelIntegrateLikelihoodsFixedScaleMulti"); - + fSumSites1 = gpu->GetFunction("kernelSumSites1"); fSumSites2 = gpu->GetFunction("kernelSumSites2"); fSumSites3 = gpu->GetFunction("kernelSumSites3"); + fInnerBastaPartialsCoalescent = gpu->GetFunction("kernelInnerBastaPartialsCoalescent"); + fReduceWithinInterval = gpu->GetFunction("kernelBastaReduceWithinInterval"); + fReduceWithinIntervalSerial = gpu->GetFunction("kernelBastaReduceWithinIntervalSerial"); + fReduceAcrossInterval = gpu->GetFunction("kernelBastaReduceAcrossInterval"); + fPreProcessBastaFlags = gpu->GetFunction("kernelPreProcessBastaFlags"); + fAccumulateCarryOut = gpu->GetFunction("kernelAccumulateCarryOut"); + fAccumulateCarryOutFinal = gpu->GetFunction("kernelAccumulateCarryOutFinal"); + + fReorderPatterns = gpu->GetFunction("kernelReorderPatterns"); // partitioning and multi-op kernels - if (kPaddedStateCount == 4) { + if (kPaddedStateCount == 4) { fPartialsPartialsByPatternBlockCoherentMulti = gpu->GetFunction( "kernelPartialsPartialsNoScaleMulti"); fPartialsPartialsByPatternBlockCoherentPartition = gpu->GetFunction( - "kernelPartialsPartialsNoScalePartition"); + "kernelPartialsPartialsNoScalePartition"); fPartialsPartialsByPatternBlockFixedScalingMulti = gpu->GetFunction( "kernelPartialsPartialsFixedScaleMulti"); @@ -507,9 +515,9 @@ void KernelLauncher::LoadKernels() { "kernelPartialsDynamicScalingAccumulateByPartition"); } } - + fIntegrateLikelihoodsPartition = gpu->GetFunction("kernelIntegrateLikelihoodsPartition"); - + fSumSites1Partition = gpu->GetFunction("kernelSumSites1Partition"); } #endif // !FW_OPENCL_TESTING @@ -552,7 +560,7 @@ void KernelLauncher::ReorderPatterns(GPUPtr dPartials, dPartials, dStates, dStatesSort, dTipOffsets, dTipTypes, dPatternsNewOrder, dPatternWeights, dPatternWeightsSort, patternCount, paddedPatternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::ReorderPatterns\n"); #endif @@ -625,7 +633,7 @@ void KernelLauncher::GetTransitionProbabilitiesSquareMulti(GPUPtr dMatrices, bgTransitionProbabilitiesGrid.x *= totalMatrix; - // Transposed (interchanged Ievc and Evec) + // Transposed (interchanged Ievc and Evec) int parameterCountV = 6; int totalParameterCount = 9; gpu->LaunchKernel(fMatrixMulADBMulti, @@ -636,7 +644,7 @@ void KernelLauncher::GetTransitionProbabilitiesSquareMulti(GPUPtr dMatrices, totalMatrix); bgTransitionProbabilitiesGrid.x /= totalMatrix; // Reset value - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::GetTransitionProbabilitiesSquareMulti\n"); #endif @@ -655,7 +663,7 @@ void KernelLauncher::GetTransitionProbabilitiesSquare(GPUPtr dMatrices, bgTransitionProbabilitiesGrid.x *= totalMatrix; - // Transposed (interchanged Ievc and Evec) + // Transposed (interchanged Ievc and Evec) int parameterCountV = 6; int totalParameterCount = 9; gpu->LaunchKernel(fMatrixMulADB, @@ -667,7 +675,7 @@ void KernelLauncher::GetTransitionProbabilitiesSquare(GPUPtr dMatrices, bgTransitionProbabilitiesGrid.x /= totalMatrix; // Reset value - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::GetTransitionProbabilitiesSquare\n"); #endif @@ -683,10 +691,10 @@ void KernelLauncher::GetTransitionProbabilitiesSquareFirstDeriv(GPUPtr dMatrices #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::GetTransitionProbabilitiesSquareFirstDeriv\n"); #endif - + bgTransitionProbabilitiesGrid.x *= totalMatrix; - - // Transposed (interchanged Ievc and Evec) + + // Transposed (interchanged Ievc and Evec) int parameterCountV = 6; int totalParameterCount = 9; gpu->LaunchKernel(fMatrixMulADBFirstDeriv, @@ -695,10 +703,10 @@ void KernelLauncher::GetTransitionProbabilitiesSquareFirstDeriv(GPUPtr dMatrices dMatrices, dPtrQueue, dIevc, dEigenValues, dEvec, distanceQueue, kPaddedStateCount, kPaddedStateCount, totalMatrix); - + bgTransitionProbabilitiesGrid.x /= totalMatrix; // Reset value - - + + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::GetTransitionProbabilitiesSquareFirstDeriv\n"); #endif @@ -714,10 +722,10 @@ void KernelLauncher::GetTransitionProbabilitiesSquareSecondDeriv(GPUPtr dMatrice #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::GetTransitionProbabilitiesSquareSecondDeriv\n"); #endif - + bgTransitionProbabilitiesGrid.x *= totalMatrix; - - // Transposed (interchanged Ievc and Evec) + + // Transposed (interchanged Ievc and Evec) int parameterCountV = 6; int totalParameterCount = 9; gpu->LaunchKernel(fMatrixMulADBSecondDeriv, @@ -726,10 +734,10 @@ void KernelLauncher::GetTransitionProbabilitiesSquareSecondDeriv(GPUPtr dMatrice dMatrices, dPtrQueue, dIevc, dEigenValues, dEvec, distanceQueue, kPaddedStateCount, kPaddedStateCount, totalMatrix); - + bgTransitionProbabilitiesGrid.x /= totalMatrix; // Reset value - - + + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::GetTransitionProbabilitiesSquareSecondDeriv\n"); #endif @@ -750,7 +758,6 @@ void KernelLauncher::PartialsStatesEdgeFirstDerivatives(GPUPtr out, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::PartialsStatesEdgeFirstDerivatives\n"); #endif -DEBUG_START_TIME(); unsigned int saved = bgDerivativeGrid.y; bgDerivativeGrid.y = nodeCount; @@ -765,7 +772,6 @@ DEBUG_START_TIME(); } bgDerivativeGrid.y = saved; -DEBUG_END_TIME(); #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsStatesEdgeFirstDerivatives\n"); #endif @@ -785,7 +791,7 @@ void KernelLauncher::PartialsPartialsEdgeFirstDerivatives(GPUPtr out, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::PartialsPartialsEdgeFirstDerivatives\n"); #endif -DEBUG_START_TIME(); + unsigned int saved = bgDerivativeGrid.y; bgDerivativeGrid.y = nodeCount; @@ -804,7 +810,7 @@ DEBUG_START_TIME(); } bgDerivativeGrid.y = saved; -DEBUG_END_TIME(); + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsPartialsEdgeFirstDerivatives\n"); #endif @@ -814,7 +820,7 @@ void KernelLauncher::PartialsStatesCrossProducts(GPUPtr out, GPUPtr states0, GPUPtr partials, GPUPtr lengths, - GPUPtr instructions, + GPUPtr instructions, GPUPtr categoryWeights, GPUPtr patternWeights, unsigned int instructionOffset, @@ -857,7 +863,7 @@ void KernelLauncher::PartialsStatesCrossProducts(GPUPtr out, void KernelLauncher::PartialsPartialsCrossProducts(GPUPtr out, GPUPtr partials, GPUPtr lengths, - GPUPtr instructions, + GPUPtr instructions, GPUPtr categoryWeights, GPUPtr patternWeights, unsigned int instructionOffset, @@ -885,12 +891,12 @@ void KernelLauncher::PartialsPartialsCrossProducts(GPUPtr out, gpu->LaunchKernel(fPartialsPartialsCrossProducts, bgCrossProductBlock, grid, 6, 12, - out, partials, lengths, instructions, + out, partials, lengths, instructions, categoryWeights, patternWeights, instructionOffset, patternCount, nodeCount, categoryCount, rateOffset, accumulate); - - gpu->SynchronizeDevice(); + + gpu->SynchronizeDevice(); #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsPartialsCrossProducts\n"); @@ -970,14 +976,14 @@ void KernelLauncher::PartialsStatesGrowing(GPUPtr partials1, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::PartialsStatesGrowing\n"); #endif -DEBUG_START_TIME(); + gpu->LaunchKernel(fPartialsStatesGrowing, bgPeelingBlock, bgPeelingGrid, 5, 6, partials1, states2, partials3, matrices1, matrices2, patternCount); gpu->SynchronizeDevice(); -DEBUG_END_TIME(); + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsStatesGrowing\n"); #endif @@ -994,14 +1000,14 @@ void KernelLauncher::PartialsPartialsGrowing(GPUPtr partials1, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::PartialsPartialsGrowing\n"); #endif -DEBUG_START_TIME(); + gpu->LaunchKernel(fPartialsPartialsGrowing, bgPeelingBlock, bgPeelingGrid, 5, 6, partials1, partials2, partials3, matrices1, matrices2, patternCount); gpu->SynchronizeDevice(); -DEBUG_END_TIME(); + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsPartialsGrowing\n"); #endif @@ -1035,7 +1041,7 @@ void KernelLauncher::PartialsPartialsPruningDynamicCheckScaling(GPUPtr partials1 bgPeelingBlock, bgPeelingGrid, 6, 7, partials1, partials2, partials3, matrices1, matrices2, dRescalingTrigger, - patternCount); + patternCount); gpu->SynchronizeDevice(); // printf("hRescalingTrigger (no factors) %d\n", *hRescalingTrigger); @@ -1047,13 +1053,13 @@ void KernelLauncher::PartialsPartialsPruningDynamicCheckScaling(GPUPtr partials1 dScalingFactors[writeScalingIndex] = gpu->AllocateMemory(patternCount * sizeReal); dScalingFactorsMaster[writeScalingIndex] = dScalingFactors[writeScalingIndex]; } - + if (dScalingFactors[cumulativeScalingIndex] != dScalingFactorsMaster[cumulativeScalingIndex]) { gpu->MemcpyDeviceToDevice(dScalingFactorsMaster[cumulativeScalingIndex], dScalingFactors[cumulativeScalingIndex], sizeReal *patternCount); gpu->SynchronizeDevice(); dScalingFactors[cumulativeScalingIndex] = dScalingFactorsMaster[cumulativeScalingIndex]; } - + gpu->LaunchKernel(fPartialsDynamicScalingAccumulateReciprocal, bgScaleBlock, bgScaleGrid, 3, 4, @@ -1062,31 +1068,31 @@ void KernelLauncher::PartialsPartialsPruningDynamicCheckScaling(GPUPtr partials1 } } else { *hRescalingTrigger = 0; - // Compute partials with known rescalings + // Compute partials with known rescalings gpu->LaunchKernel(fPartialsPartialsByPatternBlockFixedCheckScaling, bgPeelingBlock, bgPeelingGrid, 7, 8, partials1, partials2, partials3, matrices1, matrices2, dScalingFactors[readScalingIndex], dRescalingTrigger, - patternCount); - + patternCount); + gpu->SynchronizeDevice(); // printf("hRescalingTrigger (existing factors) %d\n", *hRescalingTrigger); if (*hRescalingTrigger) { // check if any partials need rescaling if (dScalingFactors[writeScalingIndex] != dScalingFactorsMaster[writeScalingIndex]) dScalingFactors[writeScalingIndex] = dScalingFactorsMaster[writeScalingIndex]; - + if (dScalingFactors[writeScalingIndex] == 0) { dScalingFactors[writeScalingIndex] = gpu->AllocateRealMemory(patternCount); dScalingFactorsMaster[writeScalingIndex] = dScalingFactors[writeScalingIndex]; } - + if (dScalingFactors[cumulativeScalingIndex] != dScalingFactorsMaster[cumulativeScalingIndex]) { gpu->MemcpyDeviceToDevice(dScalingFactorsMaster[cumulativeScalingIndex], dScalingFactors[cumulativeScalingIndex], sizeReal * patternCount); gpu->SynchronizeDevice(); dScalingFactors[cumulativeScalingIndex] = dScalingFactorsMaster[cumulativeScalingIndex]; } - + gpu->LaunchKernel(fPartialsDynamicScalingAccumulateDifference, bgScaleBlock, bgScaleGrid, 4, 5, @@ -1100,7 +1106,7 @@ void KernelLauncher::PartialsPartialsPruningDynamicCheckScaling(GPUPtr partials1 #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsPartialsPruningDynamicCheckScaling\n"); #endif - + } void KernelLauncher::PartialsPartialsPruningMulti(GPUPtr partials, @@ -1173,9 +1179,9 @@ void KernelLauncher::PartialsPartialsPruningDynamicScaling(GPUPtr partials1, bgPeelingBlock, bgPeelingGrid, 6, 7, partials1, partials2, partials3, matrices1, matrices2, scalingFactors, - patternCount); + patternCount); } else if (doRescaling != 0) { - // Compute partials without any rescaling + // Compute partials without any rescaling if (endPattern != 0) { gpu->LaunchKernelConcurrent(fPartialsPartialsByPatternBlockCoherentPartition, @@ -1205,7 +1211,7 @@ void KernelLauncher::PartialsPartialsPruningDynamicScaling(GPUPtr partials1, startPattern, endPattern); } } - + } else { // Compute partials with known rescalings if (endPattern != 0) { @@ -1223,7 +1229,7 @@ void KernelLauncher::PartialsPartialsPruningDynamicScaling(GPUPtr partials1, 6, 7, partials1, partials2, partials3, matrices1, matrices2, scalingFactors, - patternCount); + patternCount); } } @@ -1232,7 +1238,7 @@ void KernelLauncher::PartialsPartialsPruningDynamicScaling(GPUPtr partials1, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsPartialsPruningDynamicScaling\n"); #endif - + } @@ -1263,7 +1269,7 @@ void KernelLauncher::StatesPartialsPruningMulti(GPUPtr states, bgPeelingBlock, bgPeelingGrid, 5, 7, states, partials, matrices, scalingFactors, ptrOffsets, - gridStartOp, patternCount); + gridStartOp, patternCount); } bgPeelingGrid.x = tmpGridx; @@ -1317,7 +1323,7 @@ void KernelLauncher::StatesPartialsPruningDynamicScaling(GPUPtr states1, int tmpGridx = bgPeelingGrid.x; bgPeelingGrid.x = (launchPatternCount + blockPatternCount - 1) / blockPatternCount; } - + if (doRescaling != 0) { // Compute partials without any rescaling if (endPattern != 0) { @@ -1336,7 +1342,7 @@ void KernelLauncher::StatesPartialsPruningDynamicScaling(GPUPtr states1, states1, partials2, partials3, matrices1, matrices2, patternCount); } - + // Rescale partials and save scaling factors if (doRescaling > 0) { if (endPattern == 0 ) { @@ -1360,7 +1366,7 @@ void KernelLauncher::StatesPartialsPruningDynamicScaling(GPUPtr states1, } } - } else { + } else { // Compute partials with known rescalings #ifdef BEAGLE_FILL_4_STATE_SCALAR_SP @@ -1414,11 +1420,11 @@ void KernelLauncher::StatesPartialsPruningDynamicScaling(GPUPtr states1, bgPeelingGrid.x = gridX; } #endif - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"\t\tLeaving KernelLauncher::StatesPartialsPruningDynamicScaling\n"); #endif - + } void KernelLauncher::StatesStatesPruningMulti(GPUPtr states, @@ -1450,7 +1456,7 @@ void KernelLauncher::StatesStatesPruningMulti(GPUPtr states, states, partials, matrices, scalingFactors, ptrOffsets, gridStartOp, patternCount); } - + bgPeelingGrid.x = tmpGridx; #ifdef BEAGLE_DEBUG_FLOW @@ -1504,7 +1510,7 @@ void KernelLauncher::StatesStatesPruningDynamicScaling(GPUPtr states1, } if (doRescaling != 0) { - + // Compute partials without any rescaling if (endPattern != 0) { gpu->LaunchKernelConcurrent(fStatesStatesByPatternBlockCoherentPartition, @@ -1522,7 +1528,7 @@ void KernelLauncher::StatesStatesPruningDynamicScaling(GPUPtr states1, patternCount); } - // Rescale partials and save scaling factors + // Rescale partials and save scaling factors if (doRescaling > 0) { if (endPattern == 0 ) { KernelLauncher::RescalePartials(partials3, scalingFactors, cumulativeScaling, @@ -1544,9 +1550,9 @@ void KernelLauncher::StatesStatesPruningDynamicScaling(GPUPtr states1, , streamIndex, -1, startPattern, endPattern); } } - + } else { - + // Compute partials with known rescalings #ifdef BEAGLE_FILL_4_STATE_SCALAR_SS if (kPaddedStateCount == 4) { @@ -1598,7 +1604,7 @@ void KernelLauncher::StatesStatesPruningDynamicScaling(GPUPtr states1, bgPeelingGrid.x = gridX; } #endif - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::StatesStatesPruningDynamicScaling\n"); #endif @@ -1614,12 +1620,12 @@ void KernelLauncher::IntegrateLikelihoodsDynamicScaling(GPUPtr dResult, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::IntegrateLikelihoodsDynamicScaling\n"); #endif - + gpu->LaunchKernel(fIntegrateLikelihoodsDynamicScaling, bgLikelihoodBlock, bgLikelihoodGrid, 5, 7, dResult, dRootPartials, dWeights, dFrequencies, dRootScalingFactors, - categoryCount,patternCount); + categoryCount,patternCount); #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::IntegrateLikelihoodsDynamicScaling\n"); #endif @@ -1639,7 +1645,7 @@ void KernelLauncher::IntegrateLikelihoodsDynamicScalingPartition(GPUPtr dResult, #endif Dim3Int bgLikelihoodPartitionGrid = Dim3Int(gridSize); - + gpu->LaunchKernel(fIntegrateLikelihoodsDynamicScalingPartition, bgLikelihoodBlock, bgLikelihoodPartitionGrid, 6, 8, @@ -1665,14 +1671,14 @@ void KernelLauncher::IntegrateLikelihoodsDynamicScalingSecondDeriv(GPUPtr dResul #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::IntegrateLikelihoodsDynamicScalingSecondDeriv\n"); #endif - + gpu->LaunchKernel(fIntegrateLikelihoodsDynamicScalingSecondDeriv, bgLikelihoodBlock, bgLikelihoodGrid, 9, 11, dResult, dFirstDerivResult, dSecondDerivResult, dRootPartials, dRootFirstDeriv, dRootSecondDeriv, dWeights, dFrequencies, dRootScalingFactors, - categoryCount, patternCount); + categoryCount, patternCount); #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::IntegrateLikelihoodsDynamicScalingSecondDeriv\n"); #endif @@ -1741,7 +1747,7 @@ void KernelLauncher::PartialsPartialsEdgeLikelihoodsSecondDeriv(GPUPtr dPartials #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"\t\tEntering KernelLauncher::PartialsPartialsEdgeLikelihoodsSecondDeriv\n"); #endif - + gpu->LaunchKernel(fPartialsPartialsEdgeLikelihoodsSecondDeriv, bgPeelingBlock, bgPeelingGrid, 8, 9, @@ -1749,11 +1755,11 @@ void KernelLauncher::PartialsPartialsEdgeLikelihoodsSecondDeriv(GPUPtr dPartials dParentPartials, dChildParials, dTransMatrix, dFirstDerivMatrix, dSecondDerivMatrix, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::PartialsPartialsEdgeLikelihoodsSecondDeriv\n"); #endif - + } void KernelLauncher::StatesPartialsEdgeLikelihoods(GPUPtr dPartialsTmp, @@ -1765,7 +1771,7 @@ void KernelLauncher::StatesPartialsEdgeLikelihoods(GPUPtr dPartialsTmp, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"\t\tEntering KernelLauncher::StatesPartialsEdgeLikelihoods\n"); #endif - + #ifdef FW_OPENCL // fix for Apple CPU OpenCL limitations size_t blockX = bgPeelingBlock.x; @@ -1783,7 +1789,7 @@ void KernelLauncher::StatesPartialsEdgeLikelihoods(GPUPtr dPartialsTmp, bgPeelingBlock, bgPeelingGrid, 4, 5, dPartialsTmp, dParentPartials, dChildStates, dTransMatrix, - patternCount); + patternCount); #ifdef FW_OPENCL // restore values if used fix for Apple CPU OpenCL limitations @@ -1792,11 +1798,11 @@ void KernelLauncher::StatesPartialsEdgeLikelihoods(GPUPtr dPartialsTmp, bgPeelingGrid.x = gridX; } #endif - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::StatesPartialsEdgeLikelihoods\n"); #endif - + } void KernelLauncher::StatesPartialsEdgeLikelihoodsByPartition(GPUPtr dPartialsTmp, @@ -1853,7 +1859,7 @@ void KernelLauncher::StatesPartialsEdgeLikelihoodsSecondDeriv(GPUPtr dPartialsTm AppleCPUImplementation = true; } #endif - + gpu->LaunchKernel(fStatesPartialsEdgeLikelihoodsSecondDeriv, bgPeelingBlock, bgPeelingGrid, 8, 9, @@ -1861,11 +1867,11 @@ void KernelLauncher::StatesPartialsEdgeLikelihoodsSecondDeriv(GPUPtr dPartialsTm dParentPartials, dChildStates, dTransMatrix, dFirstDerivMatrix, dSecondDerivMatrix, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::StatesPartialsEdgeLikelihoodsSecondDeriv\n"); #endif - + #ifdef FW_OPENCL // restore values if used fix for Apple CPU OpenCL limitations if (AppleCPUImplementation) { @@ -1884,7 +1890,7 @@ void KernelLauncher::AccumulateFactorsDynamicScaling(GPUPtr dScalingFactors, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::AccumulateFactorsDynamicScaling\n"); #endif - + int parameterCountV = 3; int totalParameterCount = 5; gpu->LaunchKernel(fAccumulateFactorsDynamicScaling, @@ -1892,11 +1898,11 @@ void KernelLauncher::AccumulateFactorsDynamicScaling(GPUPtr dScalingFactors, parameterCountV, totalParameterCount, dScalingFactors, dNodePtrQueue, dRootScalingFactors, nodeCount, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::AccumulateFactorsDynamicScaling\n"); #endif - + } @@ -1914,8 +1920,8 @@ void KernelLauncher::AccumulateFactorsDynamicScalingByPartition(GPUPtr dScalingF Dim3Int bgAccumulatePartitionGrid = Dim3Int(partitionPatternCount / kPatternBlockSize); if (partitionPatternCount % kPatternBlockSize != 0) - bgAccumulatePartitionGrid.x += 1; - + bgAccumulatePartitionGrid.x += 1; + int parameterCountV = 3; int totalParameterCount = 6; gpu->LaunchKernel(fAccumulateFactorsDynamicScalingByPartition, @@ -1923,11 +1929,11 @@ void KernelLauncher::AccumulateFactorsDynamicScalingByPartition(GPUPtr dScalingF parameterCountV, totalParameterCount, dScalingFactors, dNodePtrQueue, dRootScalingFactors, nodeCount, startPattern, endPattern); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::AccumulateFactorsDynamicScalingByPartition\n"); #endif - + } void KernelLauncher::AccumulateFactorsAutoScaling(GPUPtr dScalingFactors, @@ -1939,7 +1945,7 @@ void KernelLauncher::AccumulateFactorsAutoScaling(GPUPtr dScalingFactors, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::AccumulateFactorsAutoScaling\n"); #endif - + int parameterCountV = 3; int totalParameterCount = 6; gpu->LaunchKernel(fAccumulateFactorsAutoScaling, @@ -1951,7 +1957,7 @@ void KernelLauncher::AccumulateFactorsAutoScaling(GPUPtr dScalingFactors, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::AccumulateFactorsAutoScaling\n"); #endif - + } @@ -1962,8 +1968,8 @@ void KernelLauncher::RemoveFactorsDynamicScaling(GPUPtr dScalingFactors, unsigned int patternCount) { #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::RemoveFactorsDynamicScaling\n"); -#endif - +#endif + int parameterCountV = 3; int totalParameterCount = 5; gpu->LaunchKernel(fRemoveFactorsDynamicScaling, @@ -1974,7 +1980,7 @@ void KernelLauncher::RemoveFactorsDynamicScaling(GPUPtr dScalingFactors, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::RemoveFactorsDynamicScaling\n"); -#endif +#endif } @@ -1986,13 +1992,13 @@ void KernelLauncher::RemoveFactorsDynamicScalingByPartition(GPUPtr dScalingFacto int endPattern) { #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::RemoveFactorsDynamicScalingByPartition\n"); -#endif - +#endif + int partitionPatternCount = endPattern - startPattern; Dim3Int bgAccumulatePartitionGrid = Dim3Int(partitionPatternCount / kPatternBlockSize); if (partitionPatternCount % kPatternBlockSize != 0) - bgAccumulatePartitionGrid.x += 1; + bgAccumulatePartitionGrid.x += 1; int parameterCountV = 3; int totalParameterCount = 6; @@ -2004,7 +2010,7 @@ void KernelLauncher::RemoveFactorsDynamicScalingByPartition(GPUPtr dScalingFacto #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::RemoveFactorsDynamicScalingByPartition\n"); -#endif +#endif } @@ -2013,13 +2019,13 @@ void KernelLauncher::ResetFactorsDynamicScalingByPartition(GPUPtr dScalingFactor int endPattern) { #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::ResetFactorsDynamicScalingByPartition\n"); -#endif - +#endif + int partitionPatternCount = endPattern - startPattern; Dim3Int bgAccumulatePartitionGrid = Dim3Int(partitionPatternCount / kPatternBlockSize); if (partitionPatternCount % kPatternBlockSize != 0) - bgAccumulatePartitionGrid.x += 1; + bgAccumulatePartitionGrid.x += 1; int parameterCountV = 1; int totalParameterCount = 3; @@ -2031,23 +2037,23 @@ void KernelLauncher::ResetFactorsDynamicScalingByPartition(GPUPtr dScalingFactor #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::ResetFactorsDynamicScalingByPartition\n"); -#endif +#endif } void KernelLauncher::RescalePartials(GPUPtr partials3, GPUPtr scalingFactors, - GPUPtr cumulativeScaling, + GPUPtr cumulativeScaling, unsigned int patternCount, unsigned int categoryCount, unsigned int fillWithOnes, int streamIndex, int waitIndex) { - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::RescalePartials\n"); -#endif - +#endif + // TODO: remove fillWithOnes and leave it up to client? // printf("RESCALE ON STREAM %d\n",streamIndex ); // Rescale partials and save scaling factors @@ -2069,17 +2075,17 @@ void KernelLauncher::RescalePartials(GPUPtr partials3, exit(0); } } - + // TODO: Totally incoherent for kPaddedStateCount == 4 - + if (cumulativeScaling != 0) { - - if (kSlowReweighing) { + + if (kSlowReweighing) { fprintf(stderr,"Simultaneous slow reweighing and accumulation is not yet implemented.\n"); exit(-1); - // TODO: add support for accumulate scaling as you rescale for SLOW_REWEIGHING + // TODO: add support for accumulate scaling as you rescale for SLOW_REWEIGHING } - + int parameterCountV = 3; int totalParameterCount = 4; gpu->LaunchKernelConcurrent(fPartialsDynamicScalingAccumulate, @@ -2098,7 +2104,7 @@ void KernelLauncher::RescalePartials(GPUPtr partials3, partials3, scalingFactors, categoryCount); } - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::RescalePartials\n"); #endif @@ -2106,7 +2112,7 @@ void KernelLauncher::RescalePartials(GPUPtr partials3, void KernelLauncher::RescalePartialsByPartition(GPUPtr partials3, GPUPtr scalingFactors, - GPUPtr cumulativeScaling, + GPUPtr cumulativeScaling, unsigned int patternCount, unsigned int categoryCount, unsigned int fillWithOnes, @@ -2114,11 +2120,11 @@ void KernelLauncher::RescalePartialsByPartition(GPUPtr partials3, int waitIndex, int startPattern, int endPattern) { - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::RescalePartialsByPartition\n"); -#endif - +#endif + int partitionPatternCount = endPattern - startPattern; Dim3Int bgScalePartitionGrid = bgScaleGrid; @@ -2126,7 +2132,7 @@ void KernelLauncher::RescalePartialsByPartition(GPUPtr partials3, if (kCPUImplementation) { bgScalePartitionGrid.x = partitionPatternCount/kPatternBlockSize; if (partitionPatternCount % kPatternBlockSize != 0) - bgScalePartitionGrid.x += 1; + bgScalePartitionGrid.x += 1; } else { if (kSlowReweighing) { fprintf(stderr,"Slow reweighing and partitioning not yet implemented\n"); @@ -2135,16 +2141,16 @@ void KernelLauncher::RescalePartialsByPartition(GPUPtr partials3, if (kPaddedStateCount == 4) { bgScalePartitionGrid.x = partitionPatternCount / 4; if (partitionPatternCount % 4 != 0) { - bgScalePartitionGrid.x += 1; // + bgScalePartitionGrid.x += 1; // // fprintf(stderr,"PATTERNS SHOULD BE PADDED! Inform Marc, please.\n"); // exit(-1); - } - } else { + } + } else { fprintf(stderr,"Partitioning and state count != 4 not implemented\n"); exit(-1); } } - } + } // printf("p %d, s %2d, e %2d, bgScaleGrid.x %2d, bgScalePartitionGrid.x %2d\n", partials3, startPattern, endPattern, bgScaleGrid.x, bgScalePartitionGrid.x ); @@ -2154,8 +2160,8 @@ void KernelLauncher::RescalePartialsByPartition(GPUPtr partials3, exit(0); } } - - // TODO: Totally incoherent for kPaddedStateCount == 4 + + // TODO: Totally incoherent for kPaddedStateCount == 4 if (cumulativeScaling != 0) { int parameterCountV = 3; int totalParameterCount = 7; @@ -2190,7 +2196,7 @@ void KernelLauncher::IntegrateLikelihoods(GPUPtr dResult, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"\t\tEntering KernelLauncher::IntegrateLikelihoods\n"); #endif - + int parameterCountV = 4; int totalParameterCount = 6; gpu->LaunchKernel(fIntegrateLikelihoods, @@ -2198,11 +2204,11 @@ void KernelLauncher::IntegrateLikelihoods(GPUPtr dResult, parameterCountV, totalParameterCount, dResult, dRootPartials, dWeights, dFrequencies, categoryCount, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::IntegrateLikelihoods\n"); #endif - + } void KernelLauncher::IntegrateLikelihoodsPartition(GPUPtr dResult, @@ -2218,7 +2224,7 @@ void KernelLauncher::IntegrateLikelihoodsPartition(GPUPtr dResult, #endif Dim3Int bgLikelihoodPartitionGrid = Dim3Int(gridSize); - + int parameterCountV = 5; int totalParameterCount = 7; gpu->LaunchKernel(fIntegrateLikelihoodsPartition, @@ -2226,11 +2232,11 @@ void KernelLauncher::IntegrateLikelihoodsPartition(GPUPtr dResult, parameterCountV, totalParameterCount, dResult, dRootPartials, dWeights, dFrequencies, dPtrOffsets, categoryCount, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::IntegrateLikelihoodsPartition\n"); #endif - + } @@ -2247,7 +2253,7 @@ void KernelLauncher::IntegrateLikelihoodsSecondDeriv(GPUPtr dResult, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"\t\tEntering KernelLauncher::IntegrateLikelihoodsSecondDeriv\n"); #endif - + int parameterCountV = 8; int totalParameterCount = 10; gpu->LaunchKernel(fIntegrateLikelihoodsSecondDeriv, @@ -2257,11 +2263,11 @@ void KernelLauncher::IntegrateLikelihoodsSecondDeriv(GPUPtr dResult, dRootPartials, dRootFirstDeriv, dRootSecondDeriv, dWeights, dFrequencies, categoryCount, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::IntegrateLikelihoodsSecondDeriv\n"); #endif - + } @@ -2275,7 +2281,7 @@ void KernelLauncher::IntegrateLikelihoodsMulti(GPUPtr dResult, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"\t\tEntering KernelLauncher::IntegrateLikelihoodsNoLog\n"); #endif - + int parameterCountV = 4; int totalParameterCount = 7; gpu->LaunchKernel(fIntegrateLikelihoodsMulti, @@ -2283,11 +2289,11 @@ void KernelLauncher::IntegrateLikelihoodsMulti(GPUPtr dResult, parameterCountV, totalParameterCount, dResult, dRootPartials, dWeights, dFrequencies, categoryCount, patternCount, takeLog); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::IntegrateLikelihoodsNoLog\n"); #endif - + } void KernelLauncher::IntegrateLikelihoodsFixedScaleMulti(GPUPtr dResult, @@ -2305,13 +2311,13 @@ void KernelLauncher::IntegrateLikelihoodsFixedScaleMulti(GPUPtr dResult, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::IntegrateLikelihoodsFixedScaleMulti\n"); #endif - + gpu->LaunchKernel(fIntegrateLikelihoodsFixedScaleMulti, bgLikelihoodBlock, bgLikelihoodGrid, 8, 12, dResult, dRootPartials, dWeights, dFrequencies, dScalingFactors, dPtrQueue, dMaxScalingFactors, dIndexMaxScalingFactors, - categoryCount, patternCount, subsetCount, subsetIndex); + categoryCount, patternCount, subsetCount, subsetIndex); #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::IntegrateLikelihoodsFixedScaleMulti\n"); #endif @@ -2332,11 +2338,11 @@ void KernelLauncher::SumSites1(GPUPtr dArray1, parameterCountV, totalParameterCount, dArray1, dSum1, dPatternWeights, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::SumSites1\n"); #endif - + } void KernelLauncher::SumSites1Partition(GPUPtr dArray1, @@ -2358,11 +2364,11 @@ void KernelLauncher::SumSites1Partition(GPUPtr dArray1, parameterCountV, totalParameterCount, dArray1, dSum1, dPatternWeights, startPattern, endPattern); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::SumSites1Partition\n"); #endif - + } void KernelLauncher::SumSites2(GPUPtr dArray1, @@ -2382,11 +2388,11 @@ void KernelLauncher::SumSites2(GPUPtr dArray1, parameterCountV, totalParameterCount, dArray1, dSum1, dArray2, dSum2, dPatternWeights, patternCount); - + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::SumSites2\n"); #endif - + } void KernelLauncher::SumSites3(GPUPtr dArray1, @@ -2400,19 +2406,213 @@ void KernelLauncher::SumSites3(GPUPtr dArray1, #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tEntering KernelLauncher::SumSites3\n"); #endif - + int parameterCountV = 7; int totalParameterCount = 8; gpu->LaunchKernel(fSumSites3, bgSumSitesBlock, bgSumSitesGrid, parameterCountV, totalParameterCount, dArray1, dSum1, dArray2, dSum2, dArray3, dSum3, dPatternWeights, - patternCount); - + patternCount); + #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr, "\t\tLeaving KernelLauncher::SumSites3\n"); #endif - + +} + + +void KernelLauncher::InnerBastaPartialsCoalescent(GPUPtr partials, + GPUPtr matrices, + GPUPtr operations, + const GPUPtr sizes, + GPUPtr coalescent, + unsigned int intervalNUmber, + unsigned int start, + unsigned int numOps, + unsigned int patternCount) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tEntering KernelLauncher::InnerBastaPartialsCoalescent\n"); +#endif + + int parameterCountV = 5; + int totalParameterCount = 9; + gpu->LaunchKernel(fInnerBastaPartialsCoalescent, + bgBastaPeelingBlock, bgBastaPeelingGrid, + parameterCountV, totalParameterCount, + partials, matrices, operations, sizes, coalescent, + intervalNUmber, start, numOps, patternCount); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tLeaving KernelLauncher::InnerBastaPartialsCoalescent\n"); +#endif + + } + +// void KernelLauncher::InnerBastaPartialsCoalescent(GPUPtr partials1, +// GPUPtr partials2, +// GPUPtr partials3, +// GPUPtr matrices1, +// GPUPtr matrices2, +// GPUPtr accumulation1, +// GPUPtr accumulation2, +// const GPUPtr sizes, +// GPUPtr coalescent, +// unsigned int intervalNUmber, +// unsigned int patternCount, +// unsigned int child2Index) { +// #ifdef BEAGLE_DEBUG_FLOW +// fprintf(stderr, "\t\tEntering KernelLauncher::InnerBastaPartialsCoalescent\n"); +// #endif +// +// int parameterCountV = 9; +// int totalParameterCount = 12; +// gpu->LaunchKernel(fInnerBastaPartialsCoalescent, +// bgBastaPeelingBlock, bgBastaPeelingGrid, +// parameterCountV, totalParameterCount, +// partials1, partials2, partials3, matrices1, matrices2, accumulation1, accumulation2, sizes, coalescent, +// intervalNUmber, patternCount, child2Index); +// +// #ifdef BEAGLE_DEBUG_FLOW +// fprintf(stderr, "\t\tLeaving KernelLauncher::InnerBastaPartialsCoalescent\n"); +// #endif +// +// } + + void KernelLauncher::reduceWithinInterval(GPUPtr operations, + GPUPtr partials, + GPUPtr dBastaBlockResMemory, + GPUPtr intervals, + unsigned int numOps, + unsigned int start, + unsigned int end, + unsigned int numSubinterval) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tEntering KernelLauncher::ReduceWithinInterval\n"); +#endif + + int parameterCountV = 4; + int totalParameterCount = 8; + gpu->LaunchKernel(fReduceWithinInterval, + bgBastaReductionBlock, bgBastaReductionGrid, + parameterCountV, totalParameterCount, + operations, partials, dBastaBlockResMemory, intervals, numOps, start, end, numSubinterval); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tLeaving KernelLauncher::ReduceWithinInterval\n"); +#endif + +} + + void KernelLauncher::reduceWithinIntervalSerial(GPUPtr operations, + GPUPtr partials, + GPUPtr dBastaMemory, + unsigned int numOps, + unsigned int start, + unsigned int end, + unsigned int kCoalescentBufferLength) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tEntering KernelLauncher::ReduceWithinInterval\n"); +#endif + + int parameterCountV = 4; + int totalParameterCount = 8; + gpu->LaunchKernel(fReduceWithinIntervalSerial, + bgBastaPreBlock, bgBastaPreGrid, + parameterCountV, totalParameterCount, + operations, partials, dBastaMemory, numOps, start, end, kCoalescentBufferLength); + +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tLeaving KernelLauncher::ReduceWithinInterval\n"); +#endif + +} + + void KernelLauncher::preProcessBastaFlags(GPUPtr dBastaInterval, + GPUPtr dBastaFlags, + GPUPtr dBlockSegmentKeysEnd, + unsigned int operationCount, + unsigned int numBlocks) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tEntering KernelLauncher::ReduceAcrossinInterval\n"); +#endif + int parameterCountV = 3; + int totalParameterCount = 5; + + gpu->LaunchKernel(fPreProcessBastaFlags, + bgBastaPreBlock, bgBastaPreGrid, + parameterCountV, totalParameterCount, + dBastaInterval, dBastaFlags, dBlockSegmentKeysEnd, operationCount, numBlocks); +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tLeaving KernelLauncher::ReduceAcrossinInterval\n"); +#endif + +} + + + void KernelLauncher::accumulateCarryOut(GPUPtr dBastaBlockResMemory, + GPUPtr dBastaFinalResMemory, + GPUPtr dBastaFlags, + unsigned int numSubinterval, + unsigned int numSubintervalFinal) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tEntering KernelLauncher::ReduceAcrossinInterval\n"); +#endif + int parameterCountV = 3; + int totalParameterCount = 5; + + gpu->LaunchKernel(fAccumulateCarryOut, + bgBastaReductionBlock, bgBastaReductionGrid, + parameterCountV, totalParameterCount, + dBastaBlockResMemory, dBastaFinalResMemory, dBastaFlags, numSubinterval, numSubintervalFinal); +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tLeaving KernelLauncher::ReduceAcrossinInterval\n"); +#endif + +} + + void KernelLauncher::accumulateCarryOutFinal(GPUPtr dBastaFinalResMemory, + GPUPtr dBastaMemory, + GPUPtr dBastaFlags, + unsigned int numSubinterval, + unsigned int numSubintervalFinal, + unsigned int kCoalescentBufferLength) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tEntering KernelLauncher::ReduceAcrossinInterval\n"); +#endif + int parameterCountV = 3; + int totalParameterCount = 6; + + gpu->LaunchKernel(fAccumulateCarryOutFinal, + bgBastaReductionBlock, bgBastaReductionGrid, + parameterCountV, totalParameterCount, + dBastaFinalResMemory, dBastaMemory, dBastaFlags, numSubinterval, numSubintervalFinal, kCoalescentBufferLength); +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tLeaving KernelLauncher::ReduceAcrossinInterval\n"); +#endif + +} + +void KernelLauncher::reduceAcrossIntervals(GPUPtr dBastaMemory, + GPUPtr distance, + GPUPtr dLogL, + const GPUPtr sizes, + GPUPtr coalescent, + unsigned int intervalNumber, + unsigned int kCoalescentBufferLength) { +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tEntering KernelLauncher::ReduceAcrossinInterval\n"); +#endif + int parameterCountV = 5; + int totalParameterCount = 7; + gpu->LaunchKernel(fReduceAcrossInterval, + bgBastaSumBlock, bgBastaSumGrid, + parameterCountV, totalParameterCount, + dBastaMemory, distance, dLogL, sizes, coalescent, intervalNumber, kCoalescentBufferLength); +#ifdef BEAGLE_DEBUG_FLOW + fprintf(stderr, "\t\tLeaving KernelLauncher::ReduceAcrossinInterval\n"); +#endif + } }; // namespace diff --git a/libhmsbeagle/GPU/KernelLauncher.h b/libhmsbeagle/GPU/KernelLauncher.h old mode 100644 new mode 100755 index 48b4bf5ab..8ceb990a2 --- a/libhmsbeagle/GPU/KernelLauncher.h +++ b/libhmsbeagle/GPU/KernelLauncher.h @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @brief GPU kernel launcher * @@ -44,7 +34,7 @@ class KernelLauncher { private: GPUInterface* gpu; - + GPUFunction fMatrixConvolution; GPUFunction fMatrixTranspose; GPUFunction fMatrixMulADBMulti; @@ -87,7 +77,7 @@ class KernelLauncher { GPUFunction fStatesPartialsEdgeLikelihoods; GPUFunction fStatesPartialsEdgeLikelihoodsByPartition; GPUFunction fStatesPartialsEdgeLikelihoodsSecondDeriv; - + GPUFunction fIntegrateLikelihoodsDynamicScaling; GPUFunction fIntegrateLikelihoodsDynamicScalingPartition; GPUFunction fIntegrateLikelihoodsDynamicScalingSecondDeriv; @@ -116,8 +106,15 @@ class KernelLauncher { GPUFunction fSumSites2; GPUFunction fSumSites3; + GPUFunction fInnerBastaPartialsCoalescent; + GPUFunction fReduceWithinInterval; + GPUFunction fReduceWithinIntervalSerial; + GPUFunction fReduceAcrossInterval; + GPUFunction fPreProcessBastaFlags; + GPUFunction fAccumulateCarryOut; + GPUFunction fAccumulateCarryOutFinal; GPUFunction fReorderPatterns; - + Dim3Int bgTransitionProbabilitiesBlock; Dim3Int bgTransitionProbabilitiesGrid; Dim3Int bgPeelingBlock; @@ -138,26 +135,35 @@ class KernelLauncher { Dim3Int bgMultiNodeSumGrid; Dim3Int bgCrossProductBlock; Dim3Int bgCrossProductGrid; - + Dim3Int bgBastaPeelingBlock; + Dim3Int bgBastaPeelingGrid; + Dim3Int bgBastaReductionBlock; + Dim3Int bgBastaReductionGrid; + Dim3Int bgBastaPreBlock; + Dim3Int bgBastaPreGrid; + Dim3Int bgBastaSumBlock; + Dim3Int bgBastaSumGrid; + + unsigned int kPaddedStateCount; unsigned int kCategoryCount; unsigned int kPatternCount; unsigned int kUnpaddedPatternCount; unsigned int kPatternBlockSize; unsigned int kMatrixBlockSize; - unsigned int kSlowReweighing; + unsigned int kSlowReweighing; unsigned int kMultiplyBlockSize; unsigned int kSumSitesBlockSize; long kFlags; bool kCPUImplementation; bool kAppleCPUImplementation; - + public: KernelLauncher(GPUInterface* inGpu); - + ~KernelLauncher(); - + // void SetupPartitioningKernelGrid(unsigned int partitionBlockCount); // Kernel links @@ -204,8 +210,8 @@ class KernelLauncher { GPUPtr dIevc, GPUPtr dEigenValues, GPUPtr distanceQueue, - unsigned int totalMatrix); - + unsigned int totalMatrix); + void GetTransitionProbabilitiesSquareSecondDeriv(GPUPtr dMatrices, GPUPtr dPtrQueue, GPUPtr dEvec, @@ -254,7 +260,7 @@ class KernelLauncher { int doRescaling, int streamIndex, int waitIndex); - + void StatesPartialsPruningMulti(GPUPtr states, GPUPtr partials, GPUPtr matrices, @@ -279,7 +285,7 @@ class KernelLauncher { int doRescaling, int streamIndex, int waitIndex); - + void StatesStatesPruningMulti(GPUPtr states, GPUPtr partials, GPUPtr matrices, @@ -351,7 +357,7 @@ class KernelLauncher { GPUPtr partials, GPUPtr lengths, GPUPtr instructions, - GPUPtr categoryWeights, + GPUPtr categoryWeights, GPUPtr patternWeights, unsigned int instructionOffset, unsigned int nodeCount, @@ -367,10 +373,10 @@ class KernelLauncher { GPUPtr partials, GPUPtr lengths, GPUPtr instructions, - GPUPtr categoryWeights, + GPUPtr categoryWeights, GPUPtr patternWeights, unsigned int instructionOffset, - unsigned int nodeCount, + unsigned int nodeCount, unsigned int rateOffset, unsigned int patternCount, unsigned int categoryCount, @@ -409,7 +415,7 @@ class KernelLauncher { unsigned int patternCount, unsigned int categoryCount, int gridSize); - + void IntegrateLikelihoodsAutoScaling(GPUPtr dResult, GPUPtr dRootPartials, GPUPtr dWeights, @@ -417,7 +423,7 @@ class KernelLauncher { GPUPtr dRootScalingFactors, unsigned int patternCount, unsigned int categoryCount); - + void IntegrateLikelihoodsDynamicScalingSecondDeriv(GPUPtr dResult, GPUPtr dFirstDerivResult, GPUPtr dSecondDerivResult, @@ -429,7 +435,7 @@ class KernelLauncher { GPUPtr dRootScalingFactors, unsigned int patternCount, unsigned int categoryCount); - + void PartialsPartialsEdgeLikelihoods(GPUPtr dPartialsTmp, GPUPtr dParentPartials, GPUPtr dChildParials, @@ -443,7 +449,7 @@ class KernelLauncher { GPUPtr dPtrOffsets, unsigned int patternCount, int gridSize); - + void PartialsPartialsEdgeLikelihoodsSecondDeriv(GPUPtr dPartialsTmp, GPUPtr dFirstDerivTmp, GPUPtr dSecondDerivTmp, @@ -454,8 +460,8 @@ class KernelLauncher { GPUPtr dSecondDerivMatrix, unsigned int patternCount, unsigned int categoryCount); - - + + void StatesPartialsEdgeLikelihoods(GPUPtr dPartialsTmp, GPUPtr dParentPartials, GPUPtr dChildStates, @@ -470,7 +476,7 @@ class KernelLauncher { GPUPtr dPtrOffsets, unsigned int patternCount, int gridSize); - + void StatesPartialsEdgeLikelihoodsSecondDeriv(GPUPtr dPartialsTmp, GPUPtr dFirstDerivTmp, GPUPtr dSecondDerivTmp, @@ -481,7 +487,7 @@ class KernelLauncher { GPUPtr dSecondDerivMatrix, unsigned int patternCount, unsigned int categoryCount); - + void AccumulateFactorsDynamicScaling(GPUPtr dScalingFactors, GPUPtr dNodePtrQueue, GPUPtr dRootScalingFactors, @@ -501,12 +507,12 @@ class KernelLauncher { unsigned int nodeCount, unsigned int patternCount, unsigned int scaleBufferSize); - + void RemoveFactorsDynamicScaling(GPUPtr dScalingFactors, GPUPtr dNodePtrQueue, GPUPtr dRootScalingFactors, unsigned int nodeCount, - unsigned int patternCount); + unsigned int patternCount); void RemoveFactorsDynamicScalingByPartition(GPUPtr dScalingFactors, GPUPtr dNodePtrQueue, @@ -514,7 +520,7 @@ class KernelLauncher { unsigned int nodeCount, int startPattern, int endPattern); - + void ResetFactorsDynamicScalingByPartition(GPUPtr dScalingFactors, int startPattern, int endPattern); @@ -545,7 +551,7 @@ class KernelLauncher { GPUPtr dFrequencies, unsigned int patternCount, unsigned int categoryCount); - + void IntegrateLikelihoodsPartition(GPUPtr dResult, GPUPtr dRootPartials, GPUPtr dWeights, @@ -565,7 +571,7 @@ class KernelLauncher { GPUPtr dFrequencies, unsigned int patternCount, unsigned int categoryCount); - + void IntegrateLikelihoodsMulti(GPUPtr dResult, GPUPtr dRootPartials, GPUPtr dWeights, @@ -573,7 +579,7 @@ class KernelLauncher { unsigned int patternCount, unsigned int categoryCount, unsigned int takeLog); - + void IntegrateLikelihoodsFixedScaleMulti(GPUPtr dResult, GPUPtr dRootPartials, GPUPtr dWeights, @@ -586,7 +592,7 @@ class KernelLauncher { unsigned int categoryCount, unsigned int subsetCount, unsigned int subsetIndex); - + void SumSites1(GPUPtr dArray1, GPUPtr dSum1, GPUPtr dPatternWeights, @@ -598,14 +604,14 @@ class KernelLauncher { int startPattern, int endPattern, int blockCount); - + void SumSites2(GPUPtr dArray1, GPUPtr dSum1, GPUPtr dArray2, GPUPtr dSum2, GPUPtr dPatternWeights, unsigned int patternCount); - + void SumSites3(GPUPtr dArray1, GPUPtr dSum1, GPUPtr dArray2, @@ -614,9 +620,23 @@ class KernelLauncher { GPUPtr dSum3, GPUPtr dPatternWeights, unsigned int patternCount); - + + // void InnerBastaPartialsCoalescent(GPUPtr partials1, GPUPtr partials2, GPUPtr partials3, GPUPtr matrices1, + // GPUPtr matrices2, GPUPtr accumulation1, GPUPtr accumulation2, GPUPtr sizes, GPUPtr coalescent, unsigned int intervalNumber, unsigned int patternCount, unsigned int child2Index); + + void InnerBastaPartialsCoalescent(GPUPtr partials, GPUPtr matrices, +GPUPtr operations, GPUPtr sizes, GPUPtr coalescent, unsigned int intervalNumber, unsigned int start, unsigned int numOps, unsigned int patternCount); + // void reduceWithinInterval(GPUPtr e, GPUPtr f, GPUPtr g, GPUPtr h, GPUPtr startPartials1, GPUPtr startPartials2, + // GPUPtr endPartials1, GPUPtr endPartials2, unsigned int intervalNUmber, unsigned int child2PartialIndex, unsigned int renew); + + void reduceWithinInterval(GPUPtr operations, GPUPtr partials, GPUPtr dBastaBlockResMemory, GPUPtr intervals, unsigned int numOps, unsigned int start, unsigned int end, unsigned int numSubinterval); + void reduceWithinIntervalSerial(GPUPtr operations, GPUPtr partials, GPUPtr dBastaMemory, unsigned int numOps, unsigned int start, unsigned int end, unsigned int kCoalescentBufferLength); + void reduceAcrossIntervals(GPUPtr dBastaMemory, GPUPtr distance, GPUPtr dLogL, GPUPtr sizes, GPUPtr coalescent, unsigned int intervalNUmber, unsigned int kCoalescentBufferLength); + void preProcessBastaFlags(GPUPtr dBastaInterval, GPUPtr dBastaFlags, GPUPtr dBlockSegmentKeysEnd, unsigned int operationCount, unsigned int numBlocks); + void accumulateCarryOut(GPUPtr dBastaBlockResMemory, GPUPtr dBastaFinalResMemory, GPUPtr dBastaFlags, unsigned int numSubinterval, unsigned int numSubintervalFinal); + void accumulateCarryOutFinal(GPUPtr dBastaFinalResMemory, GPUPtr dBastaMemory, GPUPtr dBastaFlags, unsigned int numSubinterval, unsigned int numSubintervalFinal, unsigned int kCoalescentBufferLength); void SetupKernelBlocksAndGrids(); - + protected: void LoadKernels(); diff --git a/libhmsbeagle/GPU/KernelResource.h b/libhmsbeagle/GPU/KernelResource.h index 477ef8acc..cc6b5c87c 100644 --- a/libhmsbeagle/GPU/KernelResource.h +++ b/libhmsbeagle/GPU/KernelResource.h @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard */ @@ -29,7 +19,7 @@ class KernelResource { public: KernelResource(); - + KernelResource( int inPaddedStateCount, char* inKernelString, @@ -43,12 +33,12 @@ class KernelResource { int inUnpaddedPatternCount, long inFlags ); - + KernelResource(const KernelResource& krIn, char* inKernelCode); - + virtual ~KernelResource(); - + int paddedStateCount; int categoryCount; int patternCount; @@ -62,7 +52,7 @@ class KernelResource { int slowReweighing; int multiplyBlockSize; long flags; - + KernelResource* copy(); }; diff --git a/libhmsbeagle/GPU/cuda_ops.cu b/libhmsbeagle/GPU/cuda_ops.cu new file mode 100644 index 000000000..93e1ff7eb --- /dev/null +++ b/libhmsbeagle/GPU/cuda_ops.cu @@ -0,0 +1,1020 @@ +#include "cuda_ops.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +using thrust::device_ptr; +using thrust::device_pointer_cast; + +template +// This seems to be slow because it inserts cudaStreamSynchronize() +T cuda_max_abs(device_ptr values, int length) +{ + auto in_ptr = thrust::transform_iterator(values, [] __host__ __device__ (T x) {return std::abs(x);}); + + // Don't use `*(thrust::max_element(....))` -- it is slower than thrust::reduce. + + // thrust::reduce is similar in speed to cublasI{s,d}amax. + // using thrust::reduce requires a device-to-host-memcpy, so it is slow! + return thrust::reduce(in_ptr, in_ptr + length, 0.0, thrust::maximum()); +} + +float cuda_max_abs(float* values, int length) +{ + return cuda_max_abs(device_pointer_cast(values), length); +} + +double cuda_max_abs(double* values, int length) +{ + return cuda_max_abs(device_pointer_cast(values), length); +} + +template +void initialize_norm_x_matrix(device_ptr out_ptr, int n, int m) +{ + // Element (row, column) is stored at row * m + column. Its sign comes from its column-major index + // i = column * n + row. + auto indices = thrust::counting_iterator(0); + auto initialize = [n,m] __host__ __device__ (int index) + { + const int row = index / m; + const int column = index % m; + const int i = column * n + row; + thrust::default_random_engine rng; + thrust::uniform_real_distribution dist(0, 1); + + if (i 0.5) + return T(1.0/n); + else + return T(-1.0/n); + }; + + thrust::transform(indices, indices + n*m, // in + out_ptr, // out + initialize); +} + +void initialize_norm_x_matrix(float* data, int n, int m) +{ + initialize_norm_x_matrix(device_pointer_cast(data), n, m); +} + +void initialize_norm_x_matrix(double* data, int n, int m) +{ + initialize_norm_x_matrix(device_pointer_cast(data), n, m); +} + + +// --------------------------------------------------------------------------------------------------- +// Kernels for the Taylor terms, the per-node product/rescale and the root likelihood. +// +// Action partials are stored pattern-fastest: [category][state][pattern], i.e. a (nCategories*nStates) +// x nPatterns row-major matrix, so a CSR row of Q gathers whole rows of x (coalesced over patterns). + +// Reduce v over the block with op; identity must be neutral for op. Every thread gets the result. +// Only for one-dimensional blocks. +template +__device__ T block_reduce(T v, T identity, Op op) +{ + __shared__ T warpResults[32]; + + for (int offset = 16; offset > 0; offset /= 2) + v = op(v, __shfl_down_sync(0xffffffff, v, offset)); + + const int lane = threadIdx.x % 32; + const int warp = threadIdx.x / 32; + if (lane == 0) warpResults[warp] = v; + __syncthreads(); + + if (warp == 0) + { + const int nWarps = (blockDim.x + 31) / 32; + v = (lane < nWarps) ? warpResults[lane] : identity; + for (int offset = 16; offset > 0; offset /= 2) + v = op(v, __shfl_down_sync(0xffffffff, v, offset)); + if (lane == 0) warpResults[0] = v; + } + __syncthreads(); + + return warpResults[0]; +} + +struct MaxOp { template __device__ T operator()(T a, T b) const { return max(a, b); } }; +struct SumOp { template __device__ T operator()(T a, T b) const { return a + b; } }; + +static int nextPowerOfTwo(int n, int cap) +{ + int p = 1; + while (p < n and p < cap) p *= 2; + return p; +} + +// One step w <- scale * (b + alpha * A * x) of Horner's rule for the Taylor polynomial, for each group of the +// batch. A is (nRows, nRows) in CSR; x, b and out are (nRows, nCols) row-major. +// +// For nCols >= 32: blockIdx.z is the group, the 32 lanes of a warp cover 32 adjacent columns of one row, and +// each thread does CPT columns 32 apart. Blocks are ordered rows-fastest, so the blocks in flight read the +// same column panel of x and it stays in L2. +template +__global__ void __launch_bounds__(256) taylor_horner_term_kernel(int nRows, int nCols, const int* __restrict__ rowOffsets, + const int* __restrict__ columns, const T* __restrict__ values, + const TaylorTermBatch batch) +{ + const TaylorTermGroup& g = batch.groups[blockIdx.z]; + const int row = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32; + const int col = blockIdx.y * (32 * CPT) + threadIdx.x % 32; + if (row >= nRows) return; + + const int kBegin = rowOffsets[row]; + const int kEnd = rowOffsets[row + 1]; + const T* b = g.b + (size_t)row * g.ldb + col; + T* out = g.out + (size_t)row * g.ldOut + col; + const T* x = g.x + col; + T acc[CPT]; + T own[CPT]; + + if (col + (CPT - 1) * 32 < nCols) + { +#pragma unroll + for (int q = 0; q < CPT; q++) + { + own[q] = b[q * 32]; + acc[q] = 0; + } + for (int k = kBegin; k < kEnd; k++) + { + const T v = values[k]; + const T* xRow = x + (size_t)columns[k] * g.ldx; +#pragma unroll + for (int q = 0; q < CPT; q++) + acc[q] += v * __ldg(xRow + q * 32); + } +#pragma unroll + for (int q = 0; q < CPT; q++) + out[q * 32] = g.scale * (own[q] + g.alpha * acc[q]); + } + else + { +#pragma unroll + for (int q = 0; q < CPT; q++) + { + own[q] = (col + q * 32 < nCols) ? b[q * 32] : T(0); + acc[q] = 0; + } + for (int k = kBegin; k < kEnd; k++) + { + const T v = values[k]; + const T* xRow = x + (size_t)columns[k] * g.ldx; +#pragma unroll + for (int q = 0; q < CPT; q++) + if (col + q * 32 < nCols) + acc[q] += v * __ldg(xRow + q * 32); + } +#pragma unroll + for (int q = 0; q < CPT; q++) + if (col + q * 32 < nCols) + out[q * 32] = g.scale * (own[q] + g.alpha * acc[q]); + } +} + +// For nCols < 32: the columns of all groups are numbered v = group * nCols + column, and LANES consecutive +// lanes share a row and cover LANES consecutive v. So the lanes share each (column, value) load of A, and +// when the groups' matrices are stored side by side the gathers of x are coalesced across groups too. +template +__global__ void __launch_bounds__(256) taylor_horner_term_narrow_kernel(int nRows, int nCols, const int* __restrict__ rowOffsets, + const int* __restrict__ columns, const T* __restrict__ values, + const TaylorTermBatch batch) +{ + // The lanes read different groups, which shared memory serves without serializing like parameter space. + __shared__ TaylorTermGroup groups[kMaxTaylorGroups]; + for (int i = threadIdx.x; i < batch.count; i += blockDim.x) + groups[i] = batch.groups[i]; + __syncthreads(); + + const int lane = threadIdx.x % 32; + const int row = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * (32 / LANES) + lane / LANES; + const int v = blockIdx.y * LANES + lane % LANES; + if (row >= nRows or v >= batch.count * nCols) return; + + const TaylorTermGroup& g = groups[v / nCols]; + const int col = v % nCols; + const T* x = g.x + col; + const T own = g.b[(size_t)row * g.ldb + col]; + T acc = 0; + for (int k = rowOffsets[row]; k < rowOffsets[row + 1]; k++) + acc += values[k] * __ldg(x + (size_t)columns[k] * g.ldx); + g.out[(size_t)row * g.ldOut + col] = g.scale * (own + g.alpha * acc); +} + +template +void launch_taylor_horner_terms(int nRows, int nCols, const int* rowOffsets, const int* columns, const T* values, + const TaylorTermBatch& batch, cudaStream_t stream) +{ + const int threads = 256; + const dim3 grid((nRows + threads / 32 - 1) / (threads / 32), (nCols + 32 * CPT - 1) / (32 * CPT), batch.count); + taylor_horner_term_kernel<<>>(nRows, nCols, rowOffsets, columns, values, batch); +} + +template +void launch_taylor_horner_terms_narrow(int nRows, int nCols, const int* rowOffsets, const int* columns, const T* values, + const TaylorTermBatch& batch, cudaStream_t stream) +{ + const int threads = 256; + const int rowsPerBlock = (threads / 32) * (32 / LANES); + const dim3 grid((nRows + rowsPerBlock - 1) / rowsPerBlock, (batch.count * nCols + LANES - 1) / LANES); + taylor_horner_term_narrow_kernel<<>>(nRows, nCols, rowOffsets, columns, values, batch); +} + +// Columns per thread for nCols >= 32; BEAGLE_ACTION_CPT (1, 2 or 4) overrides it for tuning. +static int columnsPerThread(int nCols) +{ + static const int forced = getenv("BEAGLE_ACTION_CPT") ? atoi(getenv("BEAGLE_ACTION_CPT")) : 0; + if (forced == 1 or forced == 2 or forced == 4) + return forced; + return (nCols >= 256) ? 4 : (nCols >= 64) ? 2 : 1; +} + +template +void cuda_taylor_horner_terms_impl(int nRows, int nCols, const int* rowOffsets, const int* columns, const T* values, + const TaylorTermBatch& batch, cudaStream_t stream) +{ + if (batch.count == 0) return; + if (nCols >= 32) + { + switch (columnsPerThread(nCols)) + { + case 4: launch_taylor_horner_terms(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + case 2: launch_taylor_horner_terms(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + default: launch_taylor_horner_terms(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + } + return; + } + switch (nextPowerOfTwo(batch.count * nCols, 32)) + { + case 1: launch_taylor_horner_terms_narrow(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + case 2: launch_taylor_horner_terms_narrow(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + case 4: launch_taylor_horner_terms_narrow(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + case 8: launch_taylor_horner_terms_narrow(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + case 16: launch_taylor_horner_terms_narrow(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + default: launch_taylor_horner_terms_narrow(nRows, nCols, rowOffsets, columns, values, batch, stream); break; + } +} + +void cuda_taylor_horner_terms(int nRows, int nCols, const int* rowOffsets, const int* columns, const float* values, + const TaylorTermBatch& batch, cudaStream_t stream) +{ + cuda_taylor_horner_terms_impl(nRows, nCols, rowOffsets, columns, values, batch, stream); +} + +void cuda_taylor_horner_terms(int nRows, int nCols, const int* rowOffsets, const int* columns, const double* values, + const TaylorTermBatch& batch, cudaStream_t stream) +{ + cuda_taylor_horner_terms_impl(nRows, nCols, rowOffsets, columns, values, batch, stream); +} + +// The per-pattern reductions over the rows of an (nRows, nPatterns) row-major matrix use blocks of +// patternsPerBlock x (256 / patternsPerBlock) threads, and split the rows into chunks so that there are +// enough blocks. Each chunk writes one partial result per pattern; a second kernel combines them. +struct RowChunks +{ + int patternsPerBlock; + int rowsPerBlock; + int patternBlocks; + int rowsPerChunk; + int chunks; +}; + +static RowChunks rowChunks(int nRows, int nPatterns) +{ + RowChunks c; + c.patternsPerBlock = nextPowerOfTwo(nPatterns, 32); + c.rowsPerBlock = 256 / c.patternsPerBlock; + c.patternBlocks = (nPatterns + c.patternsPerBlock - 1) / c.patternsPerBlock; + const int targetBlocks = 512; + int chunks = (targetBlocks + c.patternBlocks - 1) / c.patternBlocks; + chunks = std::max(1, std::min({chunks, nRows / (8 * c.rowsPerBlock), 128})); + c.rowsPerChunk = (nRows + chunks - 1) / chunks; + c.chunks = (nRows + c.rowsPerChunk - 1) / c.rowsPerChunk; + return c; +} + +int cuda_row_chunk_count(int nRows, int nPatterns) +{ + return rowChunks(nRows, nPatterns).chunks; +} + +// Reduce v over threadIdx.y (blockDim.y a power of two); the result is valid in the threads with threadIdx.y == 0. +template +__device__ T column_reduce(T v, Op op) +{ + __shared__ T shared[256]; + const int i = threadIdx.y * blockDim.x + threadIdx.x; + shared[i] = v; + __syncthreads(); + for (int stride = blockDim.y / 2; stride > 0; stride /= 2) + { + if (threadIdx.y < stride) + shared[i] = op(shared[i], shared[i + stride * blockDim.x]); + __syncthreads(); + } + return shared[threadIdx.x]; +} + +// 1 / the existing scale factor of pattern p, or 1 without fixed scaling. +template +__device__ T fixed_inverse(const PartialsProduct& product, int p, bool scalersLog) +{ + if (not product.fixedScalingFactors) + return T(1); + const T factor = product.fixedScalingFactors[p]; + return T(1) / (scalersLog ? exp(factor) : factor); +} + +// parent = left * right for each product of the batch (blockIdx.y), divided by any fixed scale factors. +template +__global__ void partials_product_kernel(const PartialsProductBatch batch, size_t n, int nPatterns, bool scalersLog) +{ + const PartialsProduct& product = batch.products[blockIdx.y]; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) + { + T value = product.right ? product.left[i] * product.right[i] : product.left[i]; + if (product.fixedScalingFactors) + value *= fixed_inverse(product, (int)(i % nPatterns), scalersLog); + product.parent[i] = value; + } +} + +// chunkMax[product, chunk, p] = max over the chunk's rows r of left[r, p] * right[r, p] (product = blockIdx.z) +template +__global__ void partials_product_max_kernel(const PartialsProductBatch batch, int nRows, int nPatterns, int rowsPerChunk, T* chunkMax) +{ + const PartialsProduct& product = batch.products[blockIdx.z]; + const int p = blockIdx.x * blockDim.x + threadIdx.x; + const int rowEnd = min(nRows, (blockIdx.y + 1) * rowsPerChunk); + T m = 0; + if (p < nPatterns and product.scalingFactors) + for (int r = blockIdx.y * rowsPerChunk + threadIdx.y; r < rowEnd; r += blockDim.y) + { + const size_t i = (size_t)r * nPatterns + p; + m = max(m, product.right ? product.left[i] * product.right[i] : product.left[i]); + } + m = column_reduce(m, MaxOp()); + if (threadIdx.y == 0 and p < nPatterns) + chunkMax[((size_t)blockIdx.z * gridDim.y + blockIdx.y) * nPatterns + p] = m; +} + +// parent = left * right / m, where m is the largest entry of the pattern (1 if all are 0, or without rescaling). +template +__global__ void partials_product_scale_kernel(const PartialsProductBatch batch, int nRows, int nPatterns, int rowsPerChunk, + const T* chunkMax, bool scalersLog) +{ + const PartialsProduct& product = batch.products[blockIdx.z]; + const int p = blockIdx.x * blockDim.x + threadIdx.x; + + // One row of threads combines the chunks' maxima for the block's patterns. + __shared__ T patternMax[32]; + if (threadIdx.y == 0) + { + T m = 0; + if (p < nPatterns) + for (int c = 0; c < gridDim.y; c++) + m = max(m, chunkMax[((size_t)blockIdx.z * gridDim.y + c) * nPatterns + p]); + patternMax[threadIdx.x] = (m == 0) ? T(1) : m; + } + __syncthreads(); + if (p >= nPatterns) return; + const T m = patternMax[threadIdx.x]; + const T inverse = product.scalingFactors ? 1 / m : fixed_inverse(product, p, scalersLog); + + const int rowEnd = min(nRows, (blockIdx.y + 1) * rowsPerChunk); + for (int r = blockIdx.y * rowsPerChunk + threadIdx.y; r < rowEnd; r += blockDim.y) + { + const size_t i = (size_t)r * nPatterns + p; + product.parent[i] = (product.right ? product.left[i] * product.right[i] : product.left[i]) * inverse; + } + + if (product.scalingFactors and blockIdx.y == 0 and threadIdx.y == 0) + product.scalingFactors[p] = scalersLog ? log(m) : m; +} + +// cumulative[p] += log m of each product in turn (the order of separate calls, so the rounding is the same). +template +__global__ void accumulate_scaling_kernel(const PartialsProductBatch batch, int nPatterns, T* cumulative, bool scalersLog) +{ + const int p = blockIdx.x * blockDim.x + threadIdx.x; + if (p >= nPatterns) return; + T sum = cumulative[p]; + for (int k = 0; k < batch.count; k++) + { + const T* factors = batch.products[k].scalingFactors; + if (factors) + sum += scalersLog ? factors[p] : log(factors[p]); + } + cumulative[p] = sum; +} + +template +void cuda_partials_products_impl(const PartialsProductBatch& batch, int nRows, int nPatterns, T* cumulative, bool scalersLog, + T* scratch, cudaStream_t stream) +{ + if (batch.count == 0) return; + bool rescale = false; + for (int k = 0; k < batch.count; k++) + rescale = rescale or batch.products[k].scalingFactors; + + if (not rescale) + { + const size_t n = (size_t)nRows * nPatterns; + const int blocks = (int)std::min((n + 255) / 256, 4096 / batch.count + 1); + partials_product_kernel<<>>(batch, n, nPatterns, scalersLog); + return; + } + + const RowChunks c = rowChunks(nRows, nPatterns); + const dim3 block(c.patternsPerBlock, c.rowsPerBlock); + const dim3 grid(c.patternBlocks, c.chunks, batch.count); + partials_product_max_kernel<<>>(batch, nRows, nPatterns, c.rowsPerChunk, scratch); + partials_product_scale_kernel<<>>(batch, nRows, nPatterns, c.rowsPerChunk, scratch, scalersLog); + if (cumulative) + accumulate_scaling_kernel<<<(nPatterns + 255) / 256, 256, 0, stream>>>(batch, nPatterns, cumulative, scalersLog); +} + +void cuda_partials_products(const PartialsProductBatch& batch, int nRows, int nPatterns, float* cumulative, bool scalersLog, + float* scratch, cudaStream_t stream) +{ + cuda_partials_products_impl(batch, nRows, nPatterns, cumulative, scalersLog, scratch, stream); +} + +void cuda_partials_products(const PartialsProductBatch& batch, int nRows, int nPatterns, double* cumulative, bool scalersLog, + double* scratch, cudaStream_t stream) +{ + cuda_partials_products_impl(batch, nRows, nPatterns, cumulative, scalersLog, scratch, stream); +} + +template +__global__ void accumulate_scale_factors_kernel(const ScaleFactorBatch batch, int nPatterns, T* cumulative, bool scalersLog, bool subtract) +{ + const int p = blockIdx.x * blockDim.x + threadIdx.x; + if (p >= nPatterns) return; + T total = 0; + for (int k = 0; k < batch.count; k++) + { + const T factor = batch.factors[k][p]; + if (scalersLog) + total += factor; + else if (factor != 1) + total += log(factor); + } + cumulative[p] += subtract ? -total : total; +} + +template +void cuda_accumulate_scale_factors_impl(const ScaleFactorBatch& batch, int nPatterns, T* cumulative, bool scalersLog, + bool subtract, cudaStream_t stream) +{ + if (batch.count == 0) return; + accumulate_scale_factors_kernel<<<(nPatterns + 255) / 256, 256, 0, stream>>>(batch, nPatterns, cumulative, scalersLog, subtract); +} + +void cuda_accumulate_scale_factors(const ScaleFactorBatch& batch, int nPatterns, float* cumulative, bool scalersLog, + bool subtract, cudaStream_t stream) +{ + cuda_accumulate_scale_factors_impl(batch, nPatterns, cumulative, scalersLog, subtract, stream); +} + +void cuda_accumulate_scale_factors(const ScaleFactorBatch& batch, int nPatterns, double* cumulative, bool scalersLog, + bool subtract, cudaStream_t stream) +{ + cuda_accumulate_scale_factors_impl(batch, nPatterns, cumulative, scalersLog, subtract, stream); +} + +// out(c, s, p) = frequencies[s] for p < nPatterns, 0 for the padded patterns. +template +__global__ void root_pre_partials_kernel(T* out, const T* frequencies, int nStates, int nRows, int nPaddedPatterns, int nPatterns) +{ + const size_t n = (size_t)nRows * nPaddedPatterns; + for (size_t i = blockIdx.x * (size_t)blockDim.x + threadIdx.x; i < n; i += (size_t)gridDim.x * blockDim.x) + { + const int r = i / nPaddedPatterns; + const int p = i % nPaddedPatterns; + out[i] = (p < nPatterns) ? frequencies[r % nStates] : T(0); + } +} + +template +void cuda_root_pre_partials_impl(T* out, const T* frequencies, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + cudaStream_t stream) +{ + const size_t n = (size_t)nStates * nCategories * nPaddedPatterns; + const int blocks = (int)std::min((n + 255) / 256, 4096); + root_pre_partials_kernel<<>>(out, frequencies, nStates, nStates * nCategories, nPaddedPatterns, nPatterns); +} + +void cuda_root_pre_partials(float* out, const float* frequencies, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + cudaStream_t stream) +{ + cuda_root_pre_partials_impl(out, frequencies, nStates, nCategories, nPaddedPatterns, nPatterns, stream); +} + +void cuda_root_pre_partials(double* out, const double* frequencies, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + cudaStream_t stream) +{ + cuda_root_pre_partials_impl(out, frequencies, nStates, nCategories, nPaddedPatterns, nPatterns, stream); +} + +// For node z = blockIdx.z, over the chunk's rows r = (c, s): +// chunkNumerator[z, chunk, p] = sum w_c m_c pre(r, p) (D post)(r, p), D = A + shift I in CSR (if rowOffsets) +// chunkDenominator[z, chunk, p] = sum w_c pre(r, p) post(r, p) +// D acts within each category's (nStates, nPatterns) block. +template +__global__ void edge_derivative_sums_kernel(const EdgeDerivativeBatch batch, int nStates, int nRows, int nPatterns, int rowsPerChunk, + const int* __restrict__ rowOffsets, const int* __restrict__ columns, + const T* __restrict__ values, T shift, const T* __restrict__ categoryWeights, + T* chunkNumerator, T* chunkDenominator) +{ + const T* post = batch.post[blockIdx.z]; + const T* pre = batch.pre[blockIdx.z]; + const int p = blockIdx.x * blockDim.x + threadIdx.x; + const int rowEnd = min(nRows, (blockIdx.y + 1) * rowsPerChunk); + T numerator = 0; + T denominator = 0; + if (p < nPatterns) + for (int r = blockIdx.y * rowsPerChunk + threadIdx.y; r < rowEnd; r += blockDim.y) + { + const int c = r / nStates; + const int s = r % nStates; + const size_t i = (size_t)r * nPatterns + p; + const T w = categoryWeights[c]; + const T own = post[i]; + denominator += w * pre[i] * own; + if (rowOffsets) + { + const T* block = post + (size_t)c * nStates * nPatterns + p; + T sum = shift * own; + for (int k = rowOffsets[s]; k < rowOffsets[s + 1]; k++) + sum += values[k] * block[(size_t)columns[k] * nPatterns]; + numerator += w * batch.categoryMultipliers[c] * pre[i] * sum; + } + } + numerator = column_reduce(numerator, SumOp()); + __syncthreads(); + denominator = column_reduce(denominator, SumOp()); + if (threadIdx.y == 0 and p < nPatterns) + { + const size_t o = ((size_t)blockIdx.z * gridDim.y + blockIdx.y) * nPatterns + p; + chunkNumerator[o] = numerator; + chunkDenominator[o] = denominator; + } +} + +// For node z = blockIdx.x: derivatives[z, p] = numerator / denominator (each summed over the chunks), and +// sums[z] = sum_p patternWeights[p] * derivative, sumSquares[z] = sum_p patternWeights[p] * derivative^2. +// With numerators == nullptr, derivatives[z, p] = patternWeights[p] / denominator instead (no sums). +template +__global__ void edge_derivative_finish_kernel(const T* chunkNumerator, const T* chunkDenominator, int nChunks, int nPaddedPatterns, + int nPatterns, const T* patternWeights, T* derivatives, T* sums, T* sumSquares) +{ + const size_t base = (size_t)blockIdx.x * nChunks * nPaddedPatterns; + T sum = 0; + T sumSquare = 0; + for (int p = threadIdx.x; p < nPatterns; p += blockDim.x) + { + T numerator = 0; + T denominator = 0; + for (int c = 0; c < nChunks; c++) + { + denominator += chunkDenominator[base + (size_t)c * nPaddedPatterns + p]; + if (chunkNumerator) + numerator += chunkNumerator[base + (size_t)c * nPaddedPatterns + p]; + } + if (not chunkNumerator) + { + derivatives[(size_t)blockIdx.x * nPatterns + p] = patternWeights[p] / denominator; + continue; + } + const T derivative = numerator / denominator; + derivatives[(size_t)blockIdx.x * nPatterns + p] = derivative; + sum += derivative * patternWeights[p]; + sumSquare += derivative * derivative * patternWeights[p]; + } + if (not chunkNumerator) return; + sum = block_reduce(sum, T(0), SumOp()); + __syncthreads(); + sumSquare = block_reduce(sumSquare, T(0), SumOp()); + if (threadIdx.x == 0) + { + sums[blockIdx.x] = sum; + sumSquares[blockIdx.x] = sumSquare; + } +} + +template +void cuda_edge_derivatives_impl(const EdgeDerivativeBatch& batch, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + const int* rowOffsets, const int* columns, const T* values, T shift, const T* categoryWeights, + const T* patternWeights, T* scratch, T* derivatives, T* sums, T* sumSquares, cudaStream_t stream) +{ + if (batch.count == 0) return; + const int nRows = nStates * nCategories; + const RowChunks c = rowChunks(nRows, nPaddedPatterns); + const dim3 block(c.patternsPerBlock, c.rowsPerBlock); + const dim3 grid(c.patternBlocks, c.chunks, batch.count); + T* chunkNumerator = rowOffsets ? scratch : nullptr; + T* chunkDenominator = scratch + (size_t)batch.count * c.chunks * nPaddedPatterns; + edge_derivative_sums_kernel<<>>(batch, nStates, nRows, nPaddedPatterns, c.rowsPerChunk, + rowOffsets, columns, values, shift, categoryWeights, + scratch, chunkDenominator); + edge_derivative_finish_kernel<<>>(chunkNumerator, chunkDenominator, c.chunks, nPaddedPatterns, nPatterns, + patternWeights, derivatives, sums, sumSquares); +} + +size_t cuda_edge_derivative_scratch_size(int nStates, int nCategories, int nPaddedPatterns) +{ + return (size_t)2 * kMaxEdgeDerivativeNodes * rowChunks(nStates * nCategories, nPaddedPatterns).chunks * nPaddedPatterns; +} + +void cuda_edge_derivatives(const EdgeDerivativeBatch& batch, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + const int* rowOffsets, const int* columns, const float* values, float shift, const float* categoryWeights, + const float* patternWeights, float* scratch, float* derivatives, float* sums, float* sumSquares, cudaStream_t stream) +{ + cuda_edge_derivatives_impl(batch, nStates, nCategories, nPaddedPatterns, nPatterns, rowOffsets, columns, values, shift, categoryWeights, + patternWeights, scratch, derivatives, sums, sumSquares, stream); +} + +void cuda_edge_derivatives(const EdgeDerivativeBatch& batch, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + const int* rowOffsets, const int* columns, const double* values, double shift, const double* categoryWeights, + const double* patternWeights, double* scratch, double* derivatives, double* sums, double* sumSquares, cudaStream_t stream) +{ + cuda_edge_derivatives_impl(batch, nStates, nCategories, nPaddedPatterns, nPatterns, rowOffsets, columns, values, shift, categoryWeights, + patternWeights, scratch, derivatives, sums, sumSquares, stream); +} + +// crossProducts[k] += sum_{c,p} multipliers[c] * patternScale[p] * pre(c, i, p) * post(c, j, p) for each non-zero k = (i, j) +// of the CSR pattern. One warp per row i; the lanes cover (category, pattern) pairs. +template +__global__ void cross_products_kernel(const T* pre, const T* post, int nStates, int nCategories, int nPatterns, + const int* __restrict__ rowOffsets, const int* __restrict__ columns, + const CategoryMultipliers multipliers, const T* __restrict__ patternScale, T* crossProducts) +{ + const int lane = threadIdx.x % 32; + const int i = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32; + if (i >= nStates) return; + const size_t categoryStride = (size_t)nStates * nPatterns; + const int n = nCategories * nPatterns; + for (int k = rowOffsets[i]; k < rowOffsets[i + 1]; k++) + { + const int j = columns[k]; + T sum = 0; + for (int q = lane; q < n; q += 32) + { + const int c = q / nPatterns; + const int p = q % nPatterns; + sum += multipliers.values[c] * patternScale[p] * pre[c * categoryStride + (size_t)i * nPatterns + p] * + post[c * categoryStride + (size_t)j * nPatterns + p]; + } + for (int offset = 16; offset > 0; offset /= 2) + sum += __shfl_down_sync(0xffffffff, sum, offset); + if (lane == 0) + crossProducts[k] += sum; + } +} + +template +void cuda_cross_products_impl(const T* pre, const T* post, int nStates, int nCategories, int nPatterns, const int* rowOffsets, + const int* columns, const CategoryMultipliers& multipliers, const T* patternScale, T* crossProducts, + cudaStream_t stream) +{ + cross_products_kernel<<<(nStates + 7) / 8, 256, 0, stream>>>(pre, post, nStates, nCategories, nPatterns, rowOffsets, columns, + multipliers, patternScale, crossProducts); +} + +void cuda_cross_products(const float* pre, const float* post, int nStates, int nCategories, int nPatterns, const int* rowOffsets, + const int* columns, const CategoryMultipliers& multipliers, const float* patternScale, float* crossProducts, + cudaStream_t stream) +{ + cuda_cross_products_impl(pre, post, nStates, nCategories, nPatterns, rowOffsets, columns, multipliers, patternScale, crossProducts, stream); +} + +void cuda_cross_products(const double* pre, const double* post, int nStates, int nCategories, int nPatterns, const int* rowOffsets, + const int* columns, const CategoryMultipliers& multipliers, const double* patternScale, double* crossProducts, + cudaStream_t stream) +{ + cuda_cross_products_impl(pre, post, nStates, nCategories, nPatterns, rowOffsets, columns, multipliers, patternScale, crossProducts, stream); +} + +// chunkSum[chunk, p] = sum over the chunk's rows r = (c, s) of root[r, p] * categoryWeights[c] * frequencies[s] +template +__global__ void root_chunk_sums_kernel(const T* root, const T* categoryWeights, const T* frequencies, int nStates, int nRows, + int nPatterns, int rowsPerChunk, T* chunkSum) +{ + const int p = blockIdx.x * blockDim.x + threadIdx.x; + const int rowEnd = min(nRows, (blockIdx.y + 1) * rowsPerChunk); + T sum = 0; + if (p < nPatterns) + for (int r = blockIdx.y * rowsPerChunk + threadIdx.y; r < rowEnd; r += blockDim.y) + sum += root[(size_t)r * nPatterns + p] * categoryWeights[r / nStates] * frequencies[r % nStates]; + sum = column_reduce(sum, SumOp()); + if (threadIdx.y == 0 and p < nPatterns) + chunkSum[blockIdx.y * nPatterns + p] = sum; +} + +// siteLogLikelihoods[p] = log(sum of the chunk sums) + cumulativeScaling[p]; out[0] = sum_p patternWeights[p] * siteLogLikelihoods[p]. +// A single block, so the sum is deterministic. +template +__global__ void root_finish_kernel(const T* chunkSum, int nChunks, int nPaddedPatterns, int nPatterns, const T* cumulativeScaling, + const T* patternWeights, T* siteLogLikelihoods, T* out) +{ + T total = 0; + for (int p = threadIdx.x; p < nPatterns; p += blockDim.x) + { + T sum = 0; + for (int c = 0; c < nChunks; c++) + sum += chunkSum[c * nPaddedPatterns + p]; + const T site = log(sum) + (cumulativeScaling ? cumulativeScaling[p] : T(0)); + siteLogLikelihoods[p] = site; + total += site * patternWeights[p]; + } + total = block_reduce(total, T(0), SumOp()); + if (threadIdx.x == 0) out[0] = total; +} + +template +void cuda_root_log_likelihoods_impl(const T* root, const T* categoryWeights, const T* frequencies, const T* cumulativeScaling, + const T* patternWeights, int nStates, int nPaddedPatterns, int nPatterns, int nCategories, + T* scratch, T* siteLogLikelihoods, T* sumLogLikelihood, cudaStream_t stream) +{ + const int nRows = nStates * nCategories; + const RowChunks c = rowChunks(nRows, nPaddedPatterns); + const dim3 block(c.patternsPerBlock, c.rowsPerBlock); + const dim3 grid(c.patternBlocks, c.chunks); + root_chunk_sums_kernel<<>>(root, categoryWeights, frequencies, nStates, nRows, nPaddedPatterns, + c.rowsPerChunk, scratch); + root_finish_kernel<<<1, 1024, 0, stream>>>(scratch, c.chunks, nPaddedPatterns, nPatterns, cumulativeScaling, patternWeights, + siteLogLikelihoods, sumLogLikelihood); +} + +void cuda_root_log_likelihoods(const float* root, const float* categoryWeights, const float* frequencies, const float* cumulativeScaling, + const float* patternWeights, int nStates, int nPaddedPatterns, int nPatterns, int nCategories, + float* scratch, float* siteLogLikelihoods, float* sumLogLikelihood, cudaStream_t stream) +{ + cuda_root_log_likelihoods_impl(root, categoryWeights, frequencies, cumulativeScaling, patternWeights, + nStates, nPaddedPatterns, nPatterns, nCategories, scratch, siteLogLikelihoods, sumLogLikelihood, stream); +} + +void cuda_root_log_likelihoods(const double* root, const double* categoryWeights, const double* frequencies, const double* cumulativeScaling, + const double* patternWeights, int nStates, int nPaddedPatterns, int nPatterns, int nCategories, + double* scratch, double* siteLogLikelihoods, double* sumLogLikelihood, cudaStream_t stream) +{ + cuda_root_log_likelihoods_impl(root, categoryWeights, frequencies, cumulativeScaling, patternWeights, + nStates, nPaddedPatterns, nPatterns, nCategories, scratch, siteLogLikelihoods, sumLogLikelihood, stream); +} + + +// --------------------------------------------------------------------------------------------------- +// Block 1-norm estimation of ||B^p||_1 for all p at once (Higham & Tisseur Algorithm 2.4, 2 iterations). +// All matrices are row-major with n rows and an explicit row stride. See BlockNormEstimator in +// BeagleGPUActionImpl.h. + +// y(:, 0:nApplied) = A * x(:, 0:nApplied), then nAppend more columns of y are set: +// from signSource (n, nAppend): y(i, c) = +1 if signSource(i, c) >= 0, else -1 +// from unitRows (nAppend): y(i, c) = 1 if i == unitRows[c], else 0 +// LANES lanes share a row and cover its columns, so the gathers of x are coalesced. +template +__global__ void norm_chain_step_kernel(int n, const int* __restrict__ rowOffsets, const int* __restrict__ columns, + const T* __restrict__ values, const T* __restrict__ x, int ldx, T* __restrict__ y, int ldy, + int nApplied, int nAppend, const T* __restrict__ signSource, int ldSign, + const int* __restrict__ unitRows) +{ + const int lane = threadIdx.x % 32; + const int row = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * (32 / LANES) + lane / LANES; + if (row >= n) return; + T* yRow = y + (size_t)row * ldy; + + const int kBegin = rowOffsets[row]; + const int kEnd = rowOffsets[row + 1]; + for (int c = lane % LANES; c < nApplied; c += LANES) + { + T sum = 0; + for (int k = kBegin; k < kEnd; k++) + sum += values[k] * x[(size_t)columns[k] * ldx + c]; + yRow[c] = sum; + } + for (int c = lane % LANES; c < nAppend; c += LANES) + { + if (signSource) + yRow[nApplied + c] = (signSource[(size_t)row * ldSign + c] >= 0) ? T(1) : T(-1); + else + yRow[nApplied + c] = (row == unitRows[c]) ? T(1) : T(0); + } +} + +template +void launch_norm_chain_step(int n, const int* rowOffsets, const int* columns, const T* values, const T* x, int ldx, T* y, int ldy, + int nApplied, int nAppend, const T* signSource, int ldSign, const int* unitRows, cudaStream_t stream) +{ + const int threads = 256; + const int rowsPerBlock = (threads / 32) * (32 / LANES); + norm_chain_step_kernel<<<(n + rowsPerBlock - 1) / rowsPerBlock, threads, 0, stream>>>( + n, rowOffsets, columns, values, x, ldx, y, ldy, nApplied, nAppend, signSource, ldSign, unitRows); +} + +template +void cuda_norm_chain_step_impl(int n, const int* rowOffsets, const int* columns, const T* values, const T* x, int ldx, T* y, int ldy, + int nApplied, int nAppend, const T* signSource, int ldSign, const int* unitRows, cudaStream_t stream) +{ + switch (nextPowerOfTwo(std::max(nApplied, nAppend), 32)) + { + case 1: + case 2: + case 4: launch_norm_chain_step(n, rowOffsets, columns, values, x, ldx, y, ldy, nApplied, nAppend, signSource, ldSign, unitRows, stream); break; + case 8: launch_norm_chain_step(n, rowOffsets, columns, values, x, ldx, y, ldy, nApplied, nAppend, signSource, ldSign, unitRows, stream); break; + case 16: launch_norm_chain_step(n, rowOffsets, columns, values, x, ldx, y, ldy, nApplied, nAppend, signSource, ldSign, unitRows, stream); break; + default: launch_norm_chain_step(n, rowOffsets, columns, values, x, ldx, y, ldy, nApplied, nAppend, signSource, ldSign, unitRows, stream); break; + } +} + +void cuda_norm_chain_step(int n, const int* rowOffsets, const int* columns, const float* values, const float* x, int ldx, float* y, int ldy, + int nApplied, int nAppend, const float* signSource, int ldSign, const int* unitRows, cudaStream_t stream) +{ + cuda_norm_chain_step_impl(n, rowOffsets, columns, values, x, ldx, y, ldy, nApplied, nAppend, signSource, ldSign, unitRows, stream); +} + +void cuda_norm_chain_step(int n, const int* rowOffsets, const int* columns, const double* values, const double* x, int ldx, double* y, int ldy, + int nApplied, int nAppend, const double* signSource, int ldSign, const int* unitRows, cudaStream_t stream) +{ + cuda_norm_chain_step_impl(n, rowOffsets, columns, values, x, ldx, y, ldy, nApplied, nAppend, signSource, ldSign, unitRows, stream); +} + +// sums[c] = sum_i |x(i, c)|, one block per column. +template +__global__ void column_abs_sums_kernel(const T* x, int n, int ld, T* sums) +{ + const int c = blockIdx.x; + T sum = 0; + for (int i = threadIdx.x; i < n; i += blockDim.x) + sum += abs(x[(size_t)i * ld + c]); + sum = block_reduce(sum, T(0), SumOp()); + if (threadIdx.x == 0) sums[c] = sum; +} + +template +void cuda_column_abs_sums_impl(const T* x, int n, int nColumns, int ld, T* sums, cudaStream_t stream) +{ + column_abs_sums_kernel<<>>(x, n, ld, sums); +} + +void cuda_column_abs_sums(const float* x, int n, int nColumns, int ld, float* sums, cudaStream_t stream) +{ + cuda_column_abs_sums_impl(x, n, nColumns, ld, sums, stream); +} + +void cuda_column_abs_sums(const double* x, int n, int nColumns, int ld, double* sums, cudaStream_t stream) +{ + cuda_column_abs_sums_impl(x, n, nColumns, ld, sums, stream); +} + +// dst[i] = src[index[i]] +template +__global__ void gather_kernel(const T* src, const int* index, int n, T* dst) +{ + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) dst[i] = src[index[i]]; +} + +template +void cuda_gather_impl(const T* src, const int* index, int n, T* dst, cudaStream_t stream) +{ + if (n > 0) + gather_kernel<<<(n + 255) / 256, 256, 0, stream>>>(src, index, n, dst); +} + +void cuda_gather(const float* src, const int* index, int n, float* dst, cudaStream_t stream) +{ + cuda_gather_impl(src, index, n, dst, stream); +} + +void cuda_gather(const double* src, const int* index, int n, double* dst, cudaStream_t stream) +{ + cuda_gather_impl(src, index, n, dst, stream); +} + +// rowMax[b * n + i] = max_j |Z(i, b*t + j)| for each block b of t columns of Z (row stride ld). +template +__global__ void block_row_max_kernel(const T* Z, int n, int t, int nBlocks, int ld, T* rowMax) +{ + const int index = blockIdx.x * blockDim.x + threadIdx.x; + if (index >= n * nBlocks) return; + const int b = index / n; + const int i = index % n; + const T* z = Z + (size_t)i * ld + b * t; + T h = 0; + for (int j = 0; j < t; j++) + h = max(h, abs(z[j])); + rowMax[index] = h; +} + +// unitRows[b*t + r] = the row with the r-th largest rowMax[b * n + i] (ties go to the lower row). +// One thread block per column block. +template +__global__ void select_unit_columns_kernel(const T* rowMax, int n, int t, int* unitRows) +{ + __shared__ T bestValue[1024]; + __shared__ int bestRow[1024]; + __shared__ int chosen[32]; + + const T* h = rowMax + (size_t)blockIdx.x * n; + + for (int r = 0; r < t; r++) + { + T value = -1; + int row = n; + for (int i = threadIdx.x; i < n; i += blockDim.x) + { + bool used = false; + for (int q = 0; q < r; q++) + used = used or (chosen[q] == i); + if (used) continue; + + if (h[i] > value) { value = h[i]; row = i; } + } + bestValue[threadIdx.x] = value; + bestRow[threadIdx.x] = row; + __syncthreads(); + + for (int stride = blockDim.x / 2; stride > 0; stride /= 2) + { + if (threadIdx.x < stride) + { + const int other = threadIdx.x + stride; + if (bestValue[other] > bestValue[threadIdx.x] or + (bestValue[other] == bestValue[threadIdx.x] and bestRow[other] < bestRow[threadIdx.x])) + { + bestValue[threadIdx.x] = bestValue[other]; + bestRow[threadIdx.x] = bestRow[other]; + } + } + __syncthreads(); + } + + if (threadIdx.x == 0) + { + chosen[r] = bestRow[0]; + unitRows[blockIdx.x * t + r] = bestRow[0]; + } + __syncthreads(); + } +} + +template +void cuda_select_unit_columns_impl(const T* Z, int n, int t, int nBlocks, int ld, T* rowMax, int* unitRows, cudaStream_t stream) +{ + block_row_max_kernel<<<(n * nBlocks + 255) / 256, 256, 0, stream>>>(Z, n, t, nBlocks, ld, rowMax); + select_unit_columns_kernel<<>>(rowMax, n, t, unitRows); +} + +void cuda_select_unit_columns(const float* Z, int n, int t, int nBlocks, int ld, float* rowMax, int* unitRows, cudaStream_t stream) +{ + cuda_select_unit_columns_impl(Z, n, t, nBlocks, ld, rowMax, unitRows, stream); +} + +void cuda_select_unit_columns(const double* Z, int n, int t, int nBlocks, int ld, double* rowMax, int* unitRows, cudaStream_t stream) +{ + cuda_select_unit_columns_impl(Z, n, t, nBlocks, ld, rowMax, unitRows, stream); +} + +// norms[p] = max over the t columns for p in both iterations, for p = 2 .. pTop: +// iteration 1: block p-1 of sums1; iteration 2: block pTop-p of sums2. +template +__global__ void combine_norm_estimates_kernel(const T* sums1, const T* sums2, int t, int pTop, T* norms) +{ + const int p = threadIdx.x + 2; + if (p > pTop) return; + T norm = 0; + for (int j = 0; j < t; j++) + norm = max(norm, max(sums1[(p - 1) * t + j], sums2[(pTop - p) * t + j])); + norms[p] = norm; +} + +template +void cuda_combine_norm_estimates_impl(const T* sums1, const T* sums2, int t, int pTop, T* norms, cudaStream_t stream) +{ + combine_norm_estimates_kernel<<<1, 32, 0, stream>>>(sums1, sums2, t, pTop, norms); +} + +void cuda_combine_norm_estimates(const float* sums1, const float* sums2, int t, int pTop, float* norms, cudaStream_t stream) +{ + cuda_combine_norm_estimates_impl(sums1, sums2, t, pTop, norms, stream); +} + +void cuda_combine_norm_estimates(const double* sums1, const double* sums2, int t, int pTop, double* norms, cudaStream_t stream) +{ + cuda_combine_norm_estimates_impl(sums1, sums2, t, pTop, norms, stream); +} diff --git a/libhmsbeagle/GPU/cuda_ops.h b/libhmsbeagle/GPU/cuda_ops.h new file mode 100644 index 000000000..b1d3d2d58 --- /dev/null +++ b/libhmsbeagle/GPU/cuda_ops.h @@ -0,0 +1,248 @@ +#ifndef CUDA_OPS_H +#define CUDA_OPS_H + +#include +#include // cudaMalloc, cudaMemcpy, etc. +#include // for std::runtime_error + + +inline void* cudaMallocWrapped(size_t n) +{ + void* result; + auto status = cudaMalloc((void**)&result, n); + if (status != cudaSuccess) + throw std::runtime_error(std::string("cudaMalloc: ") + std::string(cudaGetErrorString(status))); + return result; +} + +template +T* cudaDeviceNew(size_t n) +{ + return (T*)cudaMallocWrapped(n*sizeof(T)); +} + +template +void cudaDeviceDelete(T* buffer) +{ + if (buffer) + { + auto status = cudaFree(buffer); + if (status != cudaSuccess) + throw std::runtime_error(std::string("cudaFree: ") + std::string(cudaGetErrorString(status))); + } +} + +template +void MemcpyHostToDevice(T* dptr, const T* hptr, int n) +{ + auto status = cudaMemcpy(dptr, hptr, n*sizeof(T), cudaMemcpyHostToDevice); + if (status != cudaSuccess) + throw std::runtime_error("cudaMemcpy(Host->Device): " + std::string(cudaGetErrorString(status))); +} + +template +void MemcpyDeviceToDevice(T* dptr, const T* hptr, int n) +{ + auto status = cudaMemcpy(dptr, hptr, n*sizeof(T), cudaMemcpyDeviceToDevice); + if (status != cudaSuccess) + throw std::runtime_error("cudaMemcpy(Device->Device): " + std::string(cudaGetErrorString(status))); +} + +template +void MemcpyDeviceToDeviceAsync(T* dptr, const T* hptr, int n) +{ + auto status = cudaMemcpyAsync(dptr, hptr, n*sizeof(T), cudaMemcpyDeviceToDevice); + if (status != cudaSuccess) + throw std::runtime_error("cudaMemcpyAsync(Device->Device): " + std::string(cudaGetErrorString(status))); +} + + +template +void MemcpyDeviceToHost(T* hptr, const T* dptr, int n) +{ + auto status = cudaMemcpy(hptr, dptr, n*sizeof(T), cudaMemcpyDeviceToHost); + if (status != cudaSuccess) + throw std::runtime_error(std::string("cudaMemcpy(Device->Host): ") + std::string(cudaGetErrorString(status))); +} + +template +std::vector MemcpyDeviceToHostVector(const T* dptr, int n) +{ + std::vector host_vec(n); + auto status = cudaMemcpy(host_vec.data(), dptr, n*sizeof(T), cudaMemcpyDeviceToHost); + if (status != cudaSuccess) + throw std::runtime_error("cudaMemcpy(Device->Host): failed!"); + return host_vec; +} + +// max_i |v[i]| (synchronizes with the host). +double cuda_max_abs(double* v, int length); +float cuda_max_abs(float* v, int length); + +// The starting matrix X (n, t), row-major, of the block 1-norm estimator: first column 1/n, others random +-1/n. +void initialize_norm_x_matrix(float* data, int n, int m); +void initialize_norm_x_matrix(double* data, int n, int m); + +// Block 1-norm estimation, see BlockNormEstimator in BeagleGPUActionImpl.h. Matrices are row-major with n rows +// and row stride ld*. +// y(:, 0:nApplied) = A x(:, 0:nApplied) with A in CSR; then nAppend more columns of y are set to sign(signSource) +// if signSource is non-null, otherwise to unit vectors e(unitRows[c]). +void cuda_norm_chain_step(int n, const int* rowOffsets, const int* columns, const float* values, const float* x, int ldx, float* y, int ldy, + int nApplied, int nAppend, const float* signSource, int ldSign, const int* unitRows, cudaStream_t stream); +void cuda_norm_chain_step(int n, const int* rowOffsets, const int* columns, const double* values, const double* x, int ldx, double* y, int ldy, + int nApplied, int nAppend, const double* signSource, int ldSign, const int* unitRows, cudaStream_t stream); + +// sums[c] = sum_i |x(i, c)| for the first nColumns columns of x (n rows, row stride ld). +void cuda_column_abs_sums(const float* x, int n, int nColumns, int ld, float* sums, cudaStream_t stream); +void cuda_column_abs_sums(const double* x, int n, int nColumns, int ld, double* sums, cudaStream_t stream); + +// For each of nBlocks blocks of t columns of Z (n rows, row stride ld): the t rows with the largest +// max_j |Z(i,j)| -> unitRows[b*t ...]. rowMax is scratch for n * nBlocks values. +void cuda_select_unit_columns(const float* Z, int n, int t, int nBlocks, int ld, float* rowMax, int* unitRows, cudaStream_t stream); +void cuda_select_unit_columns(const double* Z, int n, int t, int nBlocks, int ld, double* rowMax, int* unitRows, cudaStream_t stream); + +// dst[i] = src[index[i]] for i < n. +void cuda_gather(const float* src, const int* index, int n, float* dst, cudaStream_t stream); +void cuda_gather(const double* src, const int* index, int n, double* dst, cudaStream_t stream); + +// norms[p] for p = 2..pTop: the largest column sum for p in either iteration (see the kernel). +void cuda_combine_norm_estimates(const float* sums1, const float* sums2, int t, int pTop, float* norms, cudaStream_t stream); +void cuda_combine_norm_estimates(const double* sums1, const double* sums2, int t, int pTop, double* norms, cudaStream_t stream); + +// Action partials are stored pattern-fastest, [category][state][pattern]: a (nRows, nPatterns) row-major +// matrix with nRows = nCategories * nStates. + +// One Horner step of a Taylor polynomial for several independent (nRows, nCols) row-major matrices that share A: +// out = scale * (b + alpha * A * x) +// Each matrix has its own row stride (ld*, in elements), so the groups' matrices can be stored side by side in +// one wider matrix. out must not alias x or b. +template +struct TaylorTermGroup +{ + const T* x; + const T* b; + T* out; + T alpha; + T scale; + int ldx; + int ldb; + int ldOut; +}; + +// 64 groups keep the kernel parameters under 4 KB. +constexpr int kMaxTaylorGroups = 64; + +template +struct TaylorTermBatch +{ + int count = 0; + TaylorTermGroup groups[kMaxTaylorGroups]; +}; + +void cuda_taylor_horner_terms(int nRows, int nCols, const int* rowOffsets, const int* columns, const float* values, + const TaylorTermBatch& batch, cudaStream_t stream); +void cuda_taylor_horner_terms(int nRows, int nCols, const int* rowOffsets, const int* columns, const double* values, + const TaylorTermBatch& batch, cudaStream_t stream); + +// The product and root kernels need a scratch buffer of cuda_row_chunk_count(nRows, nPatterns) * nPatterns values +// (per product, for the products). +int cuda_row_chunk_count(int nRows, int nPatterns); + +// parent = left * right for (nRows, nPatterns) partials (right == nullptr means 1). If scalingFactors is non-null, +// also rescale each pattern by its largest entry m and write m (log m if scalersLog) to scalingFactors[pattern]. +// Otherwise, if fixedScalingFactors is non-null, divide each pattern by its existing factor (exp of it if scalersLog). +template +struct PartialsProduct +{ + const T* left; + const T* right; + T* parent; + T* scalingFactors; + const T* fixedScalingFactors = nullptr; +}; + +constexpr int kMaxPartialsProducts = 16; + +template +struct PartialsProductBatch +{ + int count = 0; + PartialsProduct products[kMaxPartialsProducts]; +}; + +// All the products of the batch, then (if cumulative is non-null) cumulative[pattern] += log m of each in turn. +void cuda_partials_products(const PartialsProductBatch& batch, int nRows, int nPatterns, float* cumulative, bool scalersLog, + float* scratch, cudaStream_t stream); +void cuda_partials_products(const PartialsProductBatch& batch, int nRows, int nPatterns, double* cumulative, bool scalersLog, + double* scratch, cudaStream_t stream); + +// cumulative[p] += (or -= if subtract) the sum over the buffers of factors[p] (log factors[p] unless scalersLog). +template +struct ScaleFactorBatch +{ + int count = 0; + const T* factors[64]; +}; + +void cuda_accumulate_scale_factors(const ScaleFactorBatch& batch, int nPatterns, float* cumulative, bool scalersLog, + bool subtract, cudaStream_t stream); +void cuda_accumulate_scale_factors(const ScaleFactorBatch& batch, int nPatterns, double* cumulative, bool scalersLog, + bool subtract, cudaStream_t stream); + +// out(c, s, p) = frequencies[s] for p < nPatterns, 0 for the padded patterns: root pre-order partials. +void cuda_root_pre_partials(float* out, const float* frequencies, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + cudaStream_t stream); +void cuda_root_pre_partials(double* out, const double* frequencies, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + cudaStream_t stream); + +constexpr int kMaxEdgeDerivativeNodes = 64; +constexpr int kMaxDerivativeCategories = 64; + +// Up to kMaxEdgeDerivativeNodes (post-order, pre-order) pairs, with per-category multipliers m_c (the rates). +template +struct EdgeDerivativeBatch +{ + int count = 0; + const T* post[kMaxEdgeDerivativeNodes]; + const T* pre[kMaxEdgeDerivativeNodes]; + T categoryMultipliers[kMaxDerivativeCategories]; +}; + +// For each node z of the batch and pattern p < nPatterns (partials are (nCategories * nStates, nPaddedPatterns)): +// derivatives[z * nPatterns + p] = (sum_c w_c m_c pre^T D post) / (sum_c w_c pre^T post), D = A + shift I, +// sums[z] = sum_p patternWeights[p] * derivative, sumSquares[z] = sum_p patternWeights[p] * derivative^2, +// with A in CSR (nStates, nStates). With rowOffsets == nullptr only the denominators are formed, and +// derivatives[z * nPatterns + p] = patternWeights[p] / denominator (sums are not set). +// scratch holds cuda_edge_derivative_scratch_size( ) values; all outputs are on the device. +size_t cuda_edge_derivative_scratch_size(int nStates, int nCategories, int nPaddedPatterns); +void cuda_edge_derivatives(const EdgeDerivativeBatch& batch, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + const int* rowOffsets, const int* columns, const float* values, float shift, const float* categoryWeights, + const float* patternWeights, float* scratch, float* derivatives, float* sums, float* sumSquares, cudaStream_t stream); +void cuda_edge_derivatives(const EdgeDerivativeBatch& batch, int nStates, int nCategories, int nPaddedPatterns, int nPatterns, + const int* rowOffsets, const int* columns, const double* values, double shift, const double* categoryWeights, + const double* patternWeights, double* scratch, double* derivatives, double* sums, double* sumSquares, cudaStream_t stream); + +template +struct CategoryMultipliers +{ + T values[kMaxDerivativeCategories]; +}; + +// crossProducts[k] += sum_{c,p} multipliers[c] * patternScale[p] * pre(c, i, p) * post(c, j, p) for each non-zero k = (i, j) +// of the CSR pattern (rowOffsets, columns) of an (nStates, nStates) matrix. pre and post are (nCategories * nStates, nPatterns). +void cuda_cross_products(const float* pre, const float* post, int nStates, int nCategories, int nPatterns, const int* rowOffsets, + const int* columns, const CategoryMultipliers& multipliers, const float* patternScale, float* crossProducts, + cudaStream_t stream); +void cuda_cross_products(const double* pre, const double* post, int nStates, int nCategories, int nPatterns, const int* rowOffsets, + const int* columns, const CategoryMultipliers& multipliers, const double* patternScale, double* crossProducts, + cudaStream_t stream); + +// siteLogLikelihoods[p] = log(sum_{c,s} root(c,s,p) * categoryWeights[c] * frequencies[s]) + cumulativeScaling[p] (if non-null), +// sumLogLikelihood[0] = sum_p patternWeights[p] * siteLogLikelihoods[p]. +void cuda_root_log_likelihoods(const float* root, const float* categoryWeights, const float* frequencies, const float* cumulativeScaling, + const float* patternWeights, int nStates, int nPaddedPatterns, int nPatterns, int nCategories, + float* scratch, float* siteLogLikelihoods, float* sumLogLikelihood, cudaStream_t stream); +void cuda_root_log_likelihoods(const double* root, const double* categoryWeights, const double* frequencies, const double* cumulativeScaling, + const double* patternWeights, int nStates, int nPaddedPatterns, int nPatterns, int nCategories, + double* scratch, double* siteLogLikelihoods, double* sumLogLikelihood, cudaStream_t stream); +#endif diff --git a/libhmsbeagle/GPU/kernels/kernels4.cu b/libhmsbeagle/GPU/kernels/kernels4.cu index 63be43b73..fbd1803ab 100644 --- a/libhmsbeagle/GPU/kernels/kernels4.cu +++ b/libhmsbeagle/GPU/kernels/kernels4.cu @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres @@ -29,7 +19,7 @@ #include "libhmsbeagle/GPU/GPUImplDefs.h" #include "libhmsbeagle/GPU/kernels/kernelsAll.cu" // This file includes the non-state-count specific kernels extern "C" { -#endif +#endif #define multBy4(x) ((x) << 2) #define multBy16(x) ((x) << 4) @@ -46,14 +36,14 @@ int deltaPartialsByMatrix = matrix * PADDED_STATE_COUNT * endPattern;\ int deltaMatrix = matrix * PADDED_STATE_COUNT * PADDED_STATE_COUNT;\ int deltaPartials = deltaPartialsByMatrix + deltaPartialsByState; - + #define DETERMINE_INDICES_4_MULTI_1_CPU()\ int opIndexPtr = (gridStartOp + KW_GROUP_ID_0) * 8;\ int startPat = ptrOffsets[opIndexPtr ];\ int endPattern = ptrOffsets[opIndexPtr + 1];\ int patIdx = KW_LOCAL_ID_0;\ - int pattern = startPat + patIdx; - + int pattern = startPat + patIdx; + #define DETERMINE_INDICES_4_MULTI_2_CPU()\ int matrix = KW_GROUP_ID_1;\ int deltaPartialsByState = pattern * PADDED_STATE_COUNT;\ @@ -75,15 +65,15 @@ int deltaPartialsByState = pattern * PADDED_STATE_COUNT;\ int deltaPartialsByMatrix = matrix * PADDED_STATE_COUNT * totalPatterns;\ int deltaMatrix = matrix * PADDED_STATE_COUNT * PADDED_STATE_COUNT;\ - int deltaPartials = deltaPartialsByMatrix + deltaPartialsByState; + int deltaPartials = deltaPartialsByMatrix + deltaPartialsByState; #define DETERMINE_INDICES_4_EDGEPART_1_CPU()\ int opIndexPtr = KW_GROUP_ID_0 * 5;\ int startPat = ptrOffsets[opIndexPtr ];\ int endPattern = ptrOffsets[opIndexPtr + 1];\ int patIdx = KW_LOCAL_ID_0;\ - int pattern = startPat + patIdx; - + int pattern = startPat + patIdx; + #define SUM_PARTIALS_PARTIALS_4_CPU()\ REAL sum1[PADDED_STATE_COUNT];\ REAL sum2[PADDED_STATE_COUNT];\ @@ -503,7 +493,7 @@ sMatrix2[tx] = matrix2[tx];\ }\ KW_LOCAL_FENCE; - + #define LOAD_MATRIX_4_MULTI_GPU()\ matrix1 += x2;\ matrix2 += x2;\ @@ -815,7 +805,7 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsNoScaleMulti(KW_GLOBAL_VAR REAL* KW_ DETERMINE_INDICES_4_MULTI_2_CPU(); const KW_GLOBAL_VAR REAL* KW_RESTRICT partials1 = partials + ptrOffsets[opIndexPtr + 2]; const KW_GLOBAL_VAR REAL* KW_RESTRICT partials2 = partials + ptrOffsets[opIndexPtr + 3]; - DETERMINE_INDICES_4_MULTI_3_CPU(); + DETERMINE_INDICES_4_MULTI_3_CPU(); SUM_PARTIALS_PARTIALS_4_CPU(); for(int i = 0; i < PADDED_STATE_COUNT; i++) { partials3[deltaPartials + i] = sum1[i] * sum2[i]; @@ -1243,7 +1233,7 @@ KW_GLOBAL_KERNEL void kernelStatesStatesNoScaleMulti(KW_GLOBAL_VAR int* KW_RESTR #ifdef FW_OPENCL_CPU // CPU/MIC implementation DETERMINE_INDICES_4_MULTI_1_CPU(); if (pattern < endPattern) { - DETERMINE_INDICES_4_MULTI_2_CPU(); + DETERMINE_INDICES_4_MULTI_2_CPU(); const KW_GLOBAL_VAR int* KW_RESTRICT states1 = states + ptrOffsets[opIndexPtr + 2]; const KW_GLOBAL_VAR int* KW_RESTRICT states2 = states + ptrOffsets[opIndexPtr + 3]; DETERMINE_INDICES_4_MULTI_3_CPU(); @@ -1315,7 +1305,7 @@ KW_GLOBAL_KERNEL void kernelStatesStatesFixedScaleMulti( #ifdef FW_OPENCL_CPU // CPU/MIC implementation DETERMINE_INDICES_4_MULTI_1_CPU(); if (pattern < endPattern) { - DETERMINE_INDICES_4_MULTI_2_CPU(); + DETERMINE_INDICES_4_MULTI_2_CPU(); const KW_GLOBAL_VAR int* KW_RESTRICT states1 = states + ptrOffsets[opIndexPtr + 2]; const KW_GLOBAL_VAR int* KW_RESTRICT states2 = states + ptrOffsets[opIndexPtr + 3]; DETERMINE_INDICES_4_MULTI_3_CPU(); @@ -1534,7 +1524,7 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulate(KW_GLOBAL_VAR REAL* FIND_MAX_PARTIALS_MATRIX_4_GPU(); if (matrixMax[pat] == 0) matrixMax[pat] = 1.0; - scalingFactors[pattern] = matrixMax[pat]; + scalingFactors[pattern] = matrixMax[pat]; #ifdef CUDA atomicAdd(&cumulativeScaling[pattern], log(matrixMax[pat])); #else @@ -1775,7 +1765,7 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsMulti(KW_GLOBAL_VAR REAL* KW_RES dResult[pattern] = sumTotal; else if (takeLog == 1) dResult[pattern] = log(dResult[pattern] + sumTotal); - else + else dResult[pattern] += sumTotal; #else // GPU implementation DETERMINE_INTEGRATE_INDICES_4_GPU(); @@ -1785,7 +1775,7 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsMulti(KW_GLOBAL_VAR REAL* KW_RES dResult[pattern] = sum[pat][state]; else if (takeLog == 1) dResult[pattern] = log(dResult[pattern] + sum[pat][state]); - else + else dResult[pattern] += sum[pat][state]; } #endif // FW_OPENCL_CPU @@ -1818,7 +1808,7 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsFixedScaleMulti(KW_GLOBAL_VAR RE } } dIndexMaxScalingFactors[pattern] = indexMaxScalingFactor; - dMaxScalingFactors[pattern] = maxScalingFactor; + dMaxScalingFactors[pattern] = maxScalingFactor; if (indexMaxScalingFactor != 0) sumTotal *= exp((REAL)(cumulativeScalingFactor - maxScalingFactor)); dResult[pattern] = sumTotal; @@ -1845,7 +1835,7 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsFixedScaleMulti(KW_GLOBAL_VAR RE } } dIndexMaxScalingFactors[pattern] = indexMaxScalingFactor; - dMaxScalingFactors[pattern] = maxScalingFactor; + dMaxScalingFactors[pattern] = maxScalingFactor; if (indexMaxScalingFactor != 0) sum[pat][state] *= exp((REAL)(cumulativeScalingFactor - maxScalingFactor)); if (state == 0) @@ -2119,7 +2109,7 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsCheckScale(KW_GLOBAL_VAR REAL* parti int patIdx16pat4 = multBy16(patIdx) | (tx & 0xC); int y = deltaPartialsByState + deltaPartialsByMatrix; - + KW_GLOBAL_VAR REAL* matrix1 = matrices1 + x2; // Points to *this* matrix KW_GLOBAL_VAR REAL* matrix2 = matrices2 + x2; @@ -2168,21 +2158,21 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsCheckScale(KW_GLOBAL_VAR REAL* parti i = (i + 1) & 0x3; sum1 += sMatrix1[multBy4(i) | state] * sPartials1[patIdx16pat4 | i]; sum2 += sMatrix2[multBy4(i) | state] * sPartials2[patIdx16pat4 | i]; - + REAL tmpPartial = sum1 * sum2; - + partials3[u] = tmpPartial; if (tmpPartial < SCALING_THRESHOLD_LOWER || tmpPartial > SCALING_THRESHOLD_UPPER) *dRescalingTrigger = 1; - + // union {float f; long l;} fl; // fl.f = sum1 * sum2;; // // partials3[u] = fl.f; -// +// // int expTmp = ((fl.l >> 23) & 0x000000ff) - 0x7e; -// +// // if (abs(expTmp) > SCALING_EXPONENT_THRESHOLD) // *dRescalingTrigger = 1; } @@ -2257,9 +2247,9 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsFixedCheckScale(KW_GLOBAL_VAR REAL* i = (i + 1) & 0x3; sum1 += sMatrix1[i * 4 + state] * sPartials1[patIdx * 16 + pat * 4 + i]; sum2 += sMatrix2[i * 4 + state] * sPartials2[patIdx * 16 + pat * 4 + i]; - + REAL tmpPartial = sum1 * sum2 * fixedScalingFactors[patIdx * 4 + pat]; - + partials3[u] = tmpPartial; if (tmpPartial < SCALING_THRESHOLD_LOWER || tmpPartial > SCALING_THRESHOLD_UPPER) @@ -2285,7 +2275,7 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsAutoScale(KW_GLOBAL_VAR REAL* partia int patIdx16pat4 = multBy16(patIdx) | (tx & 0xC); int y = deltaPartialsByState + deltaPartialsByMatrix; int myIdx = multBy16(patIdx) + tx; // threadId in block - + KW_GLOBAL_VAR REAL* matrix1 = matrices1 + x2; // Points to *this* matrix KW_GLOBAL_VAR REAL* matrix2 = matrices2 + x2; @@ -2332,13 +2322,13 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsAutoScale(KW_GLOBAL_VAR REAL* partia i = (i + 1) & 0x3; sum1 += sMatrix1[multBy4(i) | state] * sPartials1[patIdx16pat4 | i]; sum2 += sMatrix2[multBy4(i) | state] * sPartials2[patIdx16pat4 | i]; - + REAL tmpPartial = sum1 * sum2; int expTmp; - REAL sigTmp = frexp(tmpPartial, &expTmp); + REAL sigTmp = frexp(tmpPartial, &expTmp); KW_LOCAL_FENCE; - + if (pattern < endPattern) { if (abs(expTmp) > SCALING_EXPONENT_THRESHOLD) { // now using sPartials2 to hold scaling trigger boolean @@ -2348,28 +2338,28 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsAutoScale(KW_GLOBAL_VAR REAL* partia sPartials2[patIdx16pat4] = 0; sPartials1[myIdx] = 0; } - } - + } + KW_LOCAL_FENCE; - + int scalingActive = sPartials2[patIdx16pat4]; - + if (scalingActive) { // now using sPartials1 to store max unscaled partials3 sPartials1[myIdx] = tmpPartial; } - + KW_LOCAL_FENCE; - + // Unrolled parallel max-reduction if (scalingActive && state < 2) { REAL compare = sPartials1[myIdx + 2]; if (compare > sPartials1[myIdx]) sPartials1[myIdx] = compare; } - + KW_LOCAL_FENCE; - + if (scalingActive && state < 1) { REAL maxPartial = sPartials1[myIdx + 1]; if (maxPartial < sPartials1[myIdx]) @@ -2380,10 +2370,10 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsAutoScale(KW_GLOBAL_VAR REAL* partia } KW_LOCAL_FENCE; - - if (scalingActive) + + if (scalingActive) partials3[u] = ldexp(sigTmp, expTmp - sPartials1[patIdx16pat4]); - + if ((myIdx < PATTERN_BLOCK_SIZE * 4) && (myIdx + (KW_GROUP_ID_0 * PATTERN_BLOCK_SIZE * 4) < endPattern)) scalingFactors[(KW_GROUP_ID_0 * PATTERN_BLOCK_SIZE * 4) + (matrix * endPattern) + myIdx] = sPartials1[multBy4(myIdx)]; } @@ -2394,16 +2384,16 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateReciprocal(KW_GLOBAL KW_GLOBAL_VAR REAL* cumulativeScaling, int matrixCount) { int tx = KW_LOCAL_ID_0; - + int state = tx & 0x3; int pat = tx >> 2; - + int patIdx = KW_GROUP_ID_0; - + int pattern = (patIdx << 2) + pat; int matrix = KW_LOCAL_ID_1; // TODO: Assumes matrixCount < MATRIX_BLOCK_SIZ - + // Patterns are always padded, so no reading/writing past end possible // Find start of patternBlock for thread-block int partialsOffset = (matrix * KW_NUM_GROUPS_0 + patIdx) << 4; //* 16; @@ -2412,14 +2402,14 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateReciprocal(KW_GLOBAL KW_LOCAL_MEM REAL storedPartials[MATRIX_BLOCK_SIZE][16]; KW_LOCAL_MEM REAL matrixMax[4]; - + if (matrix < matrixCount) - partials[matrix][tx] = allPartials[partialsOffset + tx]; + partials[matrix][tx] = allPartials[partialsOffset + tx]; storedPartials[matrix][tx] = partials[matrix][tx]; - + KW_LOCAL_FENCE; - + // Unrolled parallel max-reduction if (state < 2) { REAL compare1 = partials[matrix][tx]; @@ -2428,7 +2418,7 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateReciprocal(KW_GLOBAL partials[matrix][tx] = compare2; } KW_LOCAL_FENCE; - + if (state < 1) { REAL compare1 = partials[matrix][tx]; REAL compare2 = partials[matrix][tx + 1]; @@ -2436,7 +2426,7 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateReciprocal(KW_GLOBAL partials[matrix][tx] = compare2; } KW_LOCAL_FENCE; - + // Could also parallel-reduce here. if (state == 0 && matrix == 0) { matrixMax[pat] = 0; @@ -2445,11 +2435,11 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateReciprocal(KW_GLOBAL if (partials[m][tx] > matrixMax[pat]) matrixMax[pat] = partials[m][tx]; } - + if (matrixMax[pat] == 0) matrixMax[pat] = 1.0; - - scalingFactors[pattern] = 1/matrixMax[pat]; + + scalingFactors[pattern] = 1/matrixMax[pat]; cumulativeScaling[pattern] += log(matrixMax[pat]); } @@ -2457,7 +2447,7 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateReciprocal(KW_GLOBAL if (matrix < matrixCount) allPartials[partialsOffset + tx] = storedPartials[matrix][tx] / matrixMax[pat]; - + } KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateDifference(KW_GLOBAL_VAR REAL* allPartials, @@ -2466,16 +2456,16 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateDifference(KW_GLOBAL KW_GLOBAL_VAR REAL* cumulativeScaling, int matrixCount) { int tx = KW_LOCAL_ID_0; - + int state = tx & 0x3; int pat = tx >> 2; - + int patIdx = KW_GROUP_ID_0; - + int pattern = (patIdx << 2) + pat; int matrix = KW_LOCAL_ID_1; // TODO: Assumes matrixCount < MATRIX_BLOCK_SIZ - + // Patterns are always padded, so no reading/writing past end possible // Find start of patternBlock for thread-block int partialsOffset = (matrix * KW_NUM_GROUPS_0 + patIdx) << 4; //* 16; @@ -2484,14 +2474,14 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateDifference(KW_GLOBAL KW_LOCAL_MEM REAL storedPartials[MATRIX_BLOCK_SIZE][16]; KW_LOCAL_MEM REAL matrixMax[4]; - + if (matrix < matrixCount) - partials[matrix][tx] = allPartials[partialsOffset + tx]; + partials[matrix][tx] = allPartials[partialsOffset + tx]; storedPartials[matrix][tx] = partials[matrix][tx]; - + KW_LOCAL_FENCE; - + // Unrolled parallel max-reduction if (state < 2) { REAL compare1 = partials[matrix][tx]; @@ -2500,7 +2490,7 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateDifference(KW_GLOBAL partials[matrix][tx] = compare2; } KW_LOCAL_FENCE; - + if (state < 1) { REAL compare1 = partials[matrix][tx]; REAL compare2 = partials[matrix][tx + 1]; @@ -2508,7 +2498,7 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateDifference(KW_GLOBAL partials[matrix][tx] = compare2; } KW_LOCAL_FENCE; - + // Could also parallel-reduce here. if (state == 0 && matrix == 0) { matrixMax[pat] = 0; @@ -2517,12 +2507,12 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateDifference(KW_GLOBAL if (partials[m][tx] > matrixMax[pat]) matrixMax[pat] = partials[m][tx]; } - + if (matrixMax[pat] == 0) matrixMax[pat] = 1.0; - + REAL currentFactors = existingScalingFactors[pattern]; - scalingFactors[pattern] = 1/matrixMax[pat] * currentFactors; + scalingFactors[pattern] = 1/matrixMax[pat] * currentFactors; cumulativeScaling[pattern] += (log(matrixMax[pat])); } @@ -2530,7 +2520,7 @@ KW_GLOBAL_KERNEL void kernelPartialsDynamicScalingAccumulateDifference(KW_GLOBAL if (matrix < matrixCount) allPartials[partialsOffset + tx] = storedPartials[matrix][tx] / matrixMax[pat]; - + } KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsAutoScaling(KW_GLOBAL_VAR REAL* dResult, @@ -2543,9 +2533,9 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsAutoScaling(KW_GLOBAL_VAR REAL* int state = KW_LOCAL_ID_0; int pat = KW_LOCAL_ID_1; int pattern = KW_GROUP_ID_0 * LIKE_PATTERN_BLOCK_SIZE + KW_LOCAL_ID_1; - + KW_LOCAL_MEM REAL stateFreq[4]; - + // TODO: Currently assumes MATRIX_BLOCK_SIZE >= matrixCount KW_LOCAL_MEM REAL matrixProp[MATRIX_BLOCK_SIZE]; KW_LOCAL_MEM REAL sum[LIKE_PATTERN_BLOCK_SIZE][4]; @@ -2555,9 +2545,9 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsAutoScaling(KW_GLOBAL_VAR REAL* if (pat == 0) { stateFreq[state] = dFrequencies[state]; } - + sum[pat][state] = 0; - + // TODO: Assumes matrixCount < LIKE_PATTERN_BLOCK_SIZE * 4 if (pat * 4 + state < matrixCount) { matrixProp[pat * 4 + state] = dWeights[pat * 4 + state]; diff --git a/libhmsbeagle/GPU/kernels/kernelsAll.cu b/libhmsbeagle/GPU/kernels/kernelsAll.cu old mode 100644 new mode 100755 index 2522c6c38..6dfed614b --- a/libhmsbeagle/GPU/kernels/kernelsAll.cu +++ b/libhmsbeagle/GPU/kernels/kernelsAll.cu @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres @@ -27,8 +17,9 @@ #include #include #include - extern "C" { -#elif defined(FW_OPENCL) + #include + extern "C" { +#elif defined(FW_OPENCL) #ifdef DOUBLE_PRECISION #pragma OPENCL EXTENSION cl_khr_fp64: enable #endif @@ -73,10 +64,10 @@ KW_GLOBAL_KERNEL void kernelReorderPatterns( KW_GLOBAL_VAR REAL* KW_GLOBAL_VAR REAL* KW_RESTRICT dPatternWeightsSort, int patternCount, int paddedPatternCount) { -#ifdef FW_OPENCL_CPU +#ifdef FW_OPENCL_CPU int state = 0; int pattern = KW_LOCAL_ID_0 + KW_GROUP_ID_0 * KW_LOCAL_SIZE_0; -#else +#else int state = KW_LOCAL_ID_0; int pattern = KW_LOCAL_ID_1 + KW_GROUP_ID_0 * KW_LOCAL_SIZE_1; #endif @@ -97,10 +88,10 @@ KW_GLOBAL_KERNEL void kernelReorderPatterns( KW_GLOBAL_VAR REAL* const KW_GLOBAL_VAR REAL* KW_RESTRICT partialOriginal = dPartials + dTipOffsets[tip]; KW_GLOBAL_VAR REAL* KW_RESTRICT partialSorted = dPartials + dTipOffsets[tip+tipCount]; -#ifdef FW_OPENCL_CPU +#ifdef FW_OPENCL_CPU for (int i=0; i < stateCount; i++) { partialSorted[sortIndex+i] = partialOriginal[originIndex+i]; - } + } #else sortIndex += state; originIndex += state; @@ -128,7 +119,7 @@ KW_GLOBAL_KERNEL void kernelMatrixMulADBMulti(KW_GLOBAL_VAR REAL* dMatrices, int length, int wB, int totalMatrix) { - + int wMatrix = KW_GROUP_ID_0 % totalMatrix; int offIndex = wMatrix * 3; @@ -337,7 +328,7 @@ KW_GLOBAL_KERNEL void kernelMatrixMulADB(KW_GLOBAL_VAR REAL* dMatrices, PADDED_STATE_COUNT * ty + tx] = Csub; } } - + KW_GLOBAL_KERNEL void kernelMatrixMulADBFirstDeriv(KW_GLOBAL_VAR REAL* dMatrices, KW_GLOBAL_VAR unsigned int* listC, KW_GLOBAL_VAR REAL* A, @@ -380,7 +371,7 @@ KW_GLOBAL_KERNEL void kernelMatrixMulADBFirstDeriv(KW_GLOBAL_VAR REAL* dMatrices distanceLength = distanceQueue[wMatrix]; distanceRate = distanceQueue[wMatrix + totalMatrix]; #endif - + KW_LOCAL_FENCE; const int EDGE = PADDED_STATE_COUNT - (BLOCKS - 1) * MULTIPLY_BLOCK_SIZE; @@ -626,7 +617,7 @@ KW_GLOBAL_KERNEL void kernelMatrixMulADBSecondDeriv(KW_GLOBAL_VAR REAL* dMatrice PADDED_STATE_COUNT * ty + tx] = CSecondDerivSub; } } - + KW_GLOBAL_KERNEL void kernelMatrixConvolution(KW_GLOBAL_VAR REAL* dMatrices, KW_GLOBAL_VAR unsigned int* list, int totalMatrixCount @@ -643,7 +634,7 @@ KW_GLOBAL_KERNEL void kernelMatrixConvolution(KW_GLOBAL_VAR REAL* dMatrices, int ty = KW_LOCAL_ID_1; int BLOCKS = KW_NUM_GROUPS_1; - + #ifdef CUDA KW_LOCAL_MEM REAL* A; KW_LOCAL_MEM REAL* B; @@ -786,7 +777,7 @@ KW_GLOBAL_KERNEL void kernelMatrixTranspose(KW_GLOBAL_VAR REAL* dMatrices, } KW_LOCAL_FENCE; - + if (row < PADDED_STATE_COUNT && col < PADDED_STATE_COUNT) { C[PADDED_STATE_COUNT * rowOffset + colOffset + PADDED_STATE_COUNT * ty + tx] = As[tx][ty]; @@ -1011,7 +1002,7 @@ KW_GLOBAL_KERNEL void kernelMatrixMulADBComplexMulti(KW_GLOBAL_VAR REAL* dMatric } #endif } - + KW_GLOBAL_KERNEL void kernelMatrixMulADBComplex(KW_GLOBAL_VAR REAL* dMatrices, KW_GLOBAL_VAR unsigned int* listC, @@ -1240,13 +1231,13 @@ KW_GLOBAL_KERNEL void kernelMatrixMulADBComplex(KW_GLOBAL_VAR REAL* dMatrices, } #endif } - + KW_GLOBAL_KERNEL void kernelSumSites1(KW_GLOBAL_VAR REAL* dArray, KW_GLOBAL_VAR REAL* dSum, KW_GLOBAL_VAR REAL* dPatternWeights, int patternCount) { #ifdef FW_OPENCL_CPU - + REAL sum = 0; int pattern = KW_GROUP_ID_0 * SUM_SITES_BLOCK_SIZE; @@ -1263,7 +1254,7 @@ KW_GLOBAL_KERNEL void kernelSumSites1(KW_GLOBAL_VAR REAL* dArray, dSum[KW_GROUP_ID_0] = sum; #else - + KW_LOCAL_MEM REAL sum[SUM_SITES_BLOCK_SIZE]; int tx = KW_LOCAL_ID_0; @@ -1294,7 +1285,7 @@ KW_GLOBAL_KERNEL void kernelSumSites1Partition(KW_GLOBAL_VAR REAL* dArray, int startPattern, int endPattern) { #ifdef FW_OPENCL_CPU - + REAL sum = 0; int pattern = startPattern + KW_GROUP_ID_0 * SUM_SITES_BLOCK_SIZE; @@ -1311,7 +1302,7 @@ KW_GLOBAL_KERNEL void kernelSumSites1Partition(KW_GLOBAL_VAR REAL* dArray, dSum[KW_GROUP_ID_0] = sum; #else - + KW_LOCAL_MEM REAL sum[SUM_SITES_BLOCK_SIZE]; int tx = KW_LOCAL_ID_0; @@ -1340,13 +1331,13 @@ KW_GLOBAL_KERNEL void kernelSumSites1Partition(KW_GLOBAL_VAR REAL* dArray, // KW_GLOBAL_VAR REAL* dSum, // KW_GLOBAL_VAR REAL* dPatternWeights, // KW_GLOBAL_VAR unsigned int* dPtrOffsets) { - + // int opIndexPtr = KW_GROUP_ID_0 * 2; // int startPattern = dPtrOffsets[opIndexPtr ]; // int endPattern = dPtrOffsets[opIndexPtr + 1]; // #ifdef FW_OPENCL_CPU - + // REAL sum = 0; // int pattern = startPattern + KW_GROUP_ID_0 * SUM_SITES_BLOCK_SIZE; @@ -1359,7 +1350,7 @@ KW_GLOBAL_KERNEL void kernelSumSites1Partition(KW_GLOBAL_VAR REAL* dArray, // dSum[KW_GROUP_ID_0] = sum; // #else - + // KW_LOCAL_MEM REAL sum[SUM_SITES_BLOCK_SIZE]; // int tx = KW_LOCAL_ID_0; @@ -1392,7 +1383,7 @@ KW_GLOBAL_KERNEL void kernelSumSites2(KW_GLOBAL_VAR REAL* dArray1, int patternCount) { #ifdef FW_OPENCL_CPU - + REAL sum1 = 0, sum2 = 0; int pattern = KW_GROUP_ID_0 * SUM_SITES_BLOCK_SIZE; @@ -1455,7 +1446,7 @@ KW_GLOBAL_KERNEL void kernelSumSites3(KW_GLOBAL_VAR REAL* dArray1, int patternCount) { #ifdef FW_OPENCL_CPU - + REAL sum1 = 0, sum2 = 0, sum3 = 0; int pattern = KW_GROUP_ID_0 * SUM_SITES_BLOCK_SIZE; @@ -1983,6 +1974,640 @@ KW_GLOBAL_KERNEL void kernelAccumulateFactorsAutoScaling(KW_GLOBAL_VAR signed ch rootScaling[index] = total; } + +/* + * BASTA kernels + */ + +KW_GLOBAL_KERNEL void kernelInnerBastaPartialsCoalescent(KW_GLOBAL_VAR REAL* KW_RESTRICT partials, + KW_GLOBAL_VAR REAL* KW_RESTRICT matrices, + KW_GLOBAL_VAR REAL* KW_RESTRICT operations, + KW_GLOBAL_VAR REAL* KW_RESTRICT sizes, + KW_GLOBAL_VAR REAL* KW_RESTRICT coalescent, + int intervalNumber, + int start, + int numOps, + int totalPatterns) { + + #define PATTERN_BLOCK_SIZE_B 4 + #define BLOCK_PEELING_SIZE_B 4 + + int state = KW_LOCAL_ID_0; + int patIdx = KW_LOCAL_ID_1; + int pattern = __umul24(KW_GROUP_ID_0,PATTERN_BLOCK_SIZE_B) + patIdx; + + KW_LOCAL_MEM REAL sMatrix1[BLOCK_PEELING_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sMatrix2[BLOCK_PEELING_SIZE_B][PADDED_STATE_COUNT]; + + KW_LOCAL_MEM REAL sPartials1[PATTERN_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + int op = pattern + start; + int maxOp = start + totalPatterns - 1; + int desIndex = operations[op * numOps]; + int child1PartialIndex = operations[op * numOps + 1]; + int child1TransIndex = operations[maxOp * numOps + 2]; + int child2PartialIndex = (pattern < totalPatterns) ? operations[op * numOps + 3] : -1; + int child2TransIndex = (pattern < totalPatterns) ? operations[op * numOps + 4] : -1; + int accumulation1PartialIndex = operations[op * numOps + 5]; + int accumulation2PartialIndex = operations[op * numOps + 6]; + + KW_LOCAL_MEM REAL sPartials3[PATTERN_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL popSizes[PADDED_STATE_COUNT]; + + if (pattern < totalPatterns) { + KW_GLOBAL_VAR REAL* KW_RESTRICT partials1 = partials + child1PartialIndex; + sPartials1[patIdx][state] = partials1[state]; + //printf("op %d \n", op); + //printf("index %d \n", child1PartialIndex); + //printf("partials1 %1.2e \n", partials1[state]); + } else { + sPartials1[patIdx][state] = 0; + } + REAL sum1 = 0; + + KW_GLOBAL_VAR REAL* KW_RESTRICT matrix1 = matrices + child1TransIndex; + for (int i = 0; i < PADDED_STATE_COUNT; i += BLOCK_PEELING_SIZE_B) { + /* load one row of matrices */ + if (patIdx < BLOCK_PEELING_SIZE_B) { + /* These are all coherent global memory reads. */ + sMatrix1[patIdx][state] = matrix1[patIdx * PADDED_STATE_COUNT + state]; + /* sMatrix now filled with starting in state and ending in i */ + matrix1 += BLOCK_PEELING_SIZE_B * PADDED_STATE_COUNT; + } + KW_LOCAL_FENCE; + for(int j = 0; j < BLOCK_PEELING_SIZE_B; j++) { + FMA(sMatrix1[j][state], sPartials1[patIdx][i + j], sum1); + } + KW_LOCAL_FENCE; + } + + + if (pattern < totalPatterns) { + KW_GLOBAL_VAR REAL* KW_RESTRICT partials3 = partials + desIndex; + partials3[state] = sum1; + } + + + /* copy PADDED_STATE_COUNT*PATTERN_BLOCK_SIZE lengthed partials */ + /* These are all coherent global memory reads; checked in Profiler */ + KW_LOCAL_MEM REAL sPartials2[PATTERN_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + + if (pattern < totalPatterns && child2PartialIndex >= 0) { + KW_GLOBAL_VAR REAL* KW_RESTRICT partials2 = partials + child2PartialIndex; + sPartials2[patIdx][state] = partials2[state]; + popSizes[state] = sizes[state]; + } else { + sPartials2[patIdx][state] = 0; + popSizes[state] = 0; + } + + if (patIdx == 0) { + popSizes[state] = sizes[state]; + } + + REAL sum2 = 0; + + KW_GLOBAL_VAR REAL* KW_RESTRICT matrix2 = matrices + child1TransIndex; + for (int i = 0; i < PADDED_STATE_COUNT; i += BLOCK_PEELING_SIZE_B) { + /* load one row of matrices */ + if (patIdx < BLOCK_PEELING_SIZE_B) { + /* These are all coherent global memory reads. */ + sMatrix2[patIdx][state] = matrix2[patIdx * PADDED_STATE_COUNT + state]; + /* sMatrix now filled with starting in state and ending in i */ + matrix2 += BLOCK_PEELING_SIZE_B * PADDED_STATE_COUNT; + } + KW_LOCAL_FENCE; + for(int j = 0; j < BLOCK_PEELING_SIZE_B; j++) { + FMA(sMatrix2[j][state], sPartials2[patIdx][i + j], sum2); + } + KW_LOCAL_FENCE; + } + + + if (pattern < totalPatterns && child2PartialIndex >= 0) { + KW_GLOBAL_VAR REAL* KW_RESTRICT partials3 = partials + desIndex; + KW_GLOBAL_VAR REAL* KW_RESTRICT accumulation1 = partials + accumulation1PartialIndex; + KW_GLOBAL_VAR REAL* KW_RESTRICT accumulation2 = partials + accumulation2PartialIndex; + accumulation1[state] = sum1; + accumulation2[state] = sum2; + if (popSizes[state] > 0) { + partials3[state] = sum1 * sum2 / popSizes[state]; + } else { + partials3[state] = 0; + } + sPartials3[patIdx][state] = partials3[state]; + +#ifdef IS_POWER_OF_TWO + // parallelized reduction *** only works for powers-of-2 **** + for (int i = PADDED_STATE_COUNT / 2; i > 0; i >>= 1) { + if (state < i) { +#else + for (int i = SMALLEST_POWER_OF_TWO / 2; i > 0; i >>= 1) { + if (state < i && state + i < PADDED_STATE_COUNT) { +#endif // IS_POWER_OF_TWO + sPartials3[patIdx][state] += sPartials3[patIdx][state + i]; + } + KW_LOCAL_FENCE; + } + REAL denominator = sPartials3[patIdx][0]; + partials3[state] = partials3[state] / denominator; + coalescent[intervalNumber] = denominator; + } +} + + + +//KW_GLOBAL_KERNEL void kernelBastaReduceWithinInterval(KW_GLOBAL_VAR REAL* e, + //KW_GLOBAL_VAR REAL* f, + //KW_GLOBAL_VAR REAL* g, + //KW_GLOBAL_VAR REAL* h, + //KW_GLOBAL_VAR REAL* KW_RESTRICT startPartials1, + //KW_GLOBAL_VAR REAL* KW_RESTRICT startPartials2, + //KW_GLOBAL_VAR REAL* KW_RESTRICT endPartials1, + //KW_GLOBAL_VAR REAL* KW_RESTRICT endPartials2, + //int intervalNumber, + //int child2PartialIndex, + //int renew) { + + //#define SUM_SITES_BLOCK_SIZE_B 64 + //#define SUM_PARTIAL_BLOCK_SIZE_B 4 + //int state = KW_LOCAL_ID_0; + //int u = KW_LOCAL_ID_0 + KW_GROUP_ID_0 * SUM_SITES_BLOCK_SIZE_B; + //int y = intervalNumber * PADDED_STATE_COUNT; + //KW_LOCAL_MEM REAL sPartials1[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + + //if (state < PADDED_STATE_COUNT) { + //sPartials1[0][state] = startPartials1[u]; + //sPartials1[1][state] = startPartials1[u] * startPartials1[u]; + //sPartials1[2][state] = endPartials1[u]; + //sPartials1[3][state] = endPartials1[u] * endPartials1[u]; + //} else { + //sPartials1[0][state] = 0; + //sPartials1[1][state] = 0; + //sPartials1[2][state] = 0; + //sPartials1[3][state] = 0; + //} + + //if (renew == 0) { + //e[y + state] = sPartials1[0][state]; + //f[y + state] = sPartials1[1][state]; + //g[y + state] = sPartials1[2][state]; + //h[y + state] = sPartials1[3][state]; + //} else { + //e[y + state] += sPartials1[0][state]; + //f[y + state] += sPartials1[1][state]; + //g[y + state] += sPartials1[2][state]; + //h[y + state] += sPartials1[3][state]; + //} + + //KW_LOCAL_MEM REAL sPartials2[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + //if (child2PartialIndex >= 0) { + //if (state < PADDED_STATE_COUNT) { + //sPartials2[0][state] = startPartials2[u]; + //sPartials2[1][state] = startPartials2[u] * startPartials2[u]; + //sPartials2[2][state] = endPartials2[u]; + //sPartials2[3][state] = endPartials2[u] * endPartials2[u]; + //} else { + //sPartials2[0][state] = 0; + //sPartials2[1][state] = 0; + //sPartials2[2][state] = 0; + //sPartials2[3][state] = 0; + ///} + //e[y + state] += sPartials2[0][state]; + //f[y + state] += sPartials2[1][state]; + //g[y + state] += sPartials2[2][state]; + //h[y + state] += sPartials2[3][state]; + //} +//} + +KW_GLOBAL_KERNEL void kernelAccumulateCarryOutFinal(KW_GLOBAL_VAR REAL* dBastaFinalResMemory, + KW_GLOBAL_VAR REAL* dBastaMemory, + KW_GLOBAL_VAR REAL* intervals, + int numSubinterval, + int numSubintervalFinal, + int kCoalescentBufferLength) { +#define SUM_PARTIAL_BLOCK_SIZE_B 4 + int state = KW_LOCAL_ID_0; + int opIdx = KW_LOCAL_ID_1; + int opBlock = KW_GROUP_ID_0; + int opNumber = KW_LOCAL_ID_1 + opBlock * SUM_PARTIAL_BLOCK_SIZE_B; + int opCount = numSubintervalFinal; + int u = opNumber * PADDED_STATE_COUNT; + + KW_GLOBAL_VAR REAL* e = dBastaMemory; + KW_GLOBAL_VAR REAL* f = e + PADDED_STATE_COUNT * kCoalescentBufferLength; + KW_GLOBAL_VAR REAL* g = f + PADDED_STATE_COUNT * kCoalescentBufferLength; + KW_GLOBAL_VAR REAL* h = g + PADDED_STATE_COUNT * kCoalescentBufferLength; + KW_GLOBAL_VAR REAL* keys = intervals + 2 * numSubinterval; + + KW_LOCAL_MEM REAL sResE[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sResF[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sResG[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sResH[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sSegmentKeys[SUM_PARTIAL_BLOCK_SIZE_B]; + + if (opNumber < opCount && (state < PADDED_STATE_COUNT)) { + int m = numSubintervalFinal * PADDED_STATE_COUNT; + sSegmentKeys[opIdx] = keys[opNumber]; + sResE[opIdx][state] = dBastaFinalResMemory[u + state]; + sResF[opIdx][state] = dBastaFinalResMemory[m + u + state]; + sResG[opIdx][state] = dBastaFinalResMemory[2 * m + u + state]; + sResH[opIdx][state] = dBastaFinalResMemory[3 * m + u + state]; + } else { + sSegmentKeys[opIdx] = -1; + sResE[opIdx][state] = 0; + sResF[opIdx][state] = 0; + sResG[opIdx][state]= 0; + sResH[opIdx][state] = 0; + } + + KW_LOCAL_FENCE; + + if (opNumber < opCount && (state < PADDED_STATE_COUNT)) { + int intervalNumber = sSegmentKeys[opIdx]; + int y = intervalNumber * PADDED_STATE_COUNT; + + atomicAdd(&e[y + state], sResE[opIdx][state]); + atomicAdd(&f[y + state], sResF[opIdx][state]); + atomicAdd(&g[y + state], sResG[opIdx][state]); + atomicAdd(&h[y + state], sResH[opIdx][state]); + } +} + +KW_GLOBAL_KERNEL void kernelPreProcessBastaFlags(KW_GLOBAL_VAR REAL* KW_RESTRICT intervals, + KW_GLOBAL_VAR REAL* flags, + KW_GLOBAL_VAR REAL* blockEnds, + int operationCount, + int numBlocks) { +#define SUM_PARTIAL_BLOCK_SIZE_B 4 + int opIdx = KW_LOCAL_ID_0; + int opBlock = KW_GROUP_ID_0; + int opNumber = KW_LOCAL_ID_0 + opBlock * SUM_PARTIAL_BLOCK_SIZE_B; + int blockSize = SUM_PARTIAL_BLOCK_SIZE_B; + + if (opNumber < operationCount) { + if (opNumber == 0 || intervals[opNumber] != intervals[opNumber - 1]) { + flags[opNumber] = 1; + } else { + flags[opNumber] = 0; + } + } + + KW_LOCAL_FENCE; + + if (opBlock < numBlocks && opIdx == 0) { + int start_index = opBlock * blockSize; + int end_index = min(start_index + blockSize - 1, operationCount - 1); + blockEnds[opBlock] = intervals[end_index]; + } +} + + +KW_GLOBAL_KERNEL void kernelAccumulateCarryOut(KW_GLOBAL_VAR REAL* dBastaBlockResMemory, + KW_GLOBAL_VAR REAL* dBastaFinalResMemory, + KW_GLOBAL_VAR REAL* intervals, + int numSubinterval, + int numSubintervalFinal) { + +#define SUM_PARTIAL_BLOCK_SIZE_B 4 + int state = KW_LOCAL_ID_0; + int opIdx = KW_LOCAL_ID_1; + int opBlock = KW_GROUP_ID_0; + int opNumber = KW_LOCAL_ID_1 + opBlock * SUM_PARTIAL_BLOCK_SIZE_B; + int opCount = numSubinterval; + int blockSize = SUM_PARTIAL_BLOCK_SIZE_B; + + KW_GLOBAL_VAR REAL* e = dBastaFinalResMemory; + KW_GLOBAL_VAR REAL* f = e + PADDED_STATE_COUNT * numSubintervalFinal; + KW_GLOBAL_VAR REAL* g = f + PADDED_STATE_COUNT * numSubintervalFinal; + KW_GLOBAL_VAR REAL* h = g + PADDED_STATE_COUNT * numSubintervalFinal; + KW_GLOBAL_VAR REAL* flags = intervals + numSubinterval; + + KW_LOCAL_MEM REAL sPartialsE[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sPartialsF[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sPartialsG[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sPartialsH[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sSegmentKeys[SUM_PARTIAL_BLOCK_SIZE_B]; + KW_LOCAL_MEM REAL sSegmentFlags[SUM_PARTIAL_BLOCK_SIZE_B]; + + if (opNumber < opCount && (state < PADDED_STATE_COUNT)) { + int op = opNumber; + int u = op * PADDED_STATE_COUNT; + int m = numSubinterval * PADDED_STATE_COUNT; + sSegmentFlags[opIdx] = flags[op]; + sSegmentKeys[opIdx] = intervals[op]; + sPartialsE[opIdx][state] = dBastaBlockResMemory[u + state]; + sPartialsF[opIdx][state] = dBastaBlockResMemory[m + u + state]; + sPartialsG[opIdx][state] = dBastaBlockResMemory[2 * m + u + state]; + sPartialsH[opIdx][state] = dBastaBlockResMemory[3 * m + u + state]; + + } else { + sPartialsE[opIdx][state] = 0; + sPartialsF[opIdx][state] = 0; + sPartialsG[opIdx][state] = 0; + sPartialsH[opIdx][state] = 0; + sSegmentKeys[opIdx] = -1; + sSegmentFlags[opIdx] = 0; + } + + KW_LOCAL_FENCE; + + + int intervalNumber = sSegmentKeys[opIdx]; + int y = intervalNumber * PADDED_STATE_COUNT; + for (int stride = 1; stride < blockSize; stride *= 2) { + int k = (opIdx + 1) * 2 * stride - 1; + if (k < blockSize) { + if (sSegmentFlags[k] == 0) { + sPartialsE[k][state] += sPartialsE[k - stride][state]; + sPartialsF[k][state] += sPartialsF[k - stride][state]; + sPartialsG[k][state] += sPartialsG[k - stride][state]; + sPartialsH[k][state] += sPartialsH[k - stride][state]; + sSegmentFlags[k] = sSegmentFlags[k - stride]; + } + } + KW_LOCAL_FENCE; + } + + for (int stride = blockSize / 2; stride > 0; stride /= 2) { + int k = (opIdx + 1) * 2 * stride - 1; + if (k + stride < blockSize) { + if (sSegmentFlags[k + stride] == 0) { + sPartialsE[k + stride][state] += sPartialsE[k][state]; + sPartialsF[k + stride][state] += sPartialsF[k][state]; + sPartialsG[k + stride][state] += sPartialsG[k][state]; + sPartialsH[k + stride][state] += sPartialsH[k][state]; + sSegmentFlags[k + stride] = sSegmentFlags[k]; + } + } + KW_LOCAL_FENCE; + } + + if (sSegmentKeys[opIdx] != sSegmentKeys[opIdx + 1] && (opIdx < blockSize - 1) && (opNumber < opCount -1)) { + e[y + state] = sPartialsE[opIdx][state]; + f[y + state] = sPartialsF[opIdx][state]; + g[y + state] = sPartialsG[opIdx][state]; + h[y + state] = sPartialsH[opIdx][state]; + } + + if (opIdx == blockSize - 1 && (opNumber < opCount -1) || opNumber == opCount -1) { + e[y + state] = sPartialsE[opIdx][state]; + f[y + state] = sPartialsF[opIdx][state]; + g[y + state] = sPartialsG[opIdx][state]; + h[y + state] = sPartialsH[opIdx][state]; + } + + +} + + +KW_GLOBAL_KERNEL void kernelBastaReduceWithinIntervalSerial(KW_GLOBAL_VAR REAL* KW_RESTRICT operations, + KW_GLOBAL_VAR REAL* KW_RESTRICT partials, + KW_GLOBAL_VAR REAL* dBastaMemory, + int numOps, + int start, + int end, + int kCoalescentBufferLength) { + int state = KW_LOCAL_ID_0; + int opCount = end - start; + int blockSize = SUM_PARTIAL_BLOCK_SIZE_B; + + KW_GLOBAL_VAR REAL* e = dBastaMemory; + KW_GLOBAL_VAR REAL* f = e + PADDED_STATE_COUNT * kCoalescentBufferLength; + KW_GLOBAL_VAR REAL* g = f + PADDED_STATE_COUNT * kCoalescentBufferLength; + KW_GLOBAL_VAR REAL* h = g + PADDED_STATE_COUNT * kCoalescentBufferLength; + + + if (state < PADDED_STATE_COUNT) { + for (int opIdx = 0; opIdx < opCount; ++opIdx) { + int op = start + opIdx; + int intervalNumber = operations[op * numOps + 7]; + int child1PartialIndex = operations[op * numOps + 1]; + int accumulation1PartialIndex = operations[op * numOps + 5]; + int u = intervalNumber * PADDED_STATE_COUNT + state; + KW_GLOBAL_VAR REAL* startPartials1 = partials + child1PartialIndex; + KW_GLOBAL_VAR REAL* endPartials1 = partials + accumulation1PartialIndex; + + REAL partialE = startPartials1[state]; + REAL partialF = partialE * partialE; + REAL partialG = endPartials1[state]; + REAL partialH = partialG * partialG; + + int child2PartialIndex = operations[op * numOps + 3]; + int accumulation2PartialIndex = operations[op * numOps + 6]; + if (child2PartialIndex >= 0) { + KW_GLOBAL_VAR REAL* startPartials2 = partials + child2PartialIndex; + KW_GLOBAL_VAR REAL* endPartials2 = partials + accumulation2PartialIndex; + partialE += startPartials2[state]; + partialF += startPartials2[state] * startPartials2[state]; + partialG += endPartials2[state]; + partialH += endPartials2[state] * endPartials2[state]; + } + + e[u] += partialE; + f[u] += partialF; + g[u] += partialG; + h[u] += partialH; + } + } +} + +KW_GLOBAL_KERNEL void kernelBastaReduceWithinInterval(KW_GLOBAL_VAR REAL* KW_RESTRICT operations, + KW_GLOBAL_VAR REAL* KW_RESTRICT partials, + KW_GLOBAL_VAR REAL* dBastaBlockResMemory, + KW_GLOBAL_VAR REAL* intervals, + int numOps, + int start, + int end, + int numSubinterval) { + +#define SUM_PARTIAL_BLOCK_SIZE_B 4 + + int state = KW_LOCAL_ID_0; + int opIdx = KW_LOCAL_ID_1; + int opBlock = KW_GROUP_ID_0; + int opNumber = KW_LOCAL_ID_1 + opBlock * SUM_PARTIAL_BLOCK_SIZE_B; + int opCount = end - start; + // int opCountLast = opCount % SUM_PARTIAL_BLOCK_SIZE_B; + // int blockSize = (SUM_PARTIAL_BLOCK_SIZE_B > opCountLast) ? opCountLast : SUM_PARTIAL_BLOCK_SIZE_B; + int blockSize = SUM_PARTIAL_BLOCK_SIZE_B; + + KW_GLOBAL_VAR REAL* e = dBastaBlockResMemory; + KW_GLOBAL_VAR REAL* f = e + PADDED_STATE_COUNT * numSubinterval; + KW_GLOBAL_VAR REAL* g = f + PADDED_STATE_COUNT * numSubinterval; + KW_GLOBAL_VAR REAL* h = g + PADDED_STATE_COUNT * numSubinterval; + KW_GLOBAL_VAR REAL* flags = intervals + end; + + KW_LOCAL_MEM REAL sPartialsE[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sPartialsF[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sPartialsG[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sPartialsH[SUM_PARTIAL_BLOCK_SIZE_B][PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sSegmentKeys[SUM_PARTIAL_BLOCK_SIZE_B]; + KW_LOCAL_MEM REAL sSegmentFlags[SUM_PARTIAL_BLOCK_SIZE_B]; + + if (opNumber < opCount && (state < PADDED_STATE_COUNT)) { + int op = opNumber + start; + int child1PartialIndex = operations[op * numOps + 1]; + int accumulation1PartialIndex = operations[op * numOps + 5]; + KW_GLOBAL_VAR REAL* startPartials1 = partials + child1PartialIndex; + KW_GLOBAL_VAR REAL* endPartials1 = partials + accumulation1PartialIndex; + KW_GLOBAL_VAR REAL* partialIntervals = intervals + start; + sSegmentFlags[opIdx] = flags[op]; + sSegmentKeys[opIdx] = partialIntervals[op]; + sPartialsE[opIdx][state] = startPartials1[state]; + sPartialsF[opIdx][state] = startPartials1[state] * startPartials1[state]; + sPartialsG[opIdx][state] = endPartials1[state]; + sPartialsH[opIdx][state] = endPartials1[state] * endPartials1[state]; + } else { + sPartialsE[opIdx][state] = 0; + sPartialsF[opIdx][state] = 0; + sPartialsG[opIdx][state] = 0; + sPartialsH[opIdx][state] = 0; + sSegmentKeys[opIdx] = -1; + sSegmentFlags[opIdx] = 0; + } + + KW_LOCAL_FENCE; + + + int intervalNumber = sSegmentKeys[opIdx]; + int y = intervalNumber * PADDED_STATE_COUNT; + + if (opNumber < opCount && state < PADDED_STATE_COUNT) { + int op = opNumber + start; + int child2PartialIndex = operations[op * numOps + 3]; + int accumulation2PartialIndex = operations[op * numOps + 6]; + KW_GLOBAL_VAR REAL* startPartials2 = partials + child2PartialIndex; + KW_GLOBAL_VAR REAL* endPartials2 = partials + accumulation2PartialIndex; + e[y + state] = 0; + f[y + state] = 0; + g[y + state] = 0; + h[y + state] = 0; + + KW_LOCAL_FENCE; + + if (child2PartialIndex >= 0) { + e[y + state] = startPartials2[state]; + f[y + state] = startPartials2[state] * startPartials2[state]; + g[y + state] = endPartials2[state]; + h[y + state] = endPartials2[state] * endPartials2[state]; + } + } + + for (int stride = 1; stride < blockSize; stride *= 2) { + int k = (opIdx + 1) * 2 * stride - 1; + if (k < blockSize) { + if (sSegmentFlags[k] == 0) { + sPartialsE[k][state] += sPartialsE[k - stride][state]; + sPartialsF[k][state] += sPartialsF[k - stride][state]; + sPartialsG[k][state] += sPartialsG[k - stride][state]; + sPartialsH[k][state] += sPartialsH[k - stride][state]; + sSegmentFlags[k] = sSegmentFlags[k - stride]; + } + } + KW_LOCAL_FENCE; + } + + for (int stride = blockSize / 2; stride > 0; stride /= 2) { + int k = (opIdx + 1) * 2 * stride - 1; + if (k + stride < blockSize) { + if (sSegmentFlags[k + stride] == 0) { + sPartialsE[k + stride][state] += sPartialsE[k][state]; + sPartialsF[k + stride][state] += sPartialsF[k][state]; + sPartialsG[k + stride][state] += sPartialsG[k][state]; + sPartialsH[k + stride][state] += sPartialsH[k][state]; + sSegmentFlags[k + stride] = sSegmentFlags[k]; + } + } + KW_LOCAL_FENCE; + } + + //if (sSegmentKeys[opIdx] != sSegmentKeys[opIdx + 1]) { + //if (sSegmentFlags[opIdx] == 0) { + //sPartialsE[opIdx][state] += sPartialsE[opIdx - 1][state]; + //sPartialsF[opIdx][state] += sPartialsF[opIdx - 1][state]; + //sPartialsG[opIdx][state] += sPartialsG[opIdx - 1][state]; + //sPartialsH[opIdx][state] += sPartialsH[opIdx - 1][state]; + //} + //} + + if (opIdx == blockSize - 1 && (opNumber < opCount -1) || opNumber == opCount -1) { + e[y + state] += sPartialsE[opIdx][state]; + f[y + state] += sPartialsF[opIdx][state]; + g[y + state] += sPartialsG[opIdx][state]; + h[y + state] += sPartialsH[opIdx][state]; + } + + if (sSegmentKeys[opIdx] != sSegmentKeys[opIdx + 1] && (opIdx < blockSize - 1) && (opNumber < opCount -1)) { + e[y + state] += sPartialsE[opIdx][state]; + f[y + state] += sPartialsF[opIdx][state]; + g[y + state] += sPartialsG[opIdx][state]; + h[y + state] += sPartialsH[opIdx][state]; + } +} + +KW_GLOBAL_KERNEL void kernelBastaReduceAcrossInterval(KW_GLOBAL_VAR REAL* KW_RESTRICT dBastaMemory, + KW_GLOBAL_VAR REAL* KW_RESTRICT distance, + KW_GLOBAL_VAR REAL* KW_RESTRICT dLogL, + KW_GLOBAL_VAR REAL* KW_RESTRICT sizes, + KW_GLOBAL_VAR REAL* KW_RESTRICT coalescent, + int intervalStartsCount, + int kCoalescentBufferLength) { + +#define SUM_INTERVAL_BLOCK_SIZE 4 + + int intervalCount = intervalStartsCount - 1; + int tid = KW_LOCAL_ID_0; + int tidTotal = __umul24(KW_GROUP_ID_0, SUM_INTERVAL_BLOCK_SIZE * PADDED_STATE_COUNT) + tid; + int state = tid % PADDED_STATE_COUNT; + int intervalIdx = tid / PADDED_STATE_COUNT; + int intervalNumber = __umul24(KW_GROUP_ID_0, SUM_INTERVAL_BLOCK_SIZE) + intervalIdx; + int u = state + intervalNumber * PADDED_STATE_COUNT; + + KW_GLOBAL_VAR REAL* e = dBastaMemory; + KW_GLOBAL_VAR REAL* f = e + PADDED_STATE_COUNT * kCoalescentBufferLength; + KW_GLOBAL_VAR REAL* g = f + PADDED_STATE_COUNT * kCoalescentBufferLength; + KW_GLOBAL_VAR REAL* h = g + PADDED_STATE_COUNT * kCoalescentBufferLength; + + KW_LOCAL_MEM REAL sPartials1[SUM_INTERVAL_BLOCK_SIZE * PADDED_STATE_COUNT]; + KW_LOCAL_MEM REAL sPartials2[SUM_INTERVAL_BLOCK_SIZE]; + + if (intervalNumber < intervalCount && (sizes[state] > 0)) { + sPartials1[tid] = (e[u] * e[u] - f[u] + + g[u] * g[u] - h[u]) * distance[intervalNumber] / sizes[state]; + } else { + sPartials1[tid] = 0; + } + KW_LOCAL_FENCE; + + if (tidTotal < intervalCount && (coalescent[u] != 0)) { + sPartials2[tid] = log(coalescent[u]); + } else { + sPartials2[tid] = 0; + } + KW_LOCAL_FENCE; + + + for (int i = SUM_INTERVAL_BLOCK_SIZE * PADDED_STATE_COUNT / 2; i > 0; i >>= 1) { + if (tid < i) { + sPartials1[tid] += sPartials1[tid + i]; + } + KW_LOCAL_FENCE; + } + + for (int i = SUM_INTERVAL_BLOCK_SIZE * PADDED_STATE_COUNT / 2; i > 0; i >>= 1) { + if (tid < i) { + sPartials2[tid] += sPartials2[tid + i]; + } + KW_LOCAL_FENCE; + } + + if (tid == 0) { + REAL temp = - sPartials1[0] / 4 + sPartials2[0]; + dLogL[KW_GROUP_ID_0] = temp; + } + } + + #ifdef CUDA } // extern "C" #endif //CUDA diff --git a/libhmsbeagle/GPU/kernels/kernelsX.cu b/libhmsbeagle/GPU/kernels/kernelsX.cu index 62c58f71a..90f159d82 100644 --- a/libhmsbeagle/GPU/kernels/kernelsX.cu +++ b/libhmsbeagle/GPU/kernels/kernelsX.cu @@ -4,19 +4,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Marc Suchard * @author Daniel Ayres @@ -25,7 +15,7 @@ #ifdef CUDA #include "libhmsbeagle/GPU/GPUImplDefs.h" #include "libhmsbeagle/GPU/kernels/kernelsAll.cu" // This file includes the non-state-count specific kernels - extern "C" { + extern "C" { #endif /////////////////////////////////////////////////////////////////////////////// @@ -535,7 +525,7 @@ KW_GLOBAL_KERNEL void kernelStatesStatesNoScale(KW_GLOBAL_VAR int* KW_RESTRICT s int state1 = states1[pattern]; int state2 = states2[pattern]; KW_GLOBAL_VAR REAL* KW_RESTRICT matrix1 = matrices1 + deltaMatrix + state1 * PADDED_STATE_COUNT; - KW_GLOBAL_VAR REAL* KW_RESTRICT matrix2 = matrices2 + deltaMatrix + state2 * PADDED_STATE_COUNT; + KW_GLOBAL_VAR REAL* KW_RESTRICT matrix2 = matrices2 + deltaMatrix + state2 * PADDED_STATE_COUNT; if (state1 < PADDED_STATE_COUNT && state2 < PADDED_STATE_COUNT) { partials3[u] = matrix1[state] * matrix2[state]; } else if (state1 < PADDED_STATE_COUNT) { @@ -550,7 +540,7 @@ KW_GLOBAL_KERNEL void kernelStatesStatesNoScale(KW_GLOBAL_VAR int* KW_RESTRICT s int state1 = states1[pattern]; int state2 = states2[pattern]; KW_GLOBAL_VAR REAL* KW_RESTRICT matrix1 = matrices1 + deltaMatrix + state1 * PADDED_STATE_COUNT; - KW_GLOBAL_VAR REAL* KW_RESTRICT matrix2 = matrices2 + deltaMatrix + state2 * PADDED_STATE_COUNT; + KW_GLOBAL_VAR REAL* KW_RESTRICT matrix2 = matrices2 + deltaMatrix + state2 * PADDED_STATE_COUNT; if (pattern < totalPatterns) { if (state1 < PADDED_STATE_COUNT && state2 < PADDED_STATE_COUNT) { partials3[u] = matrix1[state] * matrix2[state]; @@ -1131,7 +1121,7 @@ KW_GLOBAL_KERNEL void kernelStatesPartialsEdgeLikelihoodsSecondDeriv(KW_GLOBAL_V if (pattern < totalPatterns) { dPartialsTmp[u] = sum1 * sPartials2[patIdx][state]; dFirstDerivTmp[u] = sumFirstDeriv * sPartials2[patIdx][state]; - dSecondDerivTmp[u] = sumSecondDeriv * sPartials2[patIdx][state]; + dSecondDerivTmp[u] = sumSecondDeriv * sPartials2[patIdx][state]; } #endif // FW_OPENCL_CPU } @@ -1281,27 +1271,27 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsAutoScale(KW_GLOBAL_VAR REAL* partia sPartials1[patIdx][0] = 0; } } - + KW_LOCAL_FENCE; - + int scalingActive = sPartials2[patIdx][0]; - + if (scalingActive) { // now using sPartials1 to store max unscaled partials3 sPartials1[patIdx][state] = tmpPartial; } - + KW_LOCAL_FENCE; - + // Unrolled parallel max-reduction if (scalingActive && state < 2) { REAL compare = sPartials1[patIdx][state + 2]; if (compare > sPartials1[patIdx][state]) sPartials1[patIdx][state] = compare; } - + KW_LOCAL_FENCE; - + if (scalingActive && state < 1) { REAL maxPartial = sPartials1[patIdx][1]; if (maxPartial < sPartials1[patIdx][0]) @@ -1312,7 +1302,7 @@ KW_GLOBAL_KERNEL void kernelPartialsPartialsAutoScale(KW_GLOBAL_VAR REAL* partia } KW_LOCAL_FENCE; - + if (scalingActive) partials3[u] = ldexp(sigTmp, expTmp - sPartials1[patIdx][0]); @@ -1356,14 +1346,14 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsAutoScaling(KW_GLOBAL_VAR REAL* int u = state + pattern * PADDED_STATE_COUNT; int delta = patternCount * PADDED_STATE_COUNT; - + short maxScaleFactor = matrixScalers[0]; for(int r = 1; r < matrixCount; r++) { int tmpFactor = matrixScalers[r]; if (tmpFactor > maxScaleFactor) maxScaleFactor = tmpFactor; } - + for(int r = 0; r < matrixCount; r++) { int tmpFactor = matrixScalers[r]; if (tmpFactor != maxScaleFactor) { @@ -1394,6 +1384,9 @@ KW_GLOBAL_KERNEL void kernelIntegrateLikelihoodsAutoScaling(KW_GLOBAL_VAR REAL* dResult[pattern] = (log(sum[state]) + (M_LN2 * maxScaleFactor)); } + + + #ifdef CUDA #include "kernelsXDerivatives.cu" #endif // CUDA diff --git a/libhmsbeagle/JNI/CMakeLists.txt b/libhmsbeagle/JNI/CMakeLists.txt index 72578278e..0b3bfdc91 100644 --- a/libhmsbeagle/JNI/CMakeLists.txt +++ b/libhmsbeagle/JNI/CMakeLists.txt @@ -19,3 +19,25 @@ endif(APPLE) install(TARGETS hmsbeagle-jni DESTINATION ${BEAGLE_INSTALL_DIR} ) + +if(BUILD_BASTA) + add_library(hmsbeagle-jni-basta SHARED + beagle_basta_BastaJNIWrapper.cpp + beagle_basta_BastaJNIWrapper.h + ) + + target_link_libraries(hmsbeagle-jni-basta hmsbeagle) + + if(APPLE) + set_target_properties(hmsbeagle-jni-basta PROPERTIES PREFIX "lib" SUFFIX ".jnilib") + elseif(WIN32) + set_target_properties(hmsbeagle-jni-basta PROPERTIES PREFIX "" SUFFIX "64.dll") + elseif(UNIX) + set_target_properties(hmsbeagle-jni-basta PROPERTIES PREFIX "lib" SUFFIX ".so") + endif(APPLE) + + install(TARGETS hmsbeagle-jni-basta + DESTINATION ${BEAGLE_INSTALL_DIR} + ) + +endif(BUILD_BASTA) diff --git a/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.cpp b/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.cpp index 1586b48df..08a2ded3b 100644 --- a/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.cpp +++ b/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.cpp @@ -634,6 +634,46 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setEigenDecomposition return errCode; } +/* + * Class: beagle_BeagleJNIWrapper + * Method: setSparseMatrix + * Signature: (II[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setSparseMatrix + (JNIEnv *env, jobject obj, jint instance, jint matrixIndex, jintArray inRowIndices, jintArray inColIndices, jdoubleArray inValues, jint numNonZeros) { + jint *rowIndices = env->GetIntArrayElements(inRowIndices, NULL); + jint *colIndices = env->GetIntArrayElements(inColIndices, NULL); + jdouble *values = env->GetDoubleArrayElements(inValues, NULL); + + jint errCode = (jint)beagleSetSparseMatrix(instance, matrixIndex, (int *)rowIndices, (int *)colIndices, (double *)values, numNonZeros); + + env->ReleaseIntArrayElements(inRowIndices, rowIndices, JNI_ABORT); + env->ReleaseIntArrayElements(inColIndices, colIndices, JNI_ABORT); + env->ReleaseDoubleArrayElements(inValues, values, JNI_ABORT); + + return errCode; +} + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setSparseMatrix + * Signature: (II[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setSparseDifferentialMatrix + (JNIEnv *env, jobject obj, jint instance, jint matrixIndex, jintArray inRowIndices, jintArray inColIndices, jdoubleArray inValues, jint numNonZeros) { + jint *rowIndices = env->GetIntArrayElements(inRowIndices, NULL); + jint *colIndices = env->GetIntArrayElements(inColIndices, NULL); + jdouble *values = env->GetDoubleArrayElements(inValues, NULL); + + jint errCode = (jint)beagleSetSparseDifferentialMatrix(instance, matrixIndex, (int *)rowIndices, (int *)colIndices, (double *)values, numNonZeros); + + env->ReleaseIntArrayElements(inRowIndices, rowIndices, JNI_ABORT); + env->ReleaseIntArrayElements(inColIndices, colIndices, JNI_ABORT); + env->ReleaseDoubleArrayElements(inValues, values, JNI_ABORT); + + return errCode; +} + /* * Class: beagle_BeagleJNIWrapper * Method: setStateFrequencies diff --git a/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.h b/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.h index 385f53a5d..1cdbeb374 100644 --- a/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.h +++ b/libhmsbeagle/JNI/beagle_BeagleJNIWrapper.h @@ -13,7 +13,7 @@ extern "C" { * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_beagle_BeagleJNIWrapper_getVersion - (JNIEnv *, jobject); + (JNIEnv *, jobject); /* * Class: beagle_BeagleJNIWrapper @@ -21,7 +21,7 @@ JNIEXPORT jstring JNICALL Java_beagle_BeagleJNIWrapper_getVersion * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_beagle_BeagleJNIWrapper_getCitation - (JNIEnv *, jobject); + (JNIEnv *, jobject); /* * Class: beagle_BeagleJNIWrapper @@ -29,7 +29,7 @@ JNIEXPORT jstring JNICALL Java_beagle_BeagleJNIWrapper_getCitation * Signature: ()[Lbeagle/ResourceDetails; */ JNIEXPORT jobjectArray JNICALL Java_beagle_BeagleJNIWrapper_getResourceList - (JNIEnv *, jobject); + (JNIEnv *, jobject); /* * Class: beagle_BeagleJNIWrapper @@ -37,7 +37,7 @@ JNIEXPORT jobjectArray JNICALL Java_beagle_BeagleJNIWrapper_getResourceList * Signature: (IIIII[IIJJIIIJ)[Lbeagle/BenchmarkedResourceDetails; */ JNIEXPORT jobjectArray JNICALL Java_beagle_BeagleJNIWrapper_getBenchmarkedResourceList - (JNIEnv *, jobject, jint, jint, jint, jint, jint, jintArray, jint, jlong, jlong, jint, jint, jint, jlong); + (JNIEnv *, jobject, jint, jint, jint, jint, jint, jintArray, jint, jlong, jlong, jint, jint, jint, jlong); /* * Class: beagle_BeagleJNIWrapper @@ -45,7 +45,7 @@ JNIEXPORT jobjectArray JNICALL Java_beagle_BeagleJNIWrapper_getBenchmarkedResour * Signature: (IIIIIIIII[IIJJLbeagle/InstanceDetails;)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_createInstance - (JNIEnv *, jobject, jint, jint, jint, jint, jint, jint, jint, jint, jint, jintArray, jint, jlong, jlong, jobject); + (JNIEnv *, jobject, jint, jint, jint, jint, jint, jint, jint, jint, jint, jintArray, jint, jlong, jlong, jobject); /* * Class: beagle_BeagleJNIWrapper @@ -53,7 +53,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_createInstance * Signature: (I)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_finalize - (JNIEnv *, jobject, jint); + (JNIEnv *, jobject, jint); /* * Class: beagle_BeagleJNIWrapper @@ -61,7 +61,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_finalize * Signature: (II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCPUThreadCount - (JNIEnv *, jobject, jint, jint); + (JNIEnv *, jobject, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -69,7 +69,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCPUThreadCount * Signature: (I[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPatternWeights - (JNIEnv *, jobject, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -77,7 +77,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPatternWeights * Signature: (II[I)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPatternPartitions - (JNIEnv *, jobject, jint, jint, jintArray); + (JNIEnv *, jobject, jint, jint, jintArray); /* * Class: beagle_BeagleJNIWrapper @@ -85,7 +85,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPatternPartitions * Signature: (II[I)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTipStates - (JNIEnv *, jobject, jint, jint, jintArray); + (JNIEnv *, jobject, jint, jint, jintArray); /* * Class: beagle_BeagleJNIWrapper @@ -93,7 +93,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTipStates * Signature: (II[I)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getTipStates - (JNIEnv *, jobject, jint, jint, jintArray); + (JNIEnv *, jobject, jint, jint, jintArray); /* * Class: beagle_BeagleJNIWrapper @@ -101,7 +101,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getTipStates * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTipPartials - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -109,7 +109,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTipPartials * Signature: (I[I[II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setRootPrePartials - (JNIEnv *, jobject, jint, jintArray, jintArray, jint); + (JNIEnv *, jobject, jint, jintArray, jintArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -117,7 +117,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setRootPrePartials * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPartials - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -125,7 +125,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setPartials * Signature: (III[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getPartials - (JNIEnv *, jobject, jint, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -133,7 +133,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getPartials * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getLogScaleFactors - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -141,7 +141,23 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getLogScaleFactors * Signature: (II[D[D[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setEigenDecomposition - (JNIEnv *, jobject, jint, jint, jdoubleArray, jdoubleArray, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray, jdoubleArray, jdoubleArray); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setSparseMatrix + * Signature: (II[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setSparseMatrix + (JNIEnv *, jobject, jint, jint, jintArray, jintArray, jdoubleArray, jint); + +/* + * Class: beagle_BeagleJNIWrapper + * Method: setSparseDifferentialMatrix + * Signature: (II[I[I[DI)I + */ +JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setSparseDifferentialMatrix + (JNIEnv *, jobject, jint, jint, jintArray, jintArray, jdoubleArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -149,7 +165,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setEigenDecomposition * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setStateFrequencies - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -157,7 +173,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setStateFrequencies * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryWeights - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -165,7 +181,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryWeights * Signature: (I[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryRates - (JNIEnv *, jobject, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -173,7 +189,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryRates * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryRatesWithIndex - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -181,7 +197,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setCategoryRatesWithIndex * Signature: (II[DD)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTransitionMatrix - (JNIEnv *, jobject, jint, jint, jdoubleArray, jdouble); + (JNIEnv *, jobject, jint, jint, jdoubleArray, jdouble); /* * Class: beagle_BeagleJNIWrapper @@ -189,7 +205,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setTransitionMatrix * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setDifferentialMatrix - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -197,7 +213,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_setDifferentialMatrix * Signature: (II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getTransitionMatrix - (JNIEnv *, jobject, jint, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -205,7 +221,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getTransitionMatrix * Signature: (I[I[I[II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_convolveTransitionMatrices - (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jint); + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -221,7 +237,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_addTransitionMatrices * Signature: (I[I[II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_transposeTransitionMatrices - (JNIEnv *, jobject, jint, jintArray, jintArray, jint); + (JNIEnv *, jobject, jint, jintArray, jintArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -229,7 +245,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_transposeTransitionMatrices * Signature: (II[I[I[I[DI)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updateTransitionMatrices - (JNIEnv *, jobject, jint, jint, jintArray, jintArray, jintArray, jdoubleArray, jint); + (JNIEnv *, jobject, jint, jint, jintArray, jintArray, jintArray, jdoubleArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -237,7 +253,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updateTransitionMatrices * Signature: (I[I[I[I[I[I[DI)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updateTransitionMatricesWithMultipleModels - (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jintArray, jdoubleArray, jint); + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jintArray, jdoubleArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -245,7 +261,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updateTransitionMatricesWith * Signature: (I[III)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePrePartials - (JNIEnv *, jobject, jint, jintArray, jint, jint); + (JNIEnv *, jobject, jint, jintArray, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -253,7 +269,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePrePartials * Signature: (I[II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePrePartialsByPartition - (JNIEnv *, jobject, jint, jintArray, jint); + (JNIEnv *, jobject, jint, jintArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -261,7 +277,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePrePartialsByPartition * Signature: (I[III)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePartials - (JNIEnv *, jobject, jint, jintArray, jint, jint); + (JNIEnv *, jobject, jint, jintArray, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -269,7 +285,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePartials * Signature: (I[II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePartialsByPartition - (JNIEnv *, jobject, jint, jintArray, jint); + (JNIEnv *, jobject, jint, jintArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -277,7 +293,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_updatePartialsByPartition * Signature: (I[II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_waitForPartials - (JNIEnv *, jobject, jint, jintArray, jint); + (JNIEnv *, jobject, jint, jintArray, jint); /* * Class: beagle_BeagleJNIWrapper @@ -285,7 +301,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_waitForPartials * Signature: (I[III)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_accumulateScaleFactors - (JNIEnv *, jobject, jint, jintArray, jint, jint); + (JNIEnv *, jobject, jint, jintArray, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -293,7 +309,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_accumulateScaleFactors * Signature: (I[IIII)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_accumulateScaleFactorsByPartition - (JNIEnv *, jobject, jint, jintArray, jint, jint, jint); + (JNIEnv *, jobject, jint, jintArray, jint, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -301,7 +317,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_accumulateScaleFactorsByPart * Signature: (I[III)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_removeScaleFactors - (JNIEnv *, jobject, jint, jintArray, jint, jint); + (JNIEnv *, jobject, jint, jintArray, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -309,7 +325,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_removeScaleFactors * Signature: (I[IIII)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_removeScaleFactorsByPartition - (JNIEnv *, jobject, jint, jintArray, jint, jint, jint); + (JNIEnv *, jobject, jint, jintArray, jint, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -317,7 +333,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_removeScaleFactorsByPartitio * Signature: (II)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_resetScaleFactors - (JNIEnv *, jobject, jint, jint); + (JNIEnv *, jobject, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -325,7 +341,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_resetScaleFactors * Signature: (III)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_resetScaleFactorsByPartition - (JNIEnv *, jobject, jint, jint, jint); + (JNIEnv *, jobject, jint, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -333,7 +349,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_resetScaleFactorsByPartition * Signature: (III)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_copyScaleFactors - (JNIEnv *, jobject, jint, jint, jint); + (JNIEnv *, jobject, jint, jint, jint); /* * Class: beagle_BeagleJNIWrapper @@ -341,7 +357,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_copyScaleFactors * Signature: (I[I[I[I[II[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateRootLogLikelihoods - (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -349,7 +365,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateRootLogLikelihoods * Signature: (I[I[I[I[I[III[D[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateRootLogLikelihoodsByPartition - (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jintArray, jint, jint, jdoubleArray, jdoubleArray); + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jintArray, jint, jint, jdoubleArray, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -357,7 +373,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateRootLogLikelihoodsB * Signature: (I[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getSiteLogLikelihoods - (JNIEnv *, jobject, jint, jdoubleArray); + (JNIEnv *, jobject, jint, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -365,15 +381,15 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_getSiteLogLikelihoods * Signature: (I[I[I[I[II[D[D[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateEdgeDifferentials - (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jint, jdoubleArray, jdoubleArray, jdoubleArray); + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jint, jdoubleArray, jdoubleArray, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper * Method: calculateCrossProductDifferentials - * Signature: (I[I[I[I[II[D[D[D)I + * Signature: (I[I[I[I[I[DI[D[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateCrossProductDifferentials - (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jdoubleArray, jint, jdoubleArray, jdoubleArray); + (JNIEnv *, jobject, jint, jintArray, jintArray, jintArray, jintArray, jdoubleArray, jint, jdoubleArray, jdoubleArray); /* * Class: beagle_BeagleJNIWrapper @@ -381,7 +397,7 @@ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateCrossProductDiffere * Signature: (I[I[II[I[IIII[II[D[D)I */ JNIEXPORT jint JNICALL Java_beagle_BeagleJNIWrapper_calculateEdgeDerivative - (JNIEnv *, jobject, jint, jintArray, jintArray, jint, jintArray, jintArray, jint, jint, jint, jintArray, jint, jdoubleArray, jdoubleArray); + (JNIEnv *, jobject, jint, jintArray, jintArray, jint, jintArray, jintArray, jint, jint, jint, jintArray, jint, jdoubleArray, jdoubleArray); #ifdef __cplusplus } diff --git a/libhmsbeagle/JNI/beagle_basta_BastaJNIWrapper.cpp b/libhmsbeagle/JNI/beagle_basta_BastaJNIWrapper.cpp new file mode 100755 index 000000000..a7e075e59 --- /dev/null +++ b/libhmsbeagle/JNI/beagle_basta_BastaJNIWrapper.cpp @@ -0,0 +1,172 @@ +#include +#include +#include +#include +#include +#include + +#include "libhmsbeagle/beagle.h" +#include "libhmsbeagle/JNI/beagle_basta_BastaJNIWrapper.h" + + +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: allocateCoalescentBuffers + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_allocateCoalescentBuffers + (JNIEnv *env, jobject obj, jint instance, jint bufferCount, jint bufferLength) { + + jint errCode = (jint)beagleAllocateBastaBuffers(instance, bufferCount, bufferLength); + + return errCode; +} + +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: updateBastaPartials + * Signature: (I[III)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_updateBastaPartials + (JNIEnv *env, jobject obj, jint instance, jintArray inOperations, + jint operationCount, jintArray inIntervals, jint intervalCount, + jint populationSizesIndex, jint coalescentIndex) { + + jint *operations = env->GetIntArrayElements(inOperations, NULL); + jint *intervals = env->GetIntArrayElements(inIntervals, NULL); + + jint errCode = (jint)beagleUpdateBastaPartials(instance, + (BastaOperation*) operations, operationCount, + intervals, intervalCount, + populationSizesIndex, coalescentIndex); + + env->ReleaseIntArrayElements(inOperations, operations, JNI_ABORT); + env->ReleaseIntArrayElements(inIntervals, intervals, JNI_ABORT); + + return errCode; + + } + +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: updateBastaPartialsGrad + * Signature: (I[III)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_updateBastaPartialsGrad + (JNIEnv *env, jobject obj, jint instance, jintArray inOperations, + jint operationCount, jintArray inIntervals, jint intervalCount, + jint populationSizesIndex, jint coalescentIndex) { + + jint *operations = env->GetIntArrayElements(inOperations, NULL); + jint *intervals = env->GetIntArrayElements(inIntervals, NULL); + + jint errCode = (jint)beagleUpdateBastaPartialsGrad(instance, + (BastaOperation*) operations, operationCount, + intervals, intervalCount, + populationSizesIndex, coalescentIndex); + + env->ReleaseIntArrayElements(inOperations, operations, JNI_ABORT); + env->ReleaseIntArrayElements(inIntervals, intervals, JNI_ABORT); + + return errCode; + + } + + +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_updateTransitionMatricesGrad + (JNIEnv *env, jobject obj, jint instance, jintArray inProbabilityIndices, jdoubleArray inEdgeLengths, jint count) +{ + jint *probabilityIndices = env->GetIntArrayElements(inProbabilityIndices, NULL); + jdouble *edgeLengths = env->GetDoubleArrayElements(inEdgeLengths, NULL); + jint errCode = (jint)beagleUpdateTransitionMatricesGrad(instance, (int *)probabilityIndices, (double *)edgeLengths, count); + + env->ReleaseDoubleArrayElements(inEdgeLengths, edgeLengths, JNI_ABORT); + env->ReleaseIntArrayElements(inProbabilityIndices, probabilityIndices, JNI_ABORT); + return errCode; +} +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: getBastaBuffer + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_getBastaBuffer + (JNIEnv *env, jobject object, jint instance, jint bufferIndex, jdoubleArray out) { + + jdouble *array = env->GetDoubleArrayElements(out, NULL); + jint errCode = beagleGetBastaBuffer(instance, bufferIndex, (double *)array); + + // not using JNI_ABORT flag here because we want the values to be copied back... + env->ReleaseDoubleArrayElements(out, array, 0); + return errCode; +} + +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: accumulateBastaPartials + * Signature: (I[II[II)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_accumulateBastaPartials + (JNIEnv *env, jobject object, jint instance, + jintArray inOperations, jint operationCount, + jintArray inIntervals, jint intervalCount, + jdoubleArray inIntervalLengths, + jint populationSizesIndex, + jint coalescentIndex, + jdoubleArray out) { + + jint *operations = env->GetIntArrayElements(inOperations, NULL); + jint *intervals = env->GetIntArrayElements(inIntervals, NULL); + + jdouble *array = env->GetDoubleArrayElements(out, NULL); + jdouble *intervalLengths = env->GetDoubleArrayElements(inIntervalLengths, NULL); + + jint errCode = beagleAccumulateBastaPartials(instance, + (const BastaOperation*) operations, operationCount, + intervals, intervalCount, + (double *)intervalLengths, + populationSizesIndex, + coalescentIndex, (double *)array); + + env->ReleaseIntArrayElements(inOperations, operations, JNI_ABORT); + env->ReleaseIntArrayElements(inIntervals, intervals, JNI_ABORT); + env->ReleaseDoubleArrayElements(inIntervalLengths, intervalLengths, JNI_ABORT); + + // not using JNI_ABORT flag here because we want the values to be copied back... + env->ReleaseDoubleArrayElements(out, array, 0); + + return errCode; + + } + +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_accumulateBastaPartialsGrad + (JNIEnv *env, jobject object, jint instance, + jintArray inOperations, jint operationCount, + jintArray inIntervals, jint intervalCount, + jdoubleArray inIntervalLengths, + jint populationSizesIndex, + jint coalescentIndex, + jdoubleArray out) { + + jint *operations = env->GetIntArrayElements(inOperations, NULL); + jint *intervals = env->GetIntArrayElements(inIntervals, NULL); + + jdouble *array = env->GetDoubleArrayElements(out, NULL); + jdouble *intervalLengths = env->GetDoubleArrayElements(inIntervalLengths, NULL); + + jint errCode = beagleAccumulateBastaPartialsGrad(instance, + (const BastaOperation*) operations, operationCount, + intervals, intervalCount, + (double *)intervalLengths, + populationSizesIndex, + coalescentIndex, (double *)array); + + env->ReleaseIntArrayElements(inOperations, operations, JNI_ABORT); + env->ReleaseIntArrayElements(inIntervals, intervals, JNI_ABORT); + env->ReleaseDoubleArrayElements(inIntervalLengths, intervalLengths, JNI_ABORT); + + // not using JNI_ABORT flag here because we want the values to be copied back... + env->ReleaseDoubleArrayElements(out, array, 0); + + return errCode; + + } diff --git a/libhmsbeagle/JNI/beagle_basta_BastaJNIWrapper.h b/libhmsbeagle/JNI/beagle_basta_BastaJNIWrapper.h new file mode 100755 index 000000000..79c03a924 --- /dev/null +++ b/libhmsbeagle/JNI/beagle_basta_BastaJNIWrapper.h @@ -0,0 +1,54 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class beagle_basta_BastaJNIWrapper */ + +#ifndef _Included_beagle_basta_BastaJNIWrapper +#define _Included_beagle_basta_BastaJNIWrapper +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: allocateCoalescentBuffers + * Signature: (III)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_allocateCoalescentBuffers + (JNIEnv *, jobject, jint, jint, jint); + +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: getBastaBuffer + * Signature: (II[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_getBastaBuffer + (JNIEnv *, jobject, jint, jint, jdoubleArray); + +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: updateBastaPartials + * Signature: (I[II[IIII)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_updateBastaPartials + (JNIEnv *, jobject, jint, jintArray, jint, jintArray, jint, jint, jint); + +/* + * Class: beagle_basta_BastaJNIWrapper + * Method: accumulateBastaPartials + * Signature: (I[II[III[D)I + */ +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_accumulateBastaPartials + (JNIEnv *, jobject, jint, jintArray, jint, jintArray, jint, jdoubleArray, jint, jint, jdoubleArray); + +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_accumulateBastaPartialsGrad + (JNIEnv *, jobject, jint, jintArray, jint, jintArray, jint, jdoubleArray, jint, jint, jdoubleArray); + +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_updateBastaPartialsGrad + (JNIEnv *, jobject, jint, jintArray, jint, jintArray, jint, jint, jint); + +JNIEXPORT jint JNICALL Java_beagle_basta_BastaJNIWrapper_updateTransitionMatricesGrad + (JNIEnv *, jobject, jint, jintArray, jdoubleArray, jint); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libhmsbeagle/beagle.cpp b/libhmsbeagle/beagle.cpp old mode 100644 new mode 100755 index 15b5bc6f9..76a059204 --- a/libhmsbeagle/beagle.cpp +++ b/libhmsbeagle/beagle.cpp @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Andrew Rambaut * @author Marc Suchard @@ -63,6 +53,9 @@ typedef std::pair > RsrcImpl; typedef std::list RsrcImplList; typedef std::list RsrcBenchPairList; +//std::map, int>> benchmarkDuration; +//std::map energyConsumption; + // #define BEAGLE_DEBUG_LOAD #define BEAGLE_PREORDER @@ -179,6 +172,19 @@ void beagleLoadPlugins(void) { plugins->push_back(actionplug); }catch(beagle::plugin::SharedLibraryException sle){} + try{ +#ifdef BEAGLE_DEBUG_LOAD + std::cerr << "Loading hmsbeagle-action-cuda" << std::endl; +#endif + beagle::plugin::Plugin* actiongpuplug = pm.findPlugin("hmsbeagle-action-cuda"); + plugins->push_back(actiongpuplug); + }catch(beagle::plugin::SharedLibraryException sle){ +#ifdef BEAGLE_DEBUG_LOAD + std::cerr << "Unable to load hmsbeagle-action-cuda: " << sle.getError() << std::endl; +#endif + } + + try{ beagle::plugin::Plugin* avxplug = pm.findPlugin("hmsbeagle-cpu-avx"); plugins->push_back(avxplug); @@ -334,7 +340,7 @@ BeagleResourceList* beagleGetResourceList() { return rsrcList; } -int scoreFlags(long flags1, long flags2) { +int scoreFlags(long long flags1, long long flags2) { int score = 0; unsigned long trait = 1; for(int bits=0; bits<64; bits++) { @@ -369,7 +375,7 @@ int filterResources(int* resourceList, for(PairedList::iterator it = possibleResources->begin(); it != possibleResources->end(); ++it) { int resource = (*it).second; - long resourceFlag = rsrcList->list[resource].supportFlags; + long long resourceFlag = rsrcList->list[resource].supportFlags; if ( (resourceFlag & requirementFlags) < requirementFlags) { if(it==possibleResources->begin()){ possibleResources->remove(*(it)); @@ -401,8 +407,8 @@ int rankResourceImplementationPairs(long long preferenceFlags, for(PairedList::iterator it = possibleResources->begin(); it != possibleResources->end(); ++it) { int resource = (*it).second; - long resourceRequiredFlags = rsrcList->list[resource].requiredFlags; - long resourceSupportedFlags = rsrcList->list[resource].supportFlags; + long long resourceRequiredFlags = rsrcList->list[resource].requiredFlags; + long long resourceSupportedFlags = rsrcList->list[resource].supportFlags; int resourceScore = (*it).first; #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"Possible resource: %s (%d)\n",rsrcList->list[resource].name,resourceScore); @@ -410,7 +416,7 @@ int rankResourceImplementationPairs(long long preferenceFlags, for (std::list::iterator factory = implFactory->begin(); factory != implFactory->end(); factory++) { - long factoryFlags = (*factory)->getFlags(); + long long factoryFlags = (*factory)->getFlags(); #ifdef BEAGLE_DEBUG_FLOW fprintf(stderr,"\tExamining implementation: %s\n",(*factory)->getName()); #endif @@ -467,7 +473,7 @@ BeagleBenchmarkedResourceList* beagleGetBenchmarkedResourceList(int tipCount, int eigenModelCount, int partitionCount, int calculateDerivatives, - long benchmarkFlags) { + long long benchmarkFlags) { #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION debugPatternCount = patternCount; @@ -518,7 +524,7 @@ BeagleBenchmarkedResourceList* beagleGetBenchmarkedResourceList(int tipCount, int resourceNumber; char* implName; - long benchedFlags; + long long benchedFlags; double benchmarkResultCPU; bool instOnly = false; @@ -641,8 +647,10 @@ int beagleCreateInstance(int tipCount, BeagleInstanceDetails* returnInfo) { DEBUG_CREATE_TIME(); try { - if (instances == NULL) + if (instances == NULL) { + DEBUG_CREATE_ENERGY(); instances = new std::vector; + } if (rsrcList == NULL) beagleGetResourceList(); @@ -739,6 +747,7 @@ int beagleCreateInstance(int tipCount, int beagleFinalizeInstance(int instance) { DEBUG_FINALIZE_TIME(); + DEBUG_FINALIZE_ENERGY(); // TODO: Figure out why this doesn't work on L248. try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -761,11 +770,13 @@ int beagleFinalizeInstance(int instance) { int beagleSetCPUThreadCount(int instance, int threadCount) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setCPUThreadCount(threadCount); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -773,12 +784,14 @@ int beagleSetTipStates(int instance, int tipIndex, const int* inStates) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setTipStates(tipIndex, inStates); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } catch (std::bad_alloc &) { @@ -796,12 +809,14 @@ int beagleSetTipPartials(int instance, int tipIndex, const double* inPartials) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setTipPartials(tipIndex, inPartials); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } catch (std::bad_alloc &) { @@ -819,12 +834,14 @@ int beagleSetPartials(int instance, int bufferIndex, const double* inPartials) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setPartials(bufferIndex, inPartials); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } catch (std::bad_alloc &) { @@ -843,6 +860,7 @@ int beagleSetRootPrePartials(const int instance, const int *stateFrequenciesIndices, int count){ DEBUG_START_TIME(); + DEBUG_START_ENERGY(); try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -851,6 +869,7 @@ int beagleSetRootPrePartials(const int instance, stateFrequenciesIndices, count); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } catch (std::bad_alloc &) { @@ -866,12 +885,14 @@ int beagleSetRootPrePartials(const int instance, int beagleGetPartials(int instance, int bufferIndex, int scaleIndex, double* outPartials) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->getPartials(bufferIndex, scaleIndex, outPartials); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } catch (std::bad_alloc &) { @@ -891,6 +912,7 @@ int beagleSetEigenDecomposition(int instance, const double* inInverseEigenVectors, const double* inEigenValues) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -898,6 +920,7 @@ int beagleSetEigenDecomposition(int instance, int returnValue = beagleInstance->setEigenDecomposition(eigenIndex, inEigenVectors, inInverseEigenVectors, inEigenValues); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } catch (std::bad_alloc &) { @@ -911,15 +934,47 @@ int beagleSetEigenDecomposition(int instance, } } +int beagleSetSparseMatrix(int instance, + int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros) { + DEBUG_START_TIME(); + beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + int returnValue = beagleInstance->setSparseMatrix(matrixIndex, rowIndices, colIndices, values, numNonZeros); + DEBUG_END_TIME(); + return returnValue; +} + +int beagleSetSparseDifferentialMatrix(int instance, + int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros) { + DEBUG_START_TIME(); + beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + int returnValue = beagleInstance->setSparseDifferentialMatrix(matrixIndex, rowIndices, colIndices, values, numNonZeros); + DEBUG_END_TIME(); + return returnValue; +} + int beagleSetStateFrequencies(int instance, int stateFrequenciesIndex, const double* inStateFrequencies) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setStateFrequencies(stateFrequenciesIndex, inStateFrequencies); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -927,22 +982,26 @@ int beagleSetCategoryWeights(int instance, int categoryWeightsIndex, const double* inCategoryWeights) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setCategoryWeights(categoryWeightsIndex, inCategoryWeights); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } int beagleSetPatternWeights(int instance, const double* inPatternWeights) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setPatternWeights(inPatternWeights); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -950,23 +1009,27 @@ int beagleSetPatternPartitions(int instance, int partitionCount, const int* inPatternPartitions) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setPatternPartitions(partitionCount, inPatternPartitions); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } int beagleSetCategoryRates(int instance, const double* inCategoryRates) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setCategoryRates(inCategoryRates); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -984,11 +1047,13 @@ int beagleSetCategoryRatesWithIndex(int instance, int categoryRatesIndex, const double* inCategoryRates) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setCategoryRatesWithIndex(categoryRatesIndex, inCategoryRates); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -997,12 +1062,14 @@ int beagleSetTransitionMatrix(int instance, const double* inMatrix, double paddedValue) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setTransitionMatrix(matrixIndex, inMatrix, paddedValue); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1020,12 +1087,14 @@ int beagleSetDifferentialMatrix(int instance, int matrixIndex, const double* inMatrix) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setDifferentialMatrix(matrixIndex, inMatrix); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1035,12 +1104,14 @@ int beagleSetTransitionMatrices(int instance, const double* paddedValues, int count) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->setTransitionMatrices(matrixIndices, inMatrices, paddedValues, count); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1058,11 +1129,13 @@ int beagleGetTransitionMatrix(int instance, int matrixIndex, double* outMatrix) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->getTransitionMatrix(matrixIndex,outMatrix); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1072,6 +1145,7 @@ int beagleConvolveTransitionMatrices(int instance, const int* resultIndices, const int matrixCount) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) { @@ -1080,6 +1154,7 @@ int beagleConvolveTransitionMatrices(int instance, int returnValue = beagleInstance->convolveTransitionMatrices(firstIndices, secondIndices, resultIndices, matrixCount); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } } @@ -1090,6 +1165,7 @@ int beagleAddTransitionMatrices(int instance, const int* resultIndices, int matrixCount) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) { @@ -1099,6 +1175,7 @@ int beagleAddTransitionMatrices(int instance, firstIndices, secondIndices, resultIndices, matrixCount); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } } @@ -1108,6 +1185,7 @@ int beagleTransposeTransitionMatrices(int instance, const int* resultIndices, int matrixCount) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) { @@ -1116,6 +1194,7 @@ int beagleTransposeTransitionMatrices(int instance, int returnValue = beagleInstance->transposeTransitionMatrices( inputIndices, resultIndices, matrixCount); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } } @@ -1128,6 +1207,7 @@ int beagleUpdateTransitionMatrices(int instance, const double* edgeLengths, int count) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -1136,6 +1216,7 @@ int beagleUpdateTransitionMatrices(int instance, firstDerivativeIndices, secondDerivativeIndices, edgeLengths, count); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1149,6 +1230,21 @@ int beagleUpdateTransitionMatrices(int instance, // } } +int beagleUpdateTransitionMatricesGrad(int instance, + const int* probabilityIndices, + const double* edgeLengths, + int count) { + DEBUG_START_TIME(); + DEBUG_START_ENERGY(); + beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + int returnValue = beagleInstance->updateTransitionMatricesGrad(probabilityIndices, edgeLengths, count); + DEBUG_END_TIME(); + DEBUG_END_ENERGY(); + return returnValue; +} + int beagleUpdateTransitionMatricesWithModelCategories(int instance, int* eigenIndices, const int* probabilityIndices, @@ -1157,6 +1253,7 @@ int beagleUpdateTransitionMatricesWithModelCategories(int instance, const double* edgeLengths, int count) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -1165,6 +1262,7 @@ int beagleUpdateTransitionMatricesWithModelCategories(int instance, firstDerivativeIndices, secondDerivativeIndices, edgeLengths, count); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1188,6 +1286,7 @@ int beagleUpdateTransitionMatricesWithMultipleModels(int instance, const double* edgeLengths, int count) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; @@ -1195,6 +1294,7 @@ int beagleUpdateTransitionMatricesWithMultipleModels(int instance, probabilityIndices, firstDerivativeIndices, secondDerivativeIndices, edgeLengths, count); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1204,12 +1304,14 @@ int beagleUpdatePartials(const int instance, int operationCount, int cumulativeScalingIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->updatePartials((const int*)operations, operationCount, cumulativeScalingIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1228,12 +1330,14 @@ int beagleUpdatePrePartials(const int instance, int operationCount, int cumulativeScalingIndex){ DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->updatePrePartials((const int *) operations, operationCount, cumulativeScalingIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1241,11 +1345,13 @@ int beagleUpdatePartialsByPartition(const int instance, const BeagleOperationByPartition* operations, int operationCount) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->updatePartialsByPartition((const int*)operations, operationCount); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1253,11 +1359,13 @@ int beagleUpdatePrePartialsByPartition(const int instance, const BeagleOperationByPartition* operations, int operationCount) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->updatePrePartialsByPartition((const int*)operations, operationCount); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1265,6 +1373,7 @@ int beagleWaitForPartials(const int instance, const int* destinationPartials, int destinationPartialsCount) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -1272,6 +1381,7 @@ int beagleWaitForPartials(const int instance, int returnValue = beagleInstance->waitForPartials(destinationPartials, destinationPartialsCount); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1290,12 +1400,14 @@ int beagleAccumulateScaleFactors(int instance, int count, int cumulativeScalingIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->accumulateScaleFactors(scalingIndices, count, cumulativeScalingIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1315,12 +1427,14 @@ int beagleAccumulateScaleFactorsByPartition(int instance, int cumulativeScalingIndex, int partitionIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->accumulateScaleFactorsByPartition(scalingIndices, count, cumulativeScalingIndex, partitionIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1339,12 +1453,14 @@ int beagleRemoveScaleFactors(int instance, int count, int cumulativeScalingIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->removeScaleFactors(scalingIndices, count, cumulativeScalingIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1364,12 +1480,14 @@ int beagleRemoveScaleFactorsByPartition(int instance, int cumulativeScalingIndex, int partitionIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->removeScaleFactorsByPartition(scalingIndices, count, cumulativeScalingIndex, partitionIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1386,12 +1504,14 @@ int beagleRemoveScaleFactorsByPartition(int instance, int beagleResetScaleFactors(int instance, int cumulativeScalingIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->resetScaleFactors(cumulativeScalingIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1409,12 +1529,14 @@ int beagleResetScaleFactorsByPartition(int instance, int cumulativeScalingIndex, int partitionIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->resetScaleFactorsByPartition(cumulativeScalingIndex, partitionIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1432,12 +1554,14 @@ int beagleCopyScaleFactors(int instance, int destScalingIndex, int srcScalingIndex) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->copyScaleFactors(destScalingIndex, srcScalingIndex); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1455,12 +1579,14 @@ int beagleGetScaleFactors(int instance, int srcScalingIndex, double* scaleFactors) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->getScaleFactors(srcScalingIndex, scaleFactors); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; // } // catch (std::bad_alloc &) { @@ -1482,6 +1608,7 @@ int beagleCalculateRootLogLikelihoods(int instance, int count, double* outSumLogLikelihood) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -1492,6 +1619,7 @@ int beagleCalculateRootLogLikelihoods(int instance, count, outSumLogLikelihood); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1526,6 +1654,7 @@ int beagleCalculateRootLogLikelihoodsByPartition(int instance, double* outSumLogLikelihoodByPartition, double* outSumLogLikelihood) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -1540,6 +1669,7 @@ int beagleCalculateRootLogLikelihoodsByPartition(int instance, outSumLogLikelihoodByPartition, outSumLogLikelihood); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1583,6 +1713,7 @@ int beagleCalculateEdgeLogLikelihoods(int instance, double* outSumFirstDerivative, double* outSumSecondDerivative) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -1596,6 +1727,7 @@ int beagleCalculateEdgeLogLikelihoods(int instance, outSumLogLikelihood, outSumFirstDerivative, outSumSecondDerivative); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1642,6 +1774,7 @@ int beagleCalculateEdgeLogLikelihoodsByPartition(int instance, double* outSumSecondDerivativeByPartition, double* outSumSecondDerivative) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); // try { beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) @@ -1665,6 +1798,7 @@ int beagleCalculateEdgeLogLikelihoodsByPartition(int instance, outSumSecondDerivativeByPartition, outSumSecondDerivative); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1701,11 +1835,13 @@ int beagleCalculateEdgeLogLikelihoodsByPartition(int instance, int beagleGetLogLikelihood(int instance, double* outSumLogLikelihood) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->getLogLikelihood(outSumLogLikelihood); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1721,12 +1857,14 @@ int beagleGetDerivatives(int instance, double* outSumFirstDerivative, double* outSumSecondDerivative) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->getDerivatives(outSumFirstDerivative, outSumSecondDerivative); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1744,11 +1882,13 @@ int beagleGetDerivatives(int instance, int beagleGetSiteLogLikelihoods(int instance, double* outLogLikelihoods) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->getSiteLogLikelihoods(outLogLikelihoods); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1766,11 +1906,13 @@ int beagleGetSiteDerivatives(int instance, double* outFirstDerivatives, double* outSecondDerivatives) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl* beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; int returnValue = beagleInstance->getSiteDerivatives(outFirstDerivatives, outSecondDerivatives); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); #ifdef BEAGLE_DEBUG_FP_REDUCED_PRECISION union {double f; long l;} dfp; @@ -1797,6 +1939,7 @@ int beagleCalculateEdgeDerivatives(int instance, double *outSumDerivatives, double *outSumSquaredDerivatives) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) { @@ -1815,6 +1958,7 @@ int beagleCalculateEdgeDerivatives(int instance, outSumSquaredDerivatives); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1829,6 +1973,7 @@ int beagleCalculateCrossProductDerivative(int instance, double *outSumDerivatives, double *outSumSquaredDerivatives) { DEBUG_START_TIME(); + DEBUG_START_ENERGY(); beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); if (beagleInstance == NULL) { @@ -1845,6 +1990,7 @@ int beagleCalculateCrossProductDerivative(int instance, outSumSquaredDerivatives); DEBUG_END_TIME(); + DEBUG_END_ENERGY(); return returnValue; } @@ -1855,7 +2001,151 @@ int beagleCalculateEdgeDerivative(int instance, const int *postBufferIndices, co const int categoryWeightsIndex, const int categoryRatesIndex, const int stateFrequenciesIndex, const int *cumulativeScaleIndices, int count, double *outFirstDerivative, double *outDiagonalSecondDerivative) { - fprintf(stderr, "Depricated"); + fprintf(stderr, "Function beagleCalculateEdgeDerivative is deprecated.\n"); return BEAGLE_ERROR_NO_IMPLEMENTATION; } +int beagleAllocateBastaBuffers(const int instance, + const int bufferCount, + const int bufferLength) { + DEBUG_START_TIME(); + DEBUG_START_ENERGY(); + + beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) { + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + } + + int returnValue = beagleInstance->allocateBastaBuffers(bufferCount, bufferLength); + + DEBUG_END_TIME(); + DEBUG_END_ENERGY(); + + return returnValue; +} + + +int beagleGetBastaBuffer(const int instance, + const int bufferIndex, + double* out) { + DEBUG_START_TIME(); + DEBUG_START_ENERGY(); + + beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) { + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + } + + int returnValue = beagleInstance->getBastaBuffer(bufferIndex, out); + + DEBUG_END_TIME(); + DEBUG_END_ENERGY(); + + return returnValue; +} + +int beagleUpdateBastaPartials(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex) { + DEBUG_START_TIME(); + DEBUG_START_ENERGY(); + + beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) { + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + } + + int returnValue = beagleInstance->updateBastaPartials((const int*) operations, + operationCount, intervals, intervalCount, populationSizesIndex, coalescentIndex); + + DEBUG_END_TIME(); + DEBUG_END_ENERGY(); + + return returnValue; +} + +int beagleUpdateBastaPartialsGrad(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervals, + int intervalCount, + int populationSizesIndex, + int coalescentIndex) { + DEBUG_START_TIME(); + DEBUG_START_ENERGY(); + + beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) { + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + } + + int returnValue = beagleInstance->updateBastaPartialsGrad((const int*) operations, + operationCount, intervals, intervalCount, populationSizesIndex, coalescentIndex); + + DEBUG_END_TIME(); + DEBUG_END_ENERGY(); + + return returnValue; +} + +int beagleAccumulateBastaPartials(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervalStarts, + int intervalCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out) { + DEBUG_START_TIME(); + DEBUG_START_ENERGY(); + + beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) { + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + } + + int returnValue = beagleInstance->accumulateBastaPartials((const int*) operations, operationCount, + intervalStarts, intervalCount, intervalLengths, + populationSizesIndex, coalescentIndex, + out); + + DEBUG_END_TIME(); + DEBUG_END_ENERGY(); + + return returnValue; + +} + +int beagleAccumulateBastaPartialsGrad(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervalStarts, + int intervalCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out) { + DEBUG_START_TIME(); + DEBUG_START_ENERGY(); + + beagle::BeagleImpl *beagleInstance = beagle::getBeagleInstance(instance); + if (beagleInstance == NULL) { + return BEAGLE_ERROR_UNINITIALIZED_INSTANCE; + } + + int returnValue = beagleInstance->accumulateBastaPartialsGrad((const int*) operations, operationCount, + intervalStarts, intervalCount, intervalLengths, + populationSizesIndex, coalescentIndex, + out); + + DEBUG_END_TIME(); + DEBUG_END_ENERGY(); + + return returnValue; + +} diff --git a/libhmsbeagle/beagle.h b/libhmsbeagle/beagle.h old mode 100644 new mode 100755 index 146039b08..80e3a2780 --- a/libhmsbeagle/beagle.h +++ b/libhmsbeagle/beagle.h @@ -1,29 +1,19 @@ /** * @file beagle.h * - * Copyright 2009-2013 Phylogenetic Likelihood Working Group + * Copyright 2009-2024 Phylogenetic Likelihood Working Group * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @brief This file documents the API as well as header for the * Broad-platform Evolutionary Analysis General Likelihood Evaluator * * KEY CONCEPTS - * + * * The key to BEAGLE performance lies in delivering fine-scale * parallelization while minimizing data transfer and memory copy overhead. * To accomplish this, the library lacks the concept of data structure for @@ -42,9 +32,9 @@ * calls can be asynchronous, allowing the calling program to implement * other coarse-scale parallelization schemes such as evaluating * independent genes or running concurrent Markov chains. - * + * * USAGE - * + * * To use the library, a client program first creates an instance of BEAGLE * by calling beagleCreateInstance; multiple instances per client are * possible and encouraged. All additional functions are called with a @@ -61,7 +51,7 @@ * can then be specified, including the equilibrium state frequencies, the * rates for one or more substitution rate categories and their weights, * and finally, the eigen decomposition for the substitution process. - * + * * In order to calculate the likelihood of a particular tree, the client * program then specifies a series of integration operations that * correspond to steps in Felsenstein’s algorithm. Finite-time transition @@ -77,7 +67,7 @@ * software to keep track of these dependencies. The final step in * evaluating the phylogenetic model is done using an API call that yields * a single log likelihood for the model given the data. - * + * * Aspects of the BEAGLE API design support both maximum likelihood (ML) * and Bayesian phylogenetic tree inference. For ML inference, API calls * can calculate first and second derivatives of the likelihood with @@ -102,7 +92,7 @@ * @author Marc Suchard * @author David Swofford * @author Derrick Zwickl - * + * */ #ifndef __beagle__ @@ -213,6 +203,7 @@ enum BeagleBenchmarkFlags { enum BeagleOpCodes { BEAGLE_OP_COUNT = 7, /**< Total number of integers per beagleUpdatePartials operation */ BEAGLE_PARTITION_OP_COUNT = 9, /**< Total number of integers per beagleUpdatePartialsByPartition operation */ + BEAGLE_BASTA_OP_COUNT = 8, BEAGLE_OP_NONE = -1 /**< Specify no use for indexed buffer */ }; @@ -237,7 +228,7 @@ typedef struct { char* name; /**< Name of resource as a NULL-terminated character string */ char* description; /**< Description of resource as a NULL-terminated character string */ long long supportFlags; /**< Bit-flags of supported capabilities on resource */ - long requiredFlags;/**< Bit-flags that identify resource type */ + long long requiredFlags;/**< Bit-flags that identify resource type */ } BeagleResource; /** @@ -256,10 +247,10 @@ typedef struct { char* name; /**< Name of resource as a NULL-terminated character string */ char* description; /**< Description of resource as a NULL-terminated character string */ long long supportFlags; /**< Bit-flags of supported capabilities on resource */ - long requiredFlags;/**< Bit-flags that identify resource type */ + long long requiredFlags;/**< Bit-flags that identify resource type */ int returnCode; /**< Return code of for benchmark attempt (see BeagleReturnCodes) */ char* implName; /**< Name of implementation used to benchmark resource */ - long benchedFlags; /**< Bit-flags that characterize the activate + long long benchedFlags; /**< Bit-flags that characterize the activate * capabilities of the resource and implementation for this benchmark */ double benchmarkResult; /**< Benchmark result in milliseconds */ double performanceRatio; /**< Performance ratio relative to default CPU resource */ @@ -320,7 +311,7 @@ BEAGLE_DLLEXPORT BeagleResourceList* beagleGetResourceList(void); * benchmark times and CPU performance ratios for each resource. Resources are benchmarked * with the given analysis parameters and the array is ordered from fastest to slowest. * If there is an error the function returns NULL. - * + * * @param tipCount Number of tip data elements (input) * @param compactBufferCount Number of compact state representation tips (input) * @param stateCount Number of states in the continuous-time Markov chain (input) @@ -333,14 +324,14 @@ BEAGLE_DLLEXPORT BeagleResourceList* beagleGetResourceList(void); * see BeagleFlags (input) * @param requirementFlags Bit-flags indicating required implementation characteristics, * see BeagleFlags (input) - * @param eigenModelCount Number of full-alignment rate matrix eigen-decomposition models (input) + * @param eigenModelCount Number of full-alignment rate matrix eigen-decomposition models (input) * @param partitionCount Number of partitions (input) * @param calculateDerivatives Indicates if calculation of derivatives are required (input) * @param benchmarkFlags Bit-flags indicating benchmarking preferences (input) * - * @return An ordered (fastest to slowest) list of hardware resources available to the library as a + * @return An ordered (fastest to slowest) list of hardware resources available to the library as a * BeagleBenchmarkedResourceList for the specified analysis parameters - * + * */ BEAGLE_DLLEXPORT BeagleBenchmarkedResourceList* beagleGetBenchmarkedResourceList(int tipCount, int compactBufferCount, @@ -354,7 +345,7 @@ BEAGLE_DLLEXPORT BeagleBenchmarkedResourceList* beagleGetBenchmarkedResourceList int eigenModelCount, int partitionCount, int calculateDerivatives, - long benchmarkFlags); + long long benchmarkFlags); /** * @brief Create a single instance @@ -430,7 +421,7 @@ BEAGLE_DLLEXPORT int beagleFinalize(void); * implementation. It should only be called after beagleCreateInstance and requires the * BEAGLE_FLAG_THREADING_CPP flag to be set. It has no effect on GPU-based * implementations. It has no effect with the default BEAGLE_FLAG_THREADING_NONE setting. - * If BEAGLE_FLAG_THREADING_CPP is set and this function is not called BEAGLE will use + * If BEAGLE_FLAG_THREADING_CPP is set and this function is not called BEAGLE will use * a heuristic to set an appropriate number of threads. * * @param instance Instance number (input) @@ -499,7 +490,7 @@ BEAGLE_DLLEXPORT int beagleSetRootPrePartials(const int instance, * @brief Set an instance partials buffer * * This function copies an array of partials into an instance buffer. The inPartials array should - * be stateCount * patternCount * categoryCount in length. + * be stateCount * patternCount * categoryCount in length. * * @param instance Instance number in which to set a partialsBuffer (input) * @param bufferIndex Index of destination partialsBuffer (input) @@ -549,6 +540,48 @@ BEAGLE_DLLEXPORT int beagleSetEigenDecomposition(int instance, const double* inInverseEigenVectors, const double* inEigenValues); +/** + * @brief Set a sparse generator matrix with majorization using non-zero entries + * + * This function sets a sparse matrix in an instance buffer. + * + * @param instance Instance number (input) + * @param matrixIndex Index of eigen-decomposition buffer (input) + * @param rowIndices List of row indices of non-zero entries (input) + * @param colIndices List of column indices of non-zero entries (input) + * @param values List of non-zero entry values + * @param numNonZeros Number of non-zero entries + * + * @return error code + */ +BEAGLE_DLLEXPORT int beagleSetSparseMatrix(int instance, + int matrixIndex, + const int* rowIndices, + const int* colIndices, + const double* values, + int numNonZeros); + +/** + * @brief Set a sparse differential matrix using non-zero entries + * + * This function sets a sparse matrix in an instance buffer. + * + * @param instance Instance number (input) + * @param matrixIndex Index of eigen-decomposition buffer (input) + * @param rowIndices List of row indices of non-zero entries (input) + * @param colIndices List of column indices of non-zero entries (input) + * @param values List of non-zero entry values + * @param numNonZeros Number of non-zero entries + * + * @return error code + */ +BEAGLE_DLLEXPORT int beagleSetSparseDifferentialMatrix(int instance, + int matrixIndex, + const int *rowIndices, + const int *colIndices, + const double *values, + int numNonZeros); + /** * @brief Set a state frequency buffer * @@ -562,8 +595,8 @@ BEAGLE_DLLEXPORT int beagleSetEigenDecomposition(int instance, */ BEAGLE_DLLEXPORT int beagleSetStateFrequencies(int instance, int stateFrequenciesIndex, - const double* inStateFrequencies); - + const double* inStateFrequencies); + /** * @brief Set a category weights buffer * @@ -619,7 +652,7 @@ BEAGLE_DLLEXPORT int beagleSetCategoryRatesWithIndex(int instance, */ BEAGLE_DLLEXPORT int beagleSetPatternWeights(int instance, const double* inPatternWeights); - + /** * @brief Set pattern partition assignments * @@ -662,11 +695,11 @@ BEAGLE_DLLEXPORT int beagleSetPatternPartitions(int instance, * This function convolves two lists of transition probability matrices. * * @param instance Instance number (input) - * @param firstIndices List of indices of the first transition probability matrices + * @param firstIndices List of indices of the first transition probability matrices * to convolve (input) * @param secondIndices List of indices of the second transition probability matrices * to convolve (input) - * @param resultIndices List of indices of resulting transition probability matrices + * @param resultIndices List of indices of resulting transition probability matrices * (input) * @param matrixCount Length of lists */ @@ -732,6 +765,12 @@ BEAGLE_DLLEXPORT int beagleTransposeTransitionMatrices(int instance, * * @return error code */ + +BEAGLE_DLLEXPORT int beagleUpdateTransitionMatricesGrad(int instance, + const int* probabilityIndices, + const double* edgeLengths, + int count); + BEAGLE_DLLEXPORT int beagleUpdateTransitionMatrices(int instance, int eigenIndex, const int* probabilityIndices, @@ -741,7 +780,7 @@ BEAGLE_DLLEXPORT int beagleUpdateTransitionMatrices(int instance, int count); /** - * @brief Calculate a list of transition probability matrices with + * @brief Calculate a list of transition probability matrices with * each category using a different eigen decompsition * * This function calculates a list of transition probabilities matrices and their first and @@ -759,7 +798,7 @@ BEAGLE_DLLEXPORT int beagleUpdateTransitionMatrices(int instance, * (input, NULL implies no calculation) * @param edgeLengths List of edge lengths with which to perform calculations (input) * @param count Length of lists (except for eigenIndices list) - * + * * @return error code */ BEAGLE_DLLEXPORT int beagleUpdateTransitionMatricesWithModelCategories(int instance, @@ -852,7 +891,7 @@ BEAGLE_DLLEXPORT int beagleSetDifferentialMatrix(int instance, BEAGLE_DLLEXPORT int beagleGetTransitionMatrix(int instance, int matrixIndex, double* outMatrix); - + /** * @brief Set multiple transition matrices * @@ -875,7 +914,7 @@ BEAGLE_DLLEXPORT int beagleSetTransitionMatrices(int instance, const double* paddedValues, int count); - + /** * @brief A list of integer indices which specify a partial likelihoods operation. */ @@ -1106,7 +1145,7 @@ BEAGLE_DLLEXPORT int beagleResetScaleFactorsByPartition(int instance, BEAGLE_DLLEXPORT int beagleCopyScaleFactors(int instance, int destScalingIndex, int srcScalingIndex); - + /** * @brief Get scale factors * @@ -1116,10 +1155,10 @@ BEAGLE_DLLEXPORT int beagleCopyScaleFactors(int instance, * @param srcScalingIndex Source scaleBuffer (input) * @param outScaleFactors Pointer to which to receive scaleFactors (output) */ -BEAGLE_DLLEXPORT int beagleGetScaleFactors(int instance, +BEAGLE_DLLEXPORT int beagleGetScaleFactors(int instance, int srcScalingIndex, - double* outScaleFactors); - + double* outScaleFactors); + /** * @brief Calculate site log likelihoods at a root node * @@ -1166,8 +1205,8 @@ BEAGLE_DLLEXPORT int beagleCalculateRootLogLikelihoods(int instance, * @param cumulativeScaleIndices List of scaleBuffers containing accumulated factors to apply to * each partialsBuffer (input). There should be one index for each * of bufferIndices - * @param partitionIndices List of partition indices indicating which sites in each - * partialsBuffer should be used (input). There should be one + * @param partitionIndices List of partition indices indicating which sites in each + * partialsBuffer should be used (input). There should be one * index for each of bufferIndices * @param partitionCount Number of distinct partitionIndices (input) * @param count Number of sets of partitions to integrate across (input) @@ -1289,7 +1328,7 @@ BEAGLE_DLLEXPORT int beagleCalculateEdgeLogLikelihoods(int instance, double* outSumSecondDerivative); /** - * @brief Calculate multiple site log likelihoods and derivatives along an edge with + * @brief Calculate multiple site log likelihoods and derivatives along an edge with * per partition buffers * * This function integrates lists of partials at a parent and child node with respect @@ -1309,8 +1348,8 @@ BEAGLE_DLLEXPORT int beagleCalculateEdgeLogLikelihoods(int instance, * @param cumulativeScaleIndices List of scaleBuffers containing accumulated factors to apply to * each partialsBuffer (input). There should be one index for each * of parentBufferIndices - * @param partitionIndices List of partition indices indicating which sites in each - * partialsBuffer should be used (input). There should be one + * @param partitionIndices List of partition indices indicating which sites in each + * partialsBuffer should be used (input). There should be one * index for each of parentBufferIndices * @param partitionCount Number of distinct partitionIndices (input) * @param count Number of sets of partitions to integrate across (input) @@ -1380,12 +1419,12 @@ BEAGLE_DLLEXPORT int beagleGetLogLikelihood(int instance, BEAGLE_DLLEXPORT int beagleGetDerivatives(int instance, double* outSumFirstDerivative, double* outSumSecondDerivative); - + /** * @brief Get site log likelihoods for last beagleCalculateRootLogLikelihoods or * beagleCalculateEdgeLogLikelihoods call * - * This function returns the log likelihoods for each site + * This function returns the log likelihoods for each site * * @param instance Instance number (input) * @param outLogLikelihoods Pointer to destination for resulting log likelihoods (output) @@ -1398,7 +1437,7 @@ BEAGLE_DLLEXPORT int beagleGetSiteLogLikelihoods(int instance, /** * @brief Get site derivatives for last beagleCalculateEdgeLogLikelihoods call * - * This function returns the derivatives for each site + * This function returns the derivatives for each site * * @param instance Instance number (input) * @param outFirstDerivatives Pointer to destination for resulting first derivatives (output) @@ -1408,8 +1447,67 @@ BEAGLE_DLLEXPORT int beagleGetSiteLogLikelihoods(int instance, */ BEAGLE_DLLEXPORT int beagleGetSiteDerivatives(int instance, double* outFirstDerivatives, - double* outSecondDerivatives); - + double* outSecondDerivatives); + +// START OF BASTA + +typedef struct { + int destinationPartials; /**< index of destination, or parent, partials buffer */ + int child1Partials; /**< index of first child partials buffer */ + int child1TransitionMatrix; /**< index of transition matrix of first partials child buffer */ + int child2Partials; /**< index of second child partials buffer */ + int child2TransitionMatrix; /**< index of transition matrix of second partials child buffer */ + int accumulation1Partials; + int accumulation2Partials2; + int intervalNumber; +} BastaOperation; + +BEAGLE_DLLEXPORT int beagleUpdateBastaPartials(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervalStarts, + int intervalCount, + int populationSizeIndex, + int coalescentIndex); + +BEAGLE_DLLEXPORT int beagleUpdateBastaPartialsGrad(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervalStarts, + int intervalCount, + int populationSizeIndex, + int coalescentIndex); + +BEAGLE_DLLEXPORT int beagleAccumulateBastaPartials(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervalStarts, + int intervalCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out); + +BEAGLE_DLLEXPORT int beagleAccumulateBastaPartialsGrad(const int instance, + const BastaOperation* operations, + int operationCount, + const int* intervalStarts, + int intervalCount, + const double* intervalLengths, + const int populationSizesIndex, + int coalescentIndex, + double* out); + +BEAGLE_DLLEXPORT int beagleAllocateBastaBuffers(const int instance, + const int bufferCount, + const int bufferLength); + +BEAGLE_DLLEXPORT int beagleGetBastaBuffer(const int instance, + const int bufferIndex, + double* out); + +// END OF BASTA + /* using C calling conventions so that C programs can successfully link the beagle library * (closing brace) */ diff --git a/libhmsbeagle/benchmark/BeagleBenchmark.cpp b/libhmsbeagle/benchmark/BeagleBenchmark.cpp index 972b026ad..83cda0713 100644 --- a/libhmsbeagle/benchmark/BeagleBenchmark.cpp +++ b/libhmsbeagle/benchmark/BeagleBenchmark.cpp @@ -6,19 +6,9 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * * @author Daniel Ayres * Based on synthetictest.cpp by Daniel Ayres, Aaron Darling. @@ -33,7 +23,7 @@ namespace benchmark { int gettimeofday(struct timeval *tp,void * tz) { FILETIME f; ULARGE_INTEGER ifreq; - LONGLONG res; + LONGLONG res; GetSystemTimeAsFileTime(&f); ifreq.HighPart = f.dwHighDateTime; ifreq.LowPart = f.dwLowDateTime; @@ -70,7 +60,7 @@ void gt_srand(unsigned int *seed, unsigned int newSeed) double* getRandomTipPartials( int nsites, int stateCount, unsigned int *seed ) { - double *partials = (double*) calloc(sizeof(double), nsites * stateCount); + double *partials = (double*) calloc(sizeof(double), nsites * stateCount); for( int i=0; i 1) { for (int i=0; i < partitionCount; i++) { beagleSetCategoryRatesWithIndex(instance, i, &rates[0]); @@ -218,12 +208,12 @@ int benchmarkResource(int resource, beagleSetCategoryRates(instance, &rates[0]); } - + double* patternWeights = (double*) malloc(sizeof(double) * nsites); - + for (int i = 0; i < nsites; i++) { patternWeights[i] = gt_rand(&seed) / (double) GT_RAND_MAX; - } + } beagleSetPatternWeights(instance, patternWeights); @@ -231,7 +221,7 @@ int benchmarkResource(int resource, double* partitionLogLs = NULL; double* partitionD1 = NULL; double* partitionD2 = NULL; - + if (partitionCount > 1) { partitionLogLs = (double*) malloc(sizeof(double) * partitionCount); partitionD1 = (double*) malloc(sizeof(double) * partitionCount); @@ -243,7 +233,7 @@ int benchmarkResource(int resource, if (sitePartition > partitionCount - 1) sitePartition = partitionCount - 1; patternPartitions[i] = sitePartition; - } + } } @@ -253,7 +243,7 @@ int benchmarkResource(int resource, #else double freqs[stateCount]; #endif - + // create an array containing site category weights #ifdef _WIN32 std::vector weights(rateCategoryCount); @@ -264,19 +254,19 @@ int benchmarkResource(int resource, for (int eigenIndex=0; eigenIndex < eigenCount; eigenIndex++) { for (int i = 0; i < rateCategoryCount; i++) { weights[i] = gt_rand(&seed) / (double) GT_RAND_MAX; - } - + } + beagleSetCategoryWeights(instance, eigenIndex, &weights[0]); } - + double* eval; eval = (double*)malloc(sizeof(double)*stateCount); double* evec = (double*)malloc(sizeof(double)*stateCount*stateCount); double* ivec = (double*)malloc(sizeof(double)*stateCount*stateCount); - + for (int eigenIndex=0; eigenIndex < modelCount; eigenIndex++) { if ((stateCount & (stateCount-1)) == 0) { - + for (int i=0; i(stateCount, stateCount); + + double** qmat=New2DArray(stateCount, stateCount); double* relNucRates = new double[(stateCount * stateCount - stateCount) / 2]; - + int rnum=0; for(int i=0;i(stateCount, stateCount);//eigenvecs double** teigvecs=New2DArray(stateCount, stateCount);//temp eigenvecs - double** inveigvecs=New2DArray(stateCount, stateCount);//inv eigenvecs + double** inveigvecs=New2DArray(stateCount, stateCount);//inv eigenvecs int* iwork=new int[stateCount]; double* work=new double[stateCount]; - + EigenRealGeneral(stateCount, qmat, eval, eigvalsimag, eigvecs, iwork, work); memcpy(*teigvecs, *eigvecs, stateCount*stateCount*sizeof(double)); InvertMatrix(teigvecs, stateCount, work, iwork, inveigvecs); - + for(int x=0;x 1 && i==0) { + if (partitionCount > 1 && i==0) { if (beagleSetPatternPartitions(instance, partitionCount, patternPartitions) != BEAGLE_SUCCESS) { return BEAGLE_ERROR_GENERAL; } @@ -545,19 +535,19 @@ int benchmarkResource(int resource, } int scalingFactorsCount = internalCount; - + for (int eigenIndex=0; eigenIndex < eigenCount; eigenIndex++) { if (manualScaling && !(i % rescaleFrequency)) { beagleResetScaleFactors(instance, cumulativeScalingFactorIndices[eigenIndex]); - + beagleAccumulateScaleFactors(instance, &scalingFactorsIndices[eigenIndex*internalCount], scalingFactorsCount, cumulativeScalingFactorIndices[eigenIndex]); - } + } } - + // calculate the site likelihoods at the root node if (!unrooted) { if (partitionCount > 1) { @@ -602,7 +592,7 @@ int benchmarkResource(int resource, (calcderivs ? &deriv1 : NULL), (calcderivs ? partitionD2 : NULL), (calcderivs ? &deriv2 : NULL)); - } else { + } else { beagleCalculateEdgeLogLikelihoods(instance, // instance rootIndices,// bufferIndices lastTipIndices, @@ -621,12 +611,12 @@ int benchmarkResource(int resource, } // end timing! gettimeofday(&time5,NULL); - + if (i == 0 || getTimeDiff(time0, time5) < bestTimeTotal) { bestTimeTotal = getTimeDiff(time0, time5); - } + } } - + // fprintf(stdout, "logL = %.5f \n", logL); // fprintf(stdout, "time = %.5f \n\n", getTimeDiff(time0, time5)); diff --git a/libhmsbeagle/benchmark/BeagleBenchmark.h b/libhmsbeagle/benchmark/BeagleBenchmark.h index 036be002d..e3eb85d33 100644 --- a/libhmsbeagle/benchmark/BeagleBenchmark.h +++ b/libhmsbeagle/benchmark/BeagleBenchmark.h @@ -6,20 +6,10 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . - * * @author Daniel Ayres */ @@ -46,7 +36,7 @@ #ifdef _WIN32 //From January 1, 1601 (UTC). to January 1,1970 - #define FACTOR 0x19db1ded53e8000 + #define FACTOR 0x19db1ded53e8000 #include #include #else @@ -56,11 +46,11 @@ namespace beagle { namespace benchmark { -int benchmarkResource(int resource, - int stateCount, - int ntaxa, - int nsites, - bool manualScaling, +int benchmarkResource(int resource, + int stateCount, + int ntaxa, + int nsites, + bool manualScaling, int rateCategoryCount, int nreps, int compactTipCount, @@ -73,7 +63,7 @@ int benchmarkResource(int resource, long long requirementFlags, int* resourceNumber, char** implName, - long* benchedFlags, + long long* benchedFlags, double* benchmarkResult, bool instOnly); diff --git a/libhmsbeagle/benchmark/BenchmarkHelper.h b/libhmsbeagle/benchmark/BenchmarkHelper.h index f6c01b5cd..e27880a49 100644 --- a/libhmsbeagle/benchmark/BenchmarkHelper.h +++ b/libhmsbeagle/benchmark/BenchmarkHelper.h @@ -19,11 +19,11 @@ double debugGetTime() { #include std::map, int>> benchmarkDuration; + #define DEBUG_CREATE_TIME() // Note: Calling DEBUG_FINALIZE_TIME() in beagle_library_finalize() will lead to memory errors -#define DEBUG_FINALIZE_TIME() std::string funcName(__func__);\ -std::map, int>>::iterator it;\ -std::cerr << "\nBENCHMARKS: " << __FILE__ << "\n" << "Function\tTime " << std::endl;\ +#define DEBUG_FINALIZE_TIME() std::map, int>>::iterator it;\ +std::cerr << "\nBENCHMARKS: " << __FILE__ << "\n" << "Function\tTime" << std::endl;\ for (it = benchmarkDuration.begin(); it != benchmarkDuration.end(); it++) {\ std::cerr << it->first << "\t" << std::chrono::duration_cast(it->second.first).count() << " ns" << "\t" << it->second.second << std::endl;\ } @@ -42,4 +42,43 @@ if(it != benchmarkDuration.end()){\ #define DEBUG_START_TIME() #define DEBUG_END_TIME() #define DEBUG_FINALIZE_TIME() +#endif + +#ifdef BEAGLE_BENCHMARK_ENERGY +#include +#include +#include +#include +#include + +std::map> energyConsumption; + +//TODO: Add checks on nvmlReturn_t objects + +#define DEBUG_CREATE_ENERGY() nvmlReturn_t statusInit = nvmlInit(); +#define DEBUG_FINALIZE_ENERGY() nvmlReturn_t statusShutdown = nvmlShutdown();\ +std::map>::iterator it2;\ +std::cerr << "\nBENCHMARKS ENERGY: " << __FILE__ << "\n" << "Function\tEnergy (mJ)\tnTimes" << std::endl;\ +for (it2 = energyConsumption.begin(); it2 != energyConsumption.end(); it2++) {\ + std::cerr << it2->first << "\t" << it2->second.first << "\t" << it2->second.second << std::endl;\ +} +#define DEBUG_START_ENERGY() nvmlDevice_t handle;\ +nvmlReturn_t status = nvmlDeviceGetHandleByIndex(0, &handle);\ +unsigned long long int energyStart;\ +status = nvmlDeviceGetTotalEnergyConsumption(handle, &energyStart); +#define DEBUG_END_ENERGY() unsigned long long int energyEnd;\ +status = nvmlDeviceGetTotalEnergyConsumption(handle, &energyEnd);\ +std::string energyKey = __func__;\ +std::map>::iterator it2 = energyConsumption.find(energyKey);\ +if(it2 != energyConsumption.end()){\ + it2->second.first += energyEnd - energyStart;\ + it2->second.second += 1;\ +} else {\ + energyConsumption.insert(energyConsumption.end(), std::pair>(energyKey, std::pair(energyEnd - energyStart, 1)));\ +} +#else +#define DEBUG_CREATE_ENERGY() +#define DEBUG_FINALIZE_ENERGY() +#define DEBUG_START_ENERGY() +#define DEBUG_END_ENERGY() #endif \ No newline at end of file diff --git a/hmsbeagle-1.pc b/libhmsbeagle/hmsbeagle-1.pc.in similarity index 56% rename from hmsbeagle-1.pc rename to libhmsbeagle/hmsbeagle-1.pc.in index 9cae501a5..ae5148891 100644 --- a/hmsbeagle-1.pc +++ b/libhmsbeagle/hmsbeagle-1.pc.in @@ -1,4 +1,4 @@ -prefix=/usr/local +prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include @@ -6,6 +6,6 @@ includedir=${prefix}/include Name: hmsbeagle Description: A library to calculate phylogenetic likelihoods. Requires: -Version: 4.0.0 -Libs: -L${libdir} -lhmsbeagle -Cflags: -I${includedir}/libhmsbeagle-1 +Version: @BEAGLE_VERSION@ +Libs: -L"${libdir}" -lhmsbeagle +Cflags: -I"${includedir}/libhmsbeagle-1" diff --git a/libhmsbeagle/platform.h b/libhmsbeagle/platform.h index 721313d84..b5d08c5b3 100644 --- a/libhmsbeagle/platform.h +++ b/libhmsbeagle/platform.h @@ -6,20 +6,10 @@ * * This file is part of BEAGLE. * - * BEAGLE is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. + * Use of this source code is governed by an MIT-style + * license that can be found in the LICENSE file or at + * https://opensource.org/licenses/MIT. * - * BEAGLE is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with BEAGLE. If not, see - * . - * * @author Aaron Darling */ @@ -29,9 +19,9 @@ #ifdef _WIN32 // needed to export library symbols #ifdef _EXPORTING -#define BEAGLE_DLLEXPORT __declspec(dllexport) +#define BEAGLE_DLLEXPORT __declspec(dllexport) #else -#define BEAGLE_DLLEXPORT __declspec(dllimport) +#define BEAGLE_DLLEXPORT __declspec(dllimport) #endif /* // automatically include the appropriate beagle library diff --git a/project/beagle-vs-2012-installer/COPYING.LESSER.rtf b/project/beagle-vs-2012-installer/COPYING.LESSER.rtf deleted file mode 100644 index db3d1b160..000000000 --- a/project/beagle-vs-2012-installer/COPYING.LESSER.rtf +++ /dev/null @@ -1,169 +0,0 @@ -{\rtf1\ansi\ansicpg1252\deff0{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}} -{\*\generator Msftedit 5.41.21.2500;}\viewkind4\uc1\pard\lang1033\f0\fs18\tab\tab GNU LESSER GENERAL PUBLIC LICENSE\par - Version 3, 29 June 2007\par -\par - Copyright (C) 2007 Free Software Foundation, Inc. \par - Everyone is permitted to copy and distribute verbatim copies\par - of this license document, but changing it is not allowed.\par -\par -\par - This version of the GNU Lesser General Public License incorporates\par -the terms and conditions of version 3 of the GNU General Public\par -License, supplemented by the additional permissions listed below.\par -\par - 0. Additional Definitions.\par -\par - As used herein, "this License" refers to version 3 of the GNU Lesser\par -General Public License, and the "GNU GPL" refers to version 3 of the GNU\par -General Public License.\par -\par - "The Library" refers to a covered work governed by this License,\par -other than an Application or a Combined Work as defined below.\par -\par - An "Application" is any work that makes use of an interface provided\par -by the Library, but which is not otherwise based on the Library.\par -Defining a subclass of a class defined by the Library is deemed a mode\par -of using an interface provided by the Library.\par -\par - A "Combined Work" is a work produced by combining or linking an\par -Application with the Library. The particular version of the Library\par -with which the Combined Work was made is also called the "Linked\par -Version".\par -\par - The "Minimal Corresponding Source" for a Combined Work means the\par -Corresponding Source for the Combined Work, excluding any source code\par -for portions of the Combined Work that, considered in isolation, are\par -based on the Application, and not on the Linked Version.\par -\par - The "Corresponding Application Code" for a Combined Work means the\par -object code and/or source code for the Application, including any data\par -and utility programs needed for reproducing the Combined Work from the\par -Application, but excluding the System Libraries of the Combined Work.\par -\par - 1. Exception to Section 3 of the GNU GPL.\par -\par - You may convey a covered work under sections 3 and 4 of this License\par -without being bound by section 3 of the GNU GPL.\par -\par - 2. Conveying Modified Versions.\par -\par - If you modify a copy of the Library, and, in your modifications, a\par -facility refers to a function or data to be supplied by an Application\par -that uses the facility (other than as an argument passed when the\par -facility is invoked), then you may convey a copy of the modified\par -version:\par -\par - a) under this License, provided that you make a good faith effort to\par - ensure that, in the event an Application does not supply the\par - function or data, the facility still operates, and performs\par - whatever part of its purpose remains meaningful, or\par -\par - b) under the GNU GPL, with none of the additional permissions of\par - this License applicable to that copy.\par -\par - 3. Object Code Incorporating Material from Library Header Files.\par -\par - The object code form of an Application may incorporate material from\par -a header file that is part of the Library. You may convey such object\par -code under terms of your choice, provided that, if the incorporated\par -material is not limited to numerical parameters, data structure\par -layouts and accessors, or small macros, inline functions and templates\par -(ten or fewer lines in length), you do both of the following:\par -\par - a) Give prominent notice with each copy of the object code that the\par - Library is used in it and that the Library and its use are\par - covered by this License.\par -\par - b) Accompany the object code with a copy of the GNU GPL and this license\par - document.\par -\par - 4. Combined Works.\par -\par - You may convey a Combined Work under terms of your choice that,\par -taken together, effectively do not restrict modification of the\par -portions of the Library contained in the Combined Work and reverse\par -engineering for debugging such modifications, if you also do each of\par -the following:\par -\par - a) Give prominent notice with each copy of the Combined Work that\par - the Library is used in it and that the Library and its use are\par - covered by this License.\par -\par - b) Accompany the Combined Work with a copy of the GNU GPL and this license\par - document.\par -\par - c) For a Combined Work that displays copyright notices during\par - execution, include the copyright notice for the Library among\par - these notices, as well as a reference directing the user to the\par - copies of the GNU GPL and this license document.\par -\par - d) Do one of the following:\par -\par - 0) Convey the Minimal Corresponding Source under the terms of this\par - License, and the Corresponding Application Code in a form\par - suitable for, and under terms that permit, the user to\par - recombine or relink the Application with a modified version of\par - the Linked Version to produce a modified Combined Work, in the\par - manner specified by section 6 of the GNU GPL for conveying\par - Corresponding Source.\par -\par - 1) Use a suitable shared library mechanism for linking with the\par - Library. A suitable mechanism is one that (a) uses at run time\par - a copy of the Library already present on the user's computer\par - system, and (b) will operate properly with a modified version\par - of the Library that is interface-compatible with the Linked\par - Version.\par -\par - e) Provide Installation Information, but only if you would otherwise\par - be required to provide such information under section 6 of the\par - GNU GPL, and only to the extent that such information is\par - necessary to install and execute a modified version of the\par - Combined Work produced by recombining or relinking the\par - Application with a modified version of the Linked Version. (If\par - you use option 4d0, the Installation Information must accompany\par - the Minimal Corresponding Source and Corresponding Application\par - Code. If you use option 4d1, you must provide the Installation\par - Information in the manner specified by section 6 of the GNU GPL\par - for conveying Corresponding Source.)\par -\par - 5. Combined Libraries.\par -\par - You may place library facilities that are a work based on the\par -Library side by side in a single library together with other library\par -facilities that are not Applications and are not covered by this\par -License, and convey such a combined library under terms of your\par -choice, if you do both of the following:\par -\par - a) Accompany the combined library with a copy of the same work based\par - on the Library, uncombined with any other library facilities,\par - conveyed under the terms of this License.\par -\par - b) Give prominent notice with the combined library that part of it\par - is a work based on the Library, and explaining where to find the\par - accompanying uncombined form of the same work.\par -\par - 6. Revised Versions of the GNU Lesser General Public License.\par -\par - The Free Software Foundation may publish revised and/or new versions\par -of the GNU Lesser General Public License from time to time. Such new\par -versions will be similar in spirit to the present version, but may\par -differ in detail to address new problems or concerns.\par -\par - Each version is given a distinguishing version number. If the\par -Library as you received it specifies that a certain numbered version\par -of the GNU Lesser General Public License "or any later version"\par -applies to it, you have the option of following the terms and\par -conditions either of that published version or of any later version\par -published by the Free Software Foundation. If the Library as you\par -received it does not specify a version number of the GNU Lesser\par -General Public License, you may choose any version of the GNU Lesser\par -General Public License ever published by the Free Software Foundation.\par -\par - If the Library as you received it specifies that a proxy can decide\par -whether future versions of the GNU Lesser General Public License shall\par -apply, that proxy's public statement of acceptance of any version is\par -permanent authorization for you to choose that version for the\par -Library.\par -\par -} - \ No newline at end of file diff --git a/project/beagle-vs-2017/installer/COPYING.LESSER.rtf b/project/beagle-vs-2017/installer/COPYING.LESSER.rtf deleted file mode 100644 index db3d1b160..000000000 --- a/project/beagle-vs-2017/installer/COPYING.LESSER.rtf +++ /dev/null @@ -1,169 +0,0 @@ -{\rtf1\ansi\ansicpg1252\deff0{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}} -{\*\generator Msftedit 5.41.21.2500;}\viewkind4\uc1\pard\lang1033\f0\fs18\tab\tab GNU LESSER GENERAL PUBLIC LICENSE\par - Version 3, 29 June 2007\par -\par - Copyright (C) 2007 Free Software Foundation, Inc. \par - Everyone is permitted to copy and distribute verbatim copies\par - of this license document, but changing it is not allowed.\par -\par -\par - This version of the GNU Lesser General Public License incorporates\par -the terms and conditions of version 3 of the GNU General Public\par -License, supplemented by the additional permissions listed below.\par -\par - 0. Additional Definitions.\par -\par - As used herein, "this License" refers to version 3 of the GNU Lesser\par -General Public License, and the "GNU GPL" refers to version 3 of the GNU\par -General Public License.\par -\par - "The Library" refers to a covered work governed by this License,\par -other than an Application or a Combined Work as defined below.\par -\par - An "Application" is any work that makes use of an interface provided\par -by the Library, but which is not otherwise based on the Library.\par -Defining a subclass of a class defined by the Library is deemed a mode\par -of using an interface provided by the Library.\par -\par - A "Combined Work" is a work produced by combining or linking an\par -Application with the Library. The particular version of the Library\par -with which the Combined Work was made is also called the "Linked\par -Version".\par -\par - The "Minimal Corresponding Source" for a Combined Work means the\par -Corresponding Source for the Combined Work, excluding any source code\par -for portions of the Combined Work that, considered in isolation, are\par -based on the Application, and not on the Linked Version.\par -\par - The "Corresponding Application Code" for a Combined Work means the\par -object code and/or source code for the Application, including any data\par -and utility programs needed for reproducing the Combined Work from the\par -Application, but excluding the System Libraries of the Combined Work.\par -\par - 1. Exception to Section 3 of the GNU GPL.\par -\par - You may convey a covered work under sections 3 and 4 of this License\par -without being bound by section 3 of the GNU GPL.\par -\par - 2. Conveying Modified Versions.\par -\par - If you modify a copy of the Library, and, in your modifications, a\par -facility refers to a function or data to be supplied by an Application\par -that uses the facility (other than as an argument passed when the\par -facility is invoked), then you may convey a copy of the modified\par -version:\par -\par - a) under this License, provided that you make a good faith effort to\par - ensure that, in the event an Application does not supply the\par - function or data, the facility still operates, and performs\par - whatever part of its purpose remains meaningful, or\par -\par - b) under the GNU GPL, with none of the additional permissions of\par - this License applicable to that copy.\par -\par - 3. Object Code Incorporating Material from Library Header Files.\par -\par - The object code form of an Application may incorporate material from\par -a header file that is part of the Library. You may convey such object\par -code under terms of your choice, provided that, if the incorporated\par -material is not limited to numerical parameters, data structure\par -layouts and accessors, or small macros, inline functions and templates\par -(ten or fewer lines in length), you do both of the following:\par -\par - a) Give prominent notice with each copy of the object code that the\par - Library is used in it and that the Library and its use are\par - covered by this License.\par -\par - b) Accompany the object code with a copy of the GNU GPL and this license\par - document.\par -\par - 4. Combined Works.\par -\par - You may convey a Combined Work under terms of your choice that,\par -taken together, effectively do not restrict modification of the\par -portions of the Library contained in the Combined Work and reverse\par -engineering for debugging such modifications, if you also do each of\par -the following:\par -\par - a) Give prominent notice with each copy of the Combined Work that\par - the Library is used in it and that the Library and its use are\par - covered by this License.\par -\par - b) Accompany the Combined Work with a copy of the GNU GPL and this license\par - document.\par -\par - c) For a Combined Work that displays copyright notices during\par - execution, include the copyright notice for the Library among\par - these notices, as well as a reference directing the user to the\par - copies of the GNU GPL and this license document.\par -\par - d) Do one of the following:\par -\par - 0) Convey the Minimal Corresponding Source under the terms of this\par - License, and the Corresponding Application Code in a form\par - suitable for, and under terms that permit, the user to\par - recombine or relink the Application with a modified version of\par - the Linked Version to produce a modified Combined Work, in the\par - manner specified by section 6 of the GNU GPL for conveying\par - Corresponding Source.\par -\par - 1) Use a suitable shared library mechanism for linking with the\par - Library. A suitable mechanism is one that (a) uses at run time\par - a copy of the Library already present on the user's computer\par - system, and (b) will operate properly with a modified version\par - of the Library that is interface-compatible with the Linked\par - Version.\par -\par - e) Provide Installation Information, but only if you would otherwise\par - be required to provide such information under section 6 of the\par - GNU GPL, and only to the extent that such information is\par - necessary to install and execute a modified version of the\par - Combined Work produced by recombining or relinking the\par - Application with a modified version of the Linked Version. (If\par - you use option 4d0, the Installation Information must accompany\par - the Minimal Corresponding Source and Corresponding Application\par - Code. If you use option 4d1, you must provide the Installation\par - Information in the manner specified by section 6 of the GNU GPL\par - for conveying Corresponding Source.)\par -\par - 5. Combined Libraries.\par -\par - You may place library facilities that are a work based on the\par -Library side by side in a single library together with other library\par -facilities that are not Applications and are not covered by this\par -License, and convey such a combined library under terms of your\par -choice, if you do both of the following:\par -\par - a) Accompany the combined library with a copy of the same work based\par - on the Library, uncombined with any other library facilities,\par - conveyed under the terms of this License.\par -\par - b) Give prominent notice with the combined library that part of it\par - is a work based on the Library, and explaining where to find the\par - accompanying uncombined form of the same work.\par -\par - 6. Revised Versions of the GNU Lesser General Public License.\par -\par - The Free Software Foundation may publish revised and/or new versions\par -of the GNU Lesser General Public License from time to time. Such new\par -versions will be similar in spirit to the present version, but may\par -differ in detail to address new problems or concerns.\par -\par - Each version is given a distinguishing version number. If the\par -Library as you received it specifies that a certain numbered version\par -of the GNU Lesser General Public License "or any later version"\par -applies to it, you have the option of following the terms and\par -conditions either of that published version or of any later version\par -published by the Free Software Foundation. If the Library as you\par -received it does not specify a version number of the GNU Lesser\par -General Public License, you may choose any version of the GNU Lesser\par -General Public License ever published by the Free Software Foundation.\par -\par - If the Library as you received it specifies that a proxy can decide\par -whether future versions of the GNU Lesser General Public License shall\par -apply, that proxy's public statement of acceptance of any version is\par -permanent authorization for you to choose that version for the\par -Library.\par -\par -} - \ No newline at end of file diff --git a/project/beagle-xcode/beagle-package.pmdoc/index.xml b/project/beagle-xcode/beagle-package.pmdoc/index.xml deleted file mode 100644 index 5ef7a4c6a..000000000 --- a/project/beagle-xcode/beagle-package.pmdoc/index.xml +++ /dev/null @@ -1,106 +0,0 @@ -BEAGLE v2.1.2/Users/ayres/developer/hmsbeagle/project/beagle-xcode/BEAGLE-2.1.2.pkghms.beagle-libbeagle-icon.png\ -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\ -This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.\ -\pard\pardeftab720\sl540 - -\b\fs36 \cf2 0. Additional Definitions.\ -\pard\pardeftab720\sl360\sa280 - -\b0\fs28 \cf2 As used herein, \'93this License\'94 refers to version 3 of the GNU Lesser General Public License, and the \'93GNU GPL\'94 refers to version 3 of the GNU General Public License.\ -\'93The Library\'94 refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.\ -An \'93Application\'94 is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.\ -A \'93Combined Work\'94 is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the \'93Linked Version\'94.\ -The \'93Minimal Corresponding Source\'94 for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.\ -The \'93Corresponding Application Code\'94 for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.\ -\pard\pardeftab720\sl540 - -\b\fs36 \cf2 1. Exception to Section 3 of the GNU GPL.\ -\pard\pardeftab720\sl360\sa280 - -\b0\fs28 \cf2 You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.\ -\pard\pardeftab720\sl540 - -\b\fs36 \cf2 2. Conveying Modified Versions.\ -\pard\pardeftab720\sl360\sa280 - -\b0\fs28 \cf2 If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:\ -\pard\tx220\tx720\pardeftab720\li720\fi-720\sl360 -\ls1\ilvl0\cf2 {\listtext \uc0\u9642 }a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or\ -{\listtext \uc0\u9642 }b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.\ -\pard\pardeftab720\sl540 - -\b\fs36 \cf2 3. Object Code Incorporating Material from Library Header Files.\ -\pard\pardeftab720\sl360\sa280 - -\b0\fs28 \cf2 The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:\ -\pard\tx220\tx720\pardeftab720\li720\fi-720\sl360 -\ls2\ilvl0\cf2 {\listtext \uc0\u9642 }a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.\ -{\listtext \uc0\u9642 }b) Accompany the object code with a copy of the GNU GPL and this license document.\ -\pard\pardeftab720\sl540 - -\b\fs36 \cf2 4. Combined Works.\ -\pard\pardeftab720\sl360\sa280 - -\b0\fs28 \cf2 You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:\ -\pard\tx220\tx720\pardeftab720\li720\fi-720\sl360 -\ls3\ilvl0\cf2 {\listtext \uc0\u9642 }a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.\ -{\listtext \uc0\u9642 }b) Accompany the Combined Work with a copy of the GNU GPL and this license document.\ -{\listtext \uc0\u9642 }c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.\ -{\listtext \uc0\u9642 }d) Do one of the following:\ -\pard\tx940\tx1440\pardeftab720\li1440\fi-1440\sl360 -\ls3\ilvl1\cf2 {\listtext \uc0\u9642 }0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.\ -{\listtext \uc0\u9642 }1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.\ -\pard\tx220\tx720\pardeftab720\li720\fi-720\sl360 -\ls3\ilvl0\cf2 {\listtext \uc0\u9642 }e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)\ -\pard\pardeftab720\sl540 - -\b\fs36 \cf2 5. Combined Libraries.\ -\pard\pardeftab720\sl360\sa280 - -\b0\fs28 \cf2 You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:\ -\pard\tx220\tx720\pardeftab720\li720\fi-720\sl360 -\ls4\ilvl0\cf2 {\listtext \uc0\u9642 }a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.\ -{\listtext \uc0\u9642 }b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.\ -\pard\pardeftab720\sl540 - -\b\fs36 \cf2 6. Revised Versions of the GNU Lesser General Public License.\ -\pard\pardeftab720\sl360\sa280 - -\b0\fs28 \cf2 The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\ -Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License \'93or any later version\'94 applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.\ -If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.}]]>01libhmsbeagle.xml02libhmsbeagle.xml03libhmsbeagle.xml04libhmsbeagle.xml05libhmsbeagle.xml06libhmsbeagle.xml07libhmsbeagle.xml08libhmsbeagle.xmlproperties.titleproperties.customizeOptionproperties.anywhereDomainproperties.systemDomain \ No newline at end of file diff --git a/tests/basta/CMakeLists.txt b/tests/basta/CMakeLists.txt new file mode 100644 index 000000000..1f15b48ed --- /dev/null +++ b/tests/basta/CMakeLists.txt @@ -0,0 +1,26 @@ +include_directories( + ${CUDA_INCLUDE_DIRS} +) + +link_directories(${CUDA_TOOLKIT_ROOT_DIR}/lib + ${CUDA_TOOLKIT_ROOT_DIR}/lib/x64 + ${CUDA_TOOLKIT_ROOT_DIR}/lib64 +) + +enable_language("CUDA") + +set(STATE_SIZE 16) + +set(BASTA_TEST_NAME "test_updateInnerBastaPartials_${STATE_SIZE}") +add_executable(${BASTA_TEST_NAME} test_x_state_updateInnerBastaPartials.cu) +target_compile_definitions( ${BASTA_TEST_NAME} PRIVATE STATE_SIZE=${STATE_SIZE} ) +target_compile_options(${BASTA_TEST_NAME} PRIVATE + $<$: + -I/usr/local/cuda/include; + -lineinfo + > +) +target_link_libraries(${BASTA_TEST_NAME} cuda) +set_source_files_properties(test_x_state_updateInnerBastaPartials.cu PROPERTIES LANGUAGE CUDA) + +add_dependencies(${BASTA_TEST_NAME} CudaKernels) \ No newline at end of file diff --git a/tests/basta/test_x_state_updateInnerBastaPartials.cu b/tests/basta/test_x_state_updateInnerBastaPartials.cu new file mode 100644 index 000000000..d6c3f6798 --- /dev/null +++ b/tests/basta/test_x_state_updateInnerBastaPartials.cu @@ -0,0 +1,224 @@ +// +// Created by gkarthik on 4/20/24. +// + +#include +#include +#include +#include +#include + +#define NPATTERNS 1 + +#define CONCAT(a, b) CONCAT_INNER(a, b) +#define CONCAT_INNER(a, b) a ## _ ## b + +#define GET_VAR_NAME(VAR) CONCAT(VAR, STATE_SIZE) + +#define KERNEL_STRING CONCAT(KERNELS_STRING_DP, STATE_SIZE) + + +double partials1Host_16[] = {0.137572756735608, 0.477254124591127, 0.428745979443192, 0.218426858074963, 0.529428300447762, 0.110051316907629, 0.000466231256723404, 0.912552231224254, 0.472219149814919, 0.928942704107612, 0.560180699685588, 0.217537123244256, 0.697977353585884, 0.623952043708414, 0.675538737559691, 0.843222103314474}; +double partials2Host_16[] = {0.828149347100407, 0.864858906250447, 0.350309345172718, 0.155412578489631, 0.571178458165377, 0.0642696765717119, 0.767122565768659, 0.989166378509253, 0.807592692552134, 0.629633222240955, 0.759149922290817, 0.947871233569458, 0.514384098816663, 0.985400719335303, 0.437582379207015, 0.961291362997144}; +double matrices_16[] = {0.318755098618567, 0.740407602395862, 0.874102377332747, 0.690571578918025, 0.701961038634181, 0.795170336496085, 0.348821813939139, 0.719763568369672, 0.895593842957169, 0.0806103076320142, 0.0329403523355722, 0.594381110742688, 0.359542798716575, 0.0881143372971565, 0.649336193455383, 0.699423802085221, 0.194982040207833, 0.0281000500544906, 0.771264882525429, 0.364646208938211, 0.0918229892849922, 0.936870703473687, 0.37309667118825, 0.0921725274529308, 0.159810511628166, 0.626376076601446, 0.692677799146622, 0.207317036110908, 0.970800938550383, 0.101070829667151, 0.944739747559652, 0.842726089060307, 0.207157449331135, 0.9937439779751, 0.821067644748837, 0.698300351854414, 0.782907243119553, 0.973109148675576, 0.77274006837979, 0.618896092521027, 0.300635955762118, 0.499129123752937, 0.656451256712899, 0.900395354721695, 0.56438325252384, 0.860600786982104, 0.49170877225697, 0.889088666066527, 0.0156871858052909, 0.81213018624112, 0.977085781516507, 0.295148188248277, 0.726798894582316, 0.916058843955398, 0.608332335250452, 0.93036122340709, 0.740293311886489, 0.477501145098358, 0.528508115326986, 0.359984828624874, 0.115733818151057, 0.162383440183476, 0.599637272302061, 0.727882955456153, 0.674989679362625, 0.862724364968017, 0.736116931773722, 0.934994351351634, 0.225678282091394, 0.0690643971320242, 0.642801651265472, 0.0847296256106347, 0.11830615834333, 0.203358805505559, 0.326086097629741, 0.730495651019737, 0.29963503475301, 0.561327135190368, 0.0538779601920396, 0.904581440845504, 0.807041098363698, 0.0369221286382526, 0.676678945310414, 0.814023691928014, 0.651314357761294, 0.901343589415774, 0.429449937539175, 0.628918903879821, 0.0323536104988307, 0.718082484090701, 0.4828297609929, 0.284520726883784, 0.997801034012809, 0.577156581915915, 0.48068075068295, 0.720765815814957, 0.403965384466574, 0.170624090125784, 0.876439346699044, 0.593427885789424, 0.769376888172701, 0.647851618006825, 0.337206641677767, 0.408452160190791, 0.0607802064623684, 0.676360174780712, 0.462037036195397, 0.347813759464771, 0.946434140671045, 0.604583449661732, 0.742167289135978, 0.0429284807760268, 0.626676751766354, 0.64561746106483, 0.673989933682606, 0.662993856705725, 0.856125113321468, 0.870688743656501, 0.308341189753264, 0.538020107662305, 0.538775310153142, 0.258829150116071, 0.407576418248937, 0.0590927223674953, 0.520942375296727, 0.434115749085322, 0.340059822658077, 0.17571780225262, 0.53029696107842, 0.975732607766986, 0.831993991043419, 0.983791405102238, 0.55990690854378, 0.710094312205911, 0.0787766603752971, 0.589558490784839, 0.673550385283306, 0.673261155607179, 0.974599071079865, 0.340651801321656, 0.0923955119214952, 0.194945273222402, 0.141258440678939, 0.639831262873486, 0.339301661355421, 0.884930776199326, 0.289516024757177, 0.126225155545399, 0.446420934982598, 0.0850053902249783, 0.395572019508108, 0.157721624244004, 0.929064428433776, 0.875803815200925, 0.36426582490094, 0.161793374456465, 0.387928539188579, 0.59461420099251, 0.174750925740227, 0.115827345522121, 0.152487984858453, 0.035088024334982, 0.983126569306478, 0.575697488617152, 0.209149486385286, 0.201207815203816, 0.110956045333296, 0.0174690247513354, 0.775130218127742, 0.497412796830758, 0.443602121900767, 0.0095906644128263, 0.198237520409748, 0.304748482536525, 0.518023134209216, 0.547018625540659, 0.526118801673874, 0.493327406002209, 0.913669281871989, 0.077805265551433, 0.929841819219291, 0.29471311555244, 0.118532110471278, 0.14501806977205, 0.436429607449099, 0.205097107682377, 0.708817657083273, 0.452689809259027, 0.0368115562014282, 0.239382016705349, 0.471294831018895, 0.290052818134427, 0.141418197192252, 0.406050314893946, 0.123278650688007, 0.793885040329769, 0.803798166336492, 0.653874792391434, 0.570221147732809, 0.238239917438477, 0.29717841069214, 0.753295891918242, 0.86618359782733, 0.0173538792878389, 0.262981676263735, 0.870678049977869, 0.235948005225509, 0.518082186812535, 0.80484891217202, 0.0546407853253186, 0.849502737633884, 0.749514716677368, 0.744097977643833, 0.543421939015388, 0.416765965521336, 0.725398944690824, 0.33459063549526, 0.478168275207281, 0.308823636500165, 0.518112531863153, 0.0382656576111913, 0.569260101066902, 0.542835577391088, 0.786958181066439, 0.191143112257123, 0.756994087249041, 0.930127918720245, 0.0538773911539465, 0.108583583729342, 0.0136260520666838, 0.0493806877639145, 0.0609419206157327, 0.157695269677788, 0.351834069937468, 0.396392825525254, 0.179786366643384, 0.822698512114584, 0.391177944373339, 0.0950508427340537, 0.0245800712145865, 0.28290240559727, 0.772152968682349, 0.14831333537586, 0.672689846949652, 0.826513405656442, 0.395902422023937, 0.837914811447263, 0.927084936527535, 0.0562630859203637, 0.810627286788076, 0.67597354692407, 0.622439709492028, 0.0950460624881089, 0.0380097457673401, 0.166366128250957, 0.867308233864605}; +// double expectedPartials_16[] = {12.9769783870594, 25.8647148645348, 37.1028089862958, 26.553395775949, 28.2498807522581, 21.9503211762829, 12.9202534609119, 13.9146869398328, 14.9317655768219, 22.3371483393775, 22.9624904769671, 9.58813665982792, 11.4421566478761, 13.2079833456249, 11.7415865195237, 23.4516262593406}; +// double sizes_16[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; +double expectedPartials_16[] = {0.0305735894520103, 0.0609369261453154, 0.0437068636330068, 0.0417062995096076, 0.133112690863239, 0.103429332771742, 0.0608798925524519, 0.0655656368012336, 0.0703580844358418, 0.105252052132227, 0.10819864774354, 0.0451790463240147, 0.0539151394667653, 0.0311178340792188, 0.018442015033903, 0.0276258606529718}; +double expectedPartials0_16[] = {2.98143795102797, 4.65854349159416, 4.91424944421801, 4.36942401534397, 4.40172642450781, 3.8340440457869, 3.24990363502535, 3.1248633106177, 3.32838756850764, 4.25163890981238, 4.16627182696517, 2.51423509758302, 2.89070331372981, 3.34836030429601, 2.60373247077971, 4.13703860672182}; +double expectedPartials1_16[] = {4.35259046145336, 5.55210333684872, 7.55004592409327, 6.07709292636792, 6.4179092537349, 5.72510928777757, 3.97558048234593, 4.45289459303814, 4.48618595926221, 5.25377361840994, 5.51151999453036, 3.8135402170804, 3.95826046676252, 3.94461233119948, 4.50952110145465, 5.66869891454158}; +double sizes_16[] = {2, 2, 4, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4}; +double coalescent_16[] = {2}; + + +//double partials1Host_4[] = {1, 0, 0, 0}; +//double partials2Host_4[] = {0, 0, 1, 0}; +//double matrices_4[] = {0.9974538211778671, 5.991008993253103E-4, 0.0010484265738193166, 8.986513489883663E-4, 4.493256744940543E-4, 0.9976035964026984, 0.0010484265738197607, 8.986513489877002E-4, 4.49325674494082E-4, 5.991008993254314E-4, 0.9980529220771925, 8.986513489880332E-4, 4.49325674494082E-4, 5.991008993254456E-4, 0.0010484265738197607, 0.9979031468523611}; +//double sizes_4[] = {2, 2, 4, 3}; +//double expectedPartials_4[] = {0.8229333698706953, 3.7070898284225927E-4, 0.1764487818245675, 2.4713932189485474E-4}; +//double expectedPartials0_4[] = {0.9974538211778671, 4.493256744940543E-4, 4.49325674494082E-4, 4.49325674494082E-4}; +//double expectedPartials1_4[] = {0.0010484265738193166, 0.0010484265738197607, 0.9980529220771925, 0.0010484265738197607}; +double expectedProb_16[] = {212.2253}; + +int main() { + char functionName[] = "kernelInnerBastaPartialsCoalescent"; + CUmodule cudaModule; + CUresult res; + cudaError_t err; + + cuInit(0); + + int numDevices; + cuDeviceGetCount(&numDevices); + std::cout << "Number of devices " << numDevices << std::endl; + + CUdevice cuDevice; + res = cuDeviceGet(&cuDevice, 0); + + CUcontext context; + res = cuCtxCreate(&context, 0, cuDevice); + + res = cuModuleLoadData(&cudaModule, KERNEL_STRING); + + CUfunction cudaFunction; + + res = cuModuleGetFunction(&cudaFunction, cudaModule, functionName); + + if(res != CUDA_SUCCESS) { + std::cerr << "Error loading function " << functionName < tolerance) { + if(pass == 0) + std::cerr << "Unequal values at positions " << std::endl; + pass = -1; + std::cerr << i << " Expected: " << GET_VAR_NAME(expectedPartials)[i] << " Observed: " << resHost[i] << std::endl; + } + } + + if(pass != 0) + std::cerr << std::endl << std::endl; + + if(pass == 0) { + std::cerr << "PASS: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } else { + std::cerr << "FAIL: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } + + int pass0 = 0; + for(int i = 0; i < STATE_SIZE; i++){ + if(abs(GET_VAR_NAME(expectedPartials0)[i] - accumHost1[i]) > tolerance) { + if(pass0 == 0) + std::cerr << "Unequal values at positions " << std::endl; + pass0 = -1; + std::cerr << i << " Expected: " << GET_VAR_NAME(expectedPartials0)[i] << " Observed: " << accumHost1[i] << std::endl; + } + } + + if(pass0 != 0) + std::cerr << std::endl << std::endl; + + if(pass0 == 0) { + std::cerr << "PASS0: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } else { + std::cerr << "FAIL0: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } + + + int pass1 = 0; + for(int i = 0; i < STATE_SIZE; i++){ + if(abs(GET_VAR_NAME(expectedPartials1)[i] - accumHost2[i]) > tolerance) { + if(pass1 == 0) + std::cerr << "Unequal values at positions " << std::endl; + pass1 = -1; + std::cerr << i << " Expected: " << GET_VAR_NAME(expectedPartials1)[i] << " Observed: " << accumHost2[i] << std::endl; + } + } + + if(pass1 != 0) + std::cerr << std::endl << std::endl; + + if(pass1 == 0) { + std::cerr << "PASS1: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } else { + std::cerr << "FAIL1: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } + + + int pass2 = 0; + for(int i = 0; i < intervalNumber; i++){ + if(abs(GET_VAR_NAME(expectedProb)[i] - coal[i]) > tolerance) { + if(pass2 == 0) + std::cerr << "Unequal values at positions " << std::endl; + pass2 = -1; + std::cerr << i << " Expected: " << GET_VAR_NAME(expectedProb)[i] << " Observed: " << coal[i] << std::endl; + } + } + + if(pass2 != 0) + std::cerr << std::endl << std::endl; + + if(pass2 == 0) { + std::cerr << "PASS2: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } else { + std::cerr << "FAIL2: Test for post-order kernel for state size " << STATE_SIZE << std::endl; + } + + cuModuleUnload(cudaModule); + + cudaFree(matrices1); + cudaFree(matrices2); + cudaFree(partials1); + cudaFree(partials2); + cudaFree(partials3); + cudaFree(accumulation1); + cudaFree(accumulation2); + cudaFree(sizes); + cudaFree(coalescent); + free(resHost); + free(accumHost1); + free(accumHost2); + free(coal); + + return pass; +} \ No newline at end of file