[llvm] [orc-rt] Implement Windows target triple detection (PR #224514)
Jared Wyles via llvm-commits
llvm-commits at lists.llvm.org
Thu Sep 17 22:01:07 PDT 2026
https://github.com/jaredwy created https://github.com/llvm/llvm-project/pull/224514
Adds Windows target triple detection for ORC-RT.
Currently supports x86-64 MSVC targets only. ARM64 will be added once tested on that platform.
>From f2349aac85061907ebb7e8f9f45633fc82acd1a7 Mon Sep 17 00:00:00 2001
From: Jared Wyles <jared.wyles at gmail.com>
Date: Fri, 18 Sep 2026 13:27:15 +1000
Subject: [PATCH 1/3] [CMake] Do not use llvm-rc without Clang in external
projects
---
llvm/cmake/modules/LLVMExternalProjectUtils.cmake | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/llvm/cmake/modules/LLVMExternalProjectUtils.cmake b/llvm/cmake/modules/LLVMExternalProjectUtils.cmake
index 60a880ace5073..32e25567ef57e 100644
--- a/llvm/cmake/modules/LLVMExternalProjectUtils.cmake
+++ b/llvm/cmake/modules/LLVMExternalProjectUtils.cmake
@@ -290,8 +290,8 @@ function(llvm_ExternalProject_Add name source_dir)
if(llvm-mt IN_LIST TOOLCHAIN_TOOLS AND is_msvc_target)
list(APPEND compiler_args -DCMAKE_MT=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-mt${CMAKE_EXECUTABLE_SUFFIX})
endif()
- if(llvm-rc IN_LIST TOOLCHAIN_TOOLS AND is_msvc_target)
- list(APPEND compiler_args -DCMAKE_RC_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-rc${CMAKE_EXECUTABLE_SUFFIX})
+ if(llvm-rc IN_LIST TOOLCHAIN_TOOLS AND is_msvc_target AND CLANG_IN_TOOLCHAIN)
+ list(APPEND compiler_args -DCMAKE_RC_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-rc${CMAKE_EXECUTABLE_SUFFIX})
endif()
list(APPEND ARG_DEPENDS ${TOOLCHAIN_TOOLS})
# Add LLVMgold.so dependency if it is available, as clang may need it for
>From c8c3aba22ae2841e0bceb3f4e0ca8ead9176de47 Mon Sep 17 00:00:00 2001
From: Jared Wyles <jared.wyles at gmail.com>
Date: Fri, 18 Sep 2026 14:46:56 +1000
Subject: [PATCH 2/3] [orc-rt] Enable MSVC for orc-rt
---
orc-rt/CMakeLists.txt | 354 ++--
orc-rt/include/orc-rt-c/support/Compiler.h | 302 ++--
.../orc-rt-internal/tools/OptionParser.h | 542 +++---
orc-rt/include/orc-rt/support/BitmaskEnum.h | 361 ++--
orc-rt/include/orc-rt/support/Error.h | 1454 ++++++++---------
.../include/orc-rt/support/ExecutorAddress.h | 466 +++---
orc-rt/include/orc-rt/support/bit.h | 355 ++--
orc-rt/lib/bedrock/CMakeLists.txt | 215 ++-
orc-rt/lib/bedrock/sps/AllSPSCI.cpp | 81 +-
.../bedrock/sys/windows/DynamicLibrary.cpp | 30 +
orc-rt/lib/bedrock/sys/windows/Memory.cpp | 29 +
orc-rt/test/unit/CMakeLists.txt | 299 ++--
.../unit/Inputs/RTTICrossDylibTestLib.cpp | 66 +-
.../unit/bedrock/ExecutorProcessInfoTest.cpp | 100 +-
.../unit/bedrock/NativeDylibManagerTest.cpp | 399 ++---
.../bedrock/SimpleNativeMemoryMapTest.cpp | 650 ++++----
.../sps/NativeDylibManagerSPSCITest.cpp | 475 +++---
.../sps/SimpleNativeMemoryMapSPSCITest.cpp | 647 ++++----
.../unit/bedrock/sps/SimpleRemoteCATest.cpp | 573 +++----
.../unit/bedrock/sys/TargetTripleTest.cpp | 116 +-
orc-rt/test/unit/support/BitmaskEnumTest.cpp | 316 ++--
.../unit/support/CallableTraitsHelperTest.cpp | 410 +++--
orc-rt/test/unit/support/bit-test.cpp | 475 +++---
orc-rt/test/unit/tools/OptionParserTest.cpp | 331 ++--
24 files changed, 4600 insertions(+), 4446 deletions(-)
create mode 100644 orc-rt/lib/bedrock/sys/windows/DynamicLibrary.cpp
create mode 100644 orc-rt/lib/bedrock/sys/windows/Memory.cpp
diff --git a/orc-rt/CMakeLists.txt b/orc-rt/CMakeLists.txt
index 75050fd2802fc..016b322c37c8e 100644
--- a/orc-rt/CMakeLists.txt
+++ b/orc-rt/CMakeLists.txt
@@ -1,165 +1,189 @@
-# CMake build for ORC-RT.
-
-#===============================================================================
-# Setup Project
-#===============================================================================
-
-cmake_minimum_required(VERSION 3.20.0)
-if("${CMAKE_VERSION}" VERSION_LESS "3.31.0")
- message(WARNING
- "Your CMake version is ${CMAKE_VERSION}. Starting with LLVM 24, the "
- "minimum version of CMake required to build LLVM will become 3.31.0, and "
- "using an older CMake will become an error. Please upgrade your CMake to "
- "at least 3.31.0 now to avoid issues in the future.")
-endif()
-
-set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
-include(${LLVM_COMMON_CMAKE_UTILS}/Modules/CMakePolicy.cmake
- NO_POLICY_SCOPE)
-
-project(OrcRT LANGUAGES C CXX ASM)
-
-list(INSERT CMAKE_MODULE_PATH 0
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake"
- "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
- "${CMAKE_CURRENT_SOURCE_DIR}/../runtimes/cmake/Modules"
- "${LLVM_COMMON_CMAKE_UTILS}"
- "${LLVM_COMMON_CMAKE_UTILS}/Modules"
- )
-
-include(GNUInstallDirs)
-
-# --- C++ standard ---
-set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard to conform to")
-set(CMAKE_CXX_STANDARD_REQUIRED YES)
-set(CMAKE_CXX_EXTENSIONS NO)
-
-# --- C standard ---
-set(CMAKE_C_STANDARD 11 CACHE STRING "C standard to conform to")
-set(CMAKE_C_STANDARD_REQUIRED YES)
-set(CMAKE_C_EXTENSIONS NO)
-
-# --- Project variables ---
-set(CMAKE_FOLDER "orc-rt")
-set(ORC_RT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
-set(ORC_RT_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})
-
-#===============================================================================
-# Setup CMake Options
-#===============================================================================
-
-# --- Build components ---
-option(ORC_RT_INCLUDE_DOCS "Build the ORC-RT documentation." ON)
-option(ORC_RT_INCLUDE_TESTS "Build ORC-RT tests." ${LLVM_INCLUDE_TESTS})
-
-# --- Build behavior ---
-option(ORC_RT_ENABLE_ASSERTIONS "Enable assertions independent of build mode." ON)
-option(ORC_RT_ENABLE_PEDANTIC "Compile with pedantic enabled." ON)
-option(ORC_RT_ENABLE_WERROR "Fail and stop if a warning is triggered." OFF)
-
-option(ORC_RT_ENABLE_PIC "Build position-independent code." ON)
-if(NOT ORC_RT_ENABLE_PIC AND
- "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS} ${CMAKE_ASM_FLAGS}" MATCHES "-fPIC")
- message(WARNING
- "ORC_RT_ENABLE_PIC is OFF, but -fPIC is already in CMAKE_C_FLAGS, "
- "CMAKE_CXX_FLAGS or CMAKE_ASM_FLAGS, so the build will still be "
- "position-independent.")
-endif()
-
-# --- Bedrock Library Type: SHARED / STATIC ---
-set(orc_rt_bedrock_library_types SHARED STATIC)
-set(ORC_RT_BEDROCK_LIBRARY_TYPE "STATIC" CACHE STRING
- "Build Bedrock as SHARED or STATIC")
-set_property(CACHE ORC_RT_BEDROCK_LIBRARY_TYPE PROPERTY STRINGS
- ${orc_rt_bedrock_library_types})
-string(TOUPPER "${ORC_RT_BEDROCK_LIBRARY_TYPE}" ORC_RT_BEDROCK_LIBRARY_TYPE)
-if(NOT ORC_RT_BEDROCK_LIBRARY_TYPE IN_LIST orc_rt_bedrock_library_types)
- message(FATAL_ERROR "ORC_RT_BEDROCK_LIBRARY_TYPE must be one of: "
- "${orc_rt_bedrock_library_types}")
-endif()
-if(ORC_RT_BEDROCK_LIBRARY_TYPE STREQUAL "SHARED" AND NOT ORC_RT_ENABLE_PIC)
- message(WARNING
- "ORC_RT_BEDROCK_LIBRARY_TYPE is SHARED, but ORC_RT_ENABLE_PIC is OFF.")
-endif()
-
-# --- Language runtime (RTTI / exceptions) ---
-option(ORC_RT_ENABLE_RTTI "Enable RTTI." ON)
-option(ORC_RT_ENABLE_EXCEPTIONS "Enable exceptions." ON)
-
-# Derive the compile flags implied by the language-runtime options.
-set(ORC_RT_COMPILE_FLAGS)
-if(ORC_RT_ENABLE_RTTI)
- list(APPEND ORC_RT_COMPILE_FLAGS -frtti)
-else()
- list(APPEND ORC_RT_COMPILE_FLAGS -fno-rtti)
-endif()
-
-if(ORC_RT_ENABLE_EXCEPTIONS)
- list(APPEND ORC_RT_COMPILE_FLAGS -fexceptions)
-else()
- list(APPEND ORC_RT_COMPILE_FLAGS -fno-exceptions)
-endif()
-
-# --- Logging ---
-# User-settable options (everything below them is validation and derivation):
-# ORC_RT_LOG_BACKEND none (default) | printf | os_log
-# ORC_RT_LOG_LEVEL error | warning | info (default) | debug
-set(orc_rt_log_level_default "info")
-set(ORC_RT_LOG_LEVEL "${orc_rt_log_level_default}" CACHE STRING
- "Lowest log level compiled in: error, warning, info, or debug")
-set(orc_rt_log_levels error warning info debug)
-set_property(CACHE ORC_RT_LOG_LEVEL PROPERTY STRINGS ${orc_rt_log_levels})
-
-set(ORC_RT_LOG_BACKEND "none" CACHE STRING
- "ORC-RT logging backend: none, printf, os_log")
-set(orc_rt_log_backends none printf os_log)
-set_property(CACHE ORC_RT_LOG_BACKEND PROPERTY STRINGS ${orc_rt_log_backends})
-
-# Validate the level and derive its config.h macro symbol.
-if(NOT ORC_RT_LOG_LEVEL IN_LIST orc_rt_log_levels)
- message(FATAL_ERROR "ORC_RT_LOG_LEVEL must be one of: ${orc_rt_log_levels}")
-endif()
-string(TOUPPER "ORC_RT_LOG_LEVEL_${ORC_RT_LOG_LEVEL}" ORC_RT_LOG_LEVEL_VALUE)
-
-# Validate the backend (os_log is Apple-only) and derive its config.h macro symbol.
-if(NOT ORC_RT_LOG_BACKEND IN_LIST orc_rt_log_backends)
- message(FATAL_ERROR "ORC_RT_LOG_BACKEND must be one of: ${orc_rt_log_backends}")
-endif()
-if(ORC_RT_LOG_BACKEND STREQUAL "os_log" AND NOT APPLE)
- message(FATAL_ERROR "ORC_RT_LOG_BACKEND=os_log is only supported on Apple platforms.")
-endif()
-string(TOUPPER "ORC_RT_LOG_BACKEND_${ORC_RT_LOG_BACKEND}" ORC_RT_LOG_BACKEND_VALUE)
-
-# The "none" backend compiles all logging out, so the level has no effect. Warn
-# if the user picked a non-default level under it, as their choice is ignored.
-if(ORC_RT_LOG_BACKEND STREQUAL "none" AND
- NOT ORC_RT_LOG_LEVEL STREQUAL orc_rt_log_level_default)
- message(WARNING
- "ORC_RT_LOG_LEVEL is set to '${ORC_RT_LOG_LEVEL}', but ORC_RT_LOG_BACKEND is "
- "'none', so no logging is compiled in and the level has no effect. Select a "
- "backend (printf or os_log) to enable logging.")
-endif()
-
-# --- Generated config header ---
-# Keep this last in the section so it captures every value derived above.
-configure_file(
- ${CMAKE_CURRENT_SOURCE_DIR}/include/orc-rt-c/config.h.in
- ${CMAKE_CURRENT_BINARY_DIR}/include/orc-rt-c/config.h
- @ONLY
-)
-
-#===============================================================================
-# Setup Source Code
-#===============================================================================
-
-if (ORC_RT_INCLUDE_DOCS)
- add_subdirectory(docs)
-endif()
-
-add_subdirectory(include)
-add_subdirectory(lib)
-add_subdirectory(tools)
-
-if(ORC_RT_INCLUDE_TESTS)
- add_subdirectory(test)
-endif()
+# CMake build for ORC-RT.
+
+#===============================================================================
+# Setup Project
+#===============================================================================
+
+cmake_minimum_required(VERSION 3.20.0)
+if("${CMAKE_VERSION}" VERSION_LESS "3.31.0")
+ message(WARNING
+ "Your CMake version is ${CMAKE_VERSION}. Starting with LLVM 24, the "
+ "minimum version of CMake required to build LLVM will become 3.31.0, and "
+ "using an older CMake will become an error. Please upgrade your CMake to "
+ "at least 3.31.0 now to avoid issues in the future.")
+endif()
+
+set(LLVM_COMMON_CMAKE_UTILS ${CMAKE_CURRENT_SOURCE_DIR}/../cmake)
+include(${LLVM_COMMON_CMAKE_UTILS}/Modules/CMakePolicy.cmake
+ NO_POLICY_SCOPE)
+
+project(OrcRT LANGUAGES C CXX ASM)
+
+list(INSERT CMAKE_MODULE_PATH 0
+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake"
+ "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules"
+ "${CMAKE_CURRENT_SOURCE_DIR}/../runtimes/cmake/Modules"
+ "${LLVM_COMMON_CMAKE_UTILS}"
+ "${LLVM_COMMON_CMAKE_UTILS}/Modules"
+ )
+
+include(GNUInstallDirs)
+
+# --- C++ standard ---
+set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard to conform to")
+set(CMAKE_CXX_STANDARD_REQUIRED YES)
+set(CMAKE_CXX_EXTENSIONS NO)
+
+# --- C standard ---
+set(CMAKE_C_STANDARD 11 CACHE STRING "C standard to conform to")
+set(CMAKE_C_STANDARD_REQUIRED YES)
+set(CMAKE_C_EXTENSIONS NO)
+
+# --- Project variables ---
+set(CMAKE_FOLDER "orc-rt")
+set(ORC_RT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
+set(ORC_RT_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR})
+
+#===============================================================================
+# Setup CMake Options
+#===============================================================================
+
+# --- Build components ---
+option(ORC_RT_INCLUDE_DOCS "Build the ORC-RT documentation." ON)
+option(ORC_RT_INCLUDE_TESTS "Build ORC-RT tests." ${LLVM_INCLUDE_TESTS})
+
+# --- Build behavior ---
+option(ORC_RT_ENABLE_ASSERTIONS "Enable assertions independent of build mode." ON)
+option(ORC_RT_ENABLE_PEDANTIC "Compile with pedantic enabled." ON)
+option(ORC_RT_ENABLE_WERROR "Fail and stop if a warning is triggered." OFF)
+
+option(ORC_RT_ENABLE_PIC "Build position-independent code." ON)
+if(NOT ORC_RT_ENABLE_PIC AND
+ "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS} ${CMAKE_ASM_FLAGS}" MATCHES "-fPIC")
+ message(WARNING
+ "ORC_RT_ENABLE_PIC is OFF, but -fPIC is already in CMAKE_C_FLAGS, "
+ "CMAKE_CXX_FLAGS or CMAKE_ASM_FLAGS, so the build will still be "
+ "position-independent.")
+endif()
+
+# --- Bedrock Library Type: SHARED / STATIC ---
+set(orc_rt_bedrock_library_types SHARED STATIC)
+set(ORC_RT_BEDROCK_LIBRARY_TYPE "STATIC" CACHE STRING
+ "Build Bedrock as SHARED or STATIC")
+set_property(CACHE ORC_RT_BEDROCK_LIBRARY_TYPE PROPERTY STRINGS
+ ${orc_rt_bedrock_library_types})
+string(TOUPPER "${ORC_RT_BEDROCK_LIBRARY_TYPE}" ORC_RT_BEDROCK_LIBRARY_TYPE)
+if(NOT ORC_RT_BEDROCK_LIBRARY_TYPE IN_LIST orc_rt_bedrock_library_types)
+ message(FATAL_ERROR "ORC_RT_BEDROCK_LIBRARY_TYPE must be one of: "
+ "${orc_rt_bedrock_library_types}")
+endif()
+if(ORC_RT_BEDROCK_LIBRARY_TYPE STREQUAL "SHARED" AND NOT ORC_RT_ENABLE_PIC)
+ message(WARNING
+ "ORC_RT_BEDROCK_LIBRARY_TYPE is SHARED, but ORC_RT_ENABLE_PIC is OFF.")
+endif()
+
+# --- Language runtime (RTTI / exceptions) ---
+option(ORC_RT_ENABLE_RTTI "Enable RTTI." ON)
+option(ORC_RT_ENABLE_EXCEPTIONS "Enable exceptions." ON)
+
+# Derive the compile flags implied by the language-runtime options.
+set(ORC_RT_COMPILE_FLAGS)
+if(MSVC OR CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
+ if(ORC_RT_ENABLE_RTTI)
+ list(APPEND ORC_RT_COMPILE_FLAGS /GR)
+ else()
+ list(APPEND ORC_RT_COMPILE_FLAGS /GR-)
+ endif()
+
+ if(ORC_RT_ENABLE_EXCEPTIONS)
+ list(APPEND ORC_RT_COMPILE_FLAGS /EHsc)
+ else()
+ list(APPEND ORC_RT_COMPILE_FLAGS /EHs-c-)
+ endif()
+else()
+ if(ORC_RT_ENABLE_RTTI)
+ list(APPEND ORC_RT_COMPILE_FLAGS -frtti)
+ else()
+ list(APPEND ORC_RT_COMPILE_FLAGS -fno-rtti)
+ endif()
+
+ if(ORC_RT_ENABLE_EXCEPTIONS)
+ list(APPEND ORC_RT_COMPILE_FLAGS -fexceptions)
+ else()
+ list(APPEND ORC_RT_COMPILE_FLAGS -fno-exceptions)
+ endif()
+endif()
+
+# --- Logging ---
+# User-settable options (everything below them is validation and derivation):
+# ORC_RT_LOG_BACKEND none (default) | printf | os_log
+# ORC_RT_LOG_LEVEL error | warning | info (default) | debug
+set(orc_rt_log_level_default "info")
+set(ORC_RT_LOG_LEVEL "${orc_rt_log_level_default}" CACHE STRING
+ "Lowest log level compiled in: error, warning, info, or debug")
+set(orc_rt_log_levels error warning info debug)
+set_property(CACHE ORC_RT_LOG_LEVEL PROPERTY STRINGS ${orc_rt_log_levels})
+
+set(ORC_RT_LOG_BACKEND "none" CACHE STRING
+ "ORC-RT logging backend: none, printf, os_log")
+set(orc_rt_log_backends none printf os_log)
+set_property(CACHE ORC_RT_LOG_BACKEND PROPERTY STRINGS ${orc_rt_log_backends})
+
+# enable project wide windows settings.
+# Mostly to avoid min and max conflicts
+if(WIN32)
+ add_compile_definitions(
+ NOMINMAX
+ WIN32_LEAN_AND_MEAN
+ )
+endif()
+
+
+# Validate the level and derive its config.h macro symbol.
+if(NOT ORC_RT_LOG_LEVEL IN_LIST orc_rt_log_levels)
+ message(FATAL_ERROR "ORC_RT_LOG_LEVEL must be one of: ${orc_rt_log_levels}")
+endif()
+string(TOUPPER "ORC_RT_LOG_LEVEL_${ORC_RT_LOG_LEVEL}" ORC_RT_LOG_LEVEL_VALUE)
+
+# Validate the backend (os_log is Apple-only) and derive its config.h macro symbol.
+if(NOT ORC_RT_LOG_BACKEND IN_LIST orc_rt_log_backends)
+ message(FATAL_ERROR "ORC_RT_LOG_BACKEND must be one of: ${orc_rt_log_backends}")
+endif()
+if(ORC_RT_LOG_BACKEND STREQUAL "os_log" AND NOT APPLE)
+ message(FATAL_ERROR "ORC_RT_LOG_BACKEND=os_log is only supported on Apple platforms.")
+endif()
+string(TOUPPER "ORC_RT_LOG_BACKEND_${ORC_RT_LOG_BACKEND}" ORC_RT_LOG_BACKEND_VALUE)
+
+# The "none" backend compiles all logging out, so the level has no effect. Warn
+# if the user picked a non-default level under it, as their choice is ignored.
+if(ORC_RT_LOG_BACKEND STREQUAL "none" AND
+ NOT ORC_RT_LOG_LEVEL STREQUAL orc_rt_log_level_default)
+ message(WARNING
+ "ORC_RT_LOG_LEVEL is set to '${ORC_RT_LOG_LEVEL}', but ORC_RT_LOG_BACKEND is "
+ "'none', so no logging is compiled in and the level has no effect. Select a "
+ "backend (printf or os_log) to enable logging.")
+endif()
+
+# --- Generated config header ---
+# Keep this last in the section so it captures every value derived above.
+configure_file(
+ ${CMAKE_CURRENT_SOURCE_DIR}/include/orc-rt-c/config.h.in
+ ${CMAKE_CURRENT_BINARY_DIR}/include/orc-rt-c/config.h
+ @ONLY
+)
+
+#===============================================================================
+# Setup Source Code
+#===============================================================================
+
+if (ORC_RT_INCLUDE_DOCS)
+ add_subdirectory(docs)
+endif()
+
+add_subdirectory(include)
+add_subdirectory(lib)
+add_subdirectory(tools)
+
+if(ORC_RT_INCLUDE_TESTS)
+ add_subdirectory(test)
+endif()
diff --git a/orc-rt/include/orc-rt-c/support/Compiler.h b/orc-rt/include/orc-rt-c/support/Compiler.h
index c576a2fd73240..b741b109f8dcd 100644
--- a/orc-rt/include/orc-rt-c/support/Compiler.h
+++ b/orc-rt/include/orc-rt-c/support/Compiler.h
@@ -1,149 +1,153 @@
-/*===-- Compiler.h - Compiler abstractions for the ORC RT C API ---*- C -*-===*\
-|* *|
-|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
-|* Exceptions. *|
-|* See https://llvm.org/LICENSE.txt for license information. *|
-|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
-|* *|
-|*===----------------------------------------------------------------------===*|
-|* *|
-|* Compiler-abstraction macros for the ORC runtime C API, plus the *|
-|* general-purpose ones that are usable from both C and C++. Macros specific *|
-|* to the C++ API live in orc-rt/support/Compiler.h, which includes this *|
-|* header. *|
-|* *|
-|* Some of the macros below were swiped from llvm/Support/Compiler.h. *|
-|* *|
-\*===----------------------------------------------------------------------===*/
-
-#ifndef ORC_RT_C_SUPPORT_COMPILER_H
-#define ORC_RT_C_SUPPORT_COMPILER_H
-
-/* For assert, used by ORC_RT_UNREACHABLE below. */
-#include <assert.h>
-
-/* ORC_RT_HAS_BUILTIN(X) expands to 1 if the compiler provides the builtin X,
- and to 0 otherwise.
-
- This wraps __has_builtin rather than supplying a fallback definition for it.
- __has_builtin is a reserved identifier, and defining one from a public header
- can collide with the compiler's own definition or with other libraries that
- the client also includes. */
-#if defined(__has_builtin)
-#define ORC_RT_HAS_BUILTIN(X) __has_builtin(X)
-#else
-#define ORC_RT_HAS_BUILTIN(X) 0
-#endif
-
-/* Helper to promote strict prototype warnings to errors */
-#ifdef __clang__
-#define ORC_RT_C_STRICT_PROTOTYPES_BEGIN \
- _Pragma("clang diagnostic push") \
- _Pragma("clang diagnostic error \"-Wstrict-prototypes\"")
-#define ORC_RT_C_STRICT_PROTOTYPES_END _Pragma("clang diagnostic pop")
-#else
-#define ORC_RT_C_STRICT_PROTOTYPES_BEGIN
-#define ORC_RT_C_STRICT_PROTOTYPES_END
-#endif
-
-/* Helper to wrap C code for C++ */
-#ifdef __cplusplus
-#define ORC_RT_C_EXTERN_C_BEGIN \
- extern "C" { \
- ORC_RT_C_STRICT_PROTOTYPES_BEGIN
-#define ORC_RT_C_EXTERN_C_END \
- ORC_RT_C_STRICT_PROTOTYPES_END \
- }
-#else
-#define ORC_RT_C_EXTERN_C_BEGIN ORC_RT_C_STRICT_PROTOTYPES_BEGIN
-#define ORC_RT_C_EXTERN_C_END ORC_RT_C_STRICT_PROTOTYPES_END
-#endif
-
-/* ORC_RT_C_EXPORT marks a symbol declared in orc-rt-c as part of the ORC
- runtime's binary interface: exported from the runtime when it is built as a
- shared library, and imported by consumers of that library.
-
- TODO: Add the Windows __declspec(dllexport) / __declspec(dllimport) and
- static-build cases once there is a shared-library build to exercise them. */
-#if defined(__has_attribute) && __has_attribute(visibility)
-#define ORC_RT_C_EXPORT __attribute__((visibility("default")))
-#endif
-
-#if !defined(ORC_RT_C_EXPORT)
-#define ORC_RT_C_EXPORT
-#endif
-
-/* ORC_RT_MAYBE_UNUSED indicates that a symbol may not be used, and that the
- compiler should not issue unused-symbol warnings for it. */
-#if defined(__cplusplus)
-#define ORC_RT_MAYBE_UNUSED [[maybe_unused]]
-#elif defined(__has_attribute) && __has_attribute(unused)
-#define ORC_RT_MAYBE_UNUSED __attribute__((unused))
-#else
-#define ORC_RT_MAYBE_UNUSED
-#endif
-
-/* ORC_RT_C_NOTHROW indicates that a function won't throw a C++ exception. */
-#if defined(__cplusplus)
-#define ORC_RT_C_NOTHROW noexcept
-#elif defined(__GNUC__) || defined(__clang__)
-#define ORC_RT_C_NOTHROW __attribute__((nothrow))
-#else
-#define ORC_RT_C_NOTHROW
-#endif
-
-/* ORC_RT_FORMAT_PRINTF(FmtIdx, FirstArg) marks a function as taking a
- printf-style format string at argument position FmtIdx, with the variadic
- arguments beginning at FirstArg, so the compiler can check the format string
- against its arguments. Indices are 1-based. */
-#if defined(__GNUC__) || defined(__clang__)
-#define ORC_RT_FORMAT_PRINTF(FmtIdx, FirstArg) \
- __attribute__((format(printf, FmtIdx, FirstArg)))
-#else
-#define ORC_RT_FORMAT_PRINTF(FmtIdx, FirstArg)
-#endif
-
-/* ORC_RT_LIKELY(EXPR) / ORC_RT_UNLIKELY(EXPR) hint to the optimizer which way a
- condition is expected to go. */
-#if ORC_RT_HAS_BUILTIN(__builtin_expect)
-#define ORC_RT_LIKELY(EXPR) __builtin_expect(!!(EXPR), 1)
-#define ORC_RT_UNLIKELY(EXPR) __builtin_expect(!!(EXPR), 0)
-#else
-#define ORC_RT_LIKELY(EXPR) (EXPR)
-#define ORC_RT_UNLIKELY(EXPR) (EXPR)
-#endif
-
-/* ORC_RT_WEAK_IMPORT marks a symbol that may be absent at run time, so that
- referencing it yields null rather than failing to load. */
-#if defined(__APPLE__)
-#define ORC_RT_WEAK_IMPORT __attribute__((weak_import))
-#elif defined(_WIN32)
-#define ORC_RT_WEAK_IMPORT
-#else
-#define ORC_RT_WEAK_IMPORT __attribute__((weak))
-#endif
-
-/* ORC_RT_BUILTIN_UNREACHABLE: an optimizer hint that the current location is
- not reachable. */
-#if ORC_RT_HAS_BUILTIN(__builtin_unreachable) || defined(__GNUC__)
-#define ORC_RT_BUILTIN_UNREACHABLE __builtin_unreachable()
-#elif defined(_MSC_VER)
-#define ORC_RT_BUILTIN_UNREACHABLE __assume(0)
-#else
-#define ORC_RT_BUILTIN_UNREACHABLE
-#endif
-
-/* ORC_RT_UNREACHABLE(MSG): marks a point the program must never reach. In
- +Asserts builds it aborts with MSG; otherwise it lowers to
- ORC_RT_BUILTIN_UNREACHABLE. */
-#ifndef NDEBUG
-#define ORC_RT_UNREACHABLE(MSG) \
- do { \
- assert(0 && (MSG)); \
- ORC_RT_BUILTIN_UNREACHABLE; \
- } while (0)
-#else
-#define ORC_RT_UNREACHABLE(MSG) ORC_RT_BUILTIN_UNREACHABLE
-#endif
-
-#endif /* ORC_RT_C_SUPPORT_COMPILER_H */
+/*===-- Compiler.h - Compiler abstractions for the ORC RT C API ---*- C -*-===*\
+|* *|
+|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
+|* Exceptions. *|
+|* See https://llvm.org/LICENSE.txt for license information. *|
+|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* Compiler-abstraction macros for the ORC runtime C API, plus the *|
+|* general-purpose ones that are usable from both C and C++. Macros specific *|
+|* to the C++ API live in orc-rt/support/Compiler.h, which includes this *|
+|* header. *|
+|* *|
+|* Some of the macros below were swiped from llvm/Support/Compiler.h. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef ORC_RT_C_SUPPORT_COMPILER_H
+#define ORC_RT_C_SUPPORT_COMPILER_H
+
+/* For assert, used by ORC_RT_UNREACHABLE below. */
+#include <assert.h>
+
+/* ORC_RT_HAS_BUILTIN(X) expands to 1 if the compiler provides the builtin X,
+ and to 0 otherwise.
+
+ This wraps __has_builtin rather than supplying a fallback definition for it.
+ __has_builtin is a reserved identifier, and defining one from a public header
+ can collide with the compiler's own definition or with other libraries that
+ the client also includes. */
+#if defined(__has_builtin)
+#define ORC_RT_HAS_BUILTIN(X) __has_builtin(X)
+#else
+#define ORC_RT_HAS_BUILTIN(X) 0
+#endif
+
+/* Helper to promote strict prototype warnings to errors */
+#ifdef __clang__
+#define ORC_RT_C_STRICT_PROTOTYPES_BEGIN \
+ _Pragma("clang diagnostic push") \
+ _Pragma("clang diagnostic error \"-Wstrict-prototypes\"")
+#define ORC_RT_C_STRICT_PROTOTYPES_END _Pragma("clang diagnostic pop")
+#else
+#define ORC_RT_C_STRICT_PROTOTYPES_BEGIN
+#define ORC_RT_C_STRICT_PROTOTYPES_END
+#endif
+
+/* Helper to wrap C code for C++ */
+#ifdef __cplusplus
+#define ORC_RT_C_EXTERN_C_BEGIN \
+ extern "C" { \
+ ORC_RT_C_STRICT_PROTOTYPES_BEGIN
+#define ORC_RT_C_EXTERN_C_END \
+ ORC_RT_C_STRICT_PROTOTYPES_END \
+ }
+#else
+#define ORC_RT_C_EXTERN_C_BEGIN ORC_RT_C_STRICT_PROTOTYPES_BEGIN
+#define ORC_RT_C_EXTERN_C_END ORC_RT_C_STRICT_PROTOTYPES_END
+#endif
+
+/* ORC_RT_C_EXPORT marks a symbol declared in orc-rt-c as part of the ORC
+ runtime's binary interface: exported from the runtime when it is built as a
+ shared library, and imported by consumers of that library.
+
+ TODO: Add the Windows __declspec(dllexport) / __declspec(dllimport) and
+ static-build cases once there is a shared-library build to exercise them. */
+#if defined(_WIN32)
+#define ORC_RT_C_EXPORT
+#elif defined(__has_attribute) && __has_attribute(visibility)
+#define ORC_RT_C_EXPORT __attribute__((visibility("default")))
+#else
+#define ORC_RT_C_EXPORT
+#endif
+
+#if !defined(ORC_RT_C_EXPORT)
+#define ORC_RT_C_EXPORT
+#endif
+
+/* ORC_RT_MAYBE_UNUSED indicates that a symbol may not be used, and that the
+ compiler should not issue unused-symbol warnings for it. */
+#if defined(__cplusplus)
+#define ORC_RT_MAYBE_UNUSED [[maybe_unused]]
+#elif defined(__has_attribute) && __has_attribute(unused)
+#define ORC_RT_MAYBE_UNUSED __attribute__((unused))
+#else
+#define ORC_RT_MAYBE_UNUSED
+#endif
+
+/* ORC_RT_C_NOTHROW indicates that a function won't throw a C++ exception. */
+#if defined(__cplusplus)
+#define ORC_RT_C_NOTHROW noexcept
+#elif defined(__GNUC__) || defined(__clang__)
+#define ORC_RT_C_NOTHROW __attribute__((nothrow))
+#else
+#define ORC_RT_C_NOTHROW
+#endif
+
+/* ORC_RT_FORMAT_PRINTF(FmtIdx, FirstArg) marks a function as taking a
+ printf-style format string at argument position FmtIdx, with the variadic
+ arguments beginning at FirstArg, so the compiler can check the format string
+ against its arguments. Indices are 1-based. */
+#if defined(__GNUC__) || defined(__clang__)
+#define ORC_RT_FORMAT_PRINTF(FmtIdx, FirstArg) \
+ __attribute__((format(printf, FmtIdx, FirstArg)))
+#else
+#define ORC_RT_FORMAT_PRINTF(FmtIdx, FirstArg)
+#endif
+
+/* ORC_RT_LIKELY(EXPR) / ORC_RT_UNLIKELY(EXPR) hint to the optimizer which way a
+ condition is expected to go. */
+#if ORC_RT_HAS_BUILTIN(__builtin_expect)
+#define ORC_RT_LIKELY(EXPR) __builtin_expect(!!(EXPR), 1)
+#define ORC_RT_UNLIKELY(EXPR) __builtin_expect(!!(EXPR), 0)
+#else
+#define ORC_RT_LIKELY(EXPR) (EXPR)
+#define ORC_RT_UNLIKELY(EXPR) (EXPR)
+#endif
+
+/* ORC_RT_WEAK_IMPORT marks a symbol that may be absent at run time, so that
+ referencing it yields null rather than failing to load. */
+#if defined(__APPLE__)
+#define ORC_RT_WEAK_IMPORT __attribute__((weak_import))
+#elif defined(_WIN32)
+#define ORC_RT_WEAK_IMPORT
+#else
+#define ORC_RT_WEAK_IMPORT __attribute__((weak))
+#endif
+
+/* ORC_RT_BUILTIN_UNREACHABLE: an optimizer hint that the current location is
+ not reachable. */
+#if ORC_RT_HAS_BUILTIN(__builtin_unreachable) || defined(__GNUC__)
+#define ORC_RT_BUILTIN_UNREACHABLE __builtin_unreachable()
+#elif defined(_MSC_VER)
+#define ORC_RT_BUILTIN_UNREACHABLE __assume(0)
+#else
+#define ORC_RT_BUILTIN_UNREACHABLE
+#endif
+
+/* ORC_RT_UNREACHABLE(MSG): marks a point the program must never reach. In
+ +Asserts builds it aborts with MSG; otherwise it lowers to
+ ORC_RT_BUILTIN_UNREACHABLE. */
+#ifndef NDEBUG
+#define ORC_RT_UNREACHABLE(MSG) \
+ do { \
+ assert(0 && (MSG)); \
+ ORC_RT_BUILTIN_UNREACHABLE; \
+ } while (0)
+#else
+#define ORC_RT_UNREACHABLE(MSG) ORC_RT_BUILTIN_UNREACHABLE
+#endif
+
+#endif /* ORC_RT_C_SUPPORT_COMPILER_H */
diff --git a/orc-rt/include/orc-rt-internal/tools/OptionParser.h b/orc-rt/include/orc-rt-internal/tools/OptionParser.h
index ddc50f46b0613..045acd1cc0920 100644
--- a/orc-rt/include/orc-rt-internal/tools/OptionParser.h
+++ b/orc-rt/include/orc-rt-internal/tools/OptionParser.h
@@ -1,270 +1,272 @@
-//===- OptionParser.h -------------------------------------------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Simple orc-rt command-line parser. Supports flags, values and positionals.
-// All storage owned by caller.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_INTERNAL_TOOLS_OPTIONPARSER_H
-#define ORC_RT_INTERNAL_TOOLS_OPTIONPARSER_H
-
-#include <algorithm>
-#include <charconv>
-#include <optional>
-#include <string>
-#include <string_view>
-#include <vector>
-
-#include "orc-rt-internal/support/StringExtras.h"
-#include "orc-rt/support/Error.h"
-#include "orc-rt/support/move_only_function.h"
-
-namespace orc_rt {
-namespace detail {
-
-template <typename T> inline std::optional<T> parseValue(std::string_view Str);
-
-template <>
-inline std::optional<std::string>
-parseValue<std::string>(std::string_view Str) {
- return std::string(Str);
-}
-
-template <>
-inline std::optional<std::string_view>
-parseValue<std::string_view>(std::string_view Str) {
- return Str;
-}
-
-template <> inline std::optional<int> parseValue<int>(std::string_view Str) {
- if (Str.empty())
- return std::nullopt;
- int Val{};
- auto Ret = std::from_chars(Str.data(), Str.data() + Str.size(), Val);
- if (Ret.ec != std::errc() || Ret.ptr != Str.data() + Str.size())
- return std::nullopt;
- return Val;
-}
-
-template <> inline std::optional<bool> parseValue<bool>(std::string_view Str) {
- if (Str.empty())
- return std::nullopt;
-
- if (Str == "1")
- return true;
- if (Str == "0")
- return false;
-
- std::string Val;
- std::transform(
- Str.begin(), Str.end(), std::back_inserter(Val),
- [](unsigned char C) { return static_cast<char>(std::tolower(C)); });
-
- if (Val == "true")
- return true;
- if (Val == "false")
- return false;
-
- return std::nullopt;
-}
-} // namespace detail
-
-class OptionParser {
-public:
- enum class OptionKind { Flag, Value };
- OptionParser() = default;
-
- OptionParser &addFlag(std::string_view Name, std::string_view Desc,
- bool DefaultVal, bool &Val,
- std::optional<char> ShortName = std::nullopt) {
- return addValue(Name, Desc, DefaultVal, Val, OptionKind::Flag,
- std::move(ShortName));
- }
-
- template <typename T>
- OptionParser &addValue(std::string_view Name, std::string_view Desc,
- T DefaultVal, T &Val,
- OptionKind Kind = OptionKind::Value,
- std::optional<char> ShortName = std::nullopt) {
- Val = DefaultVal;
- Opts.push_back({.Name = std::string(Name),
- .ShortName = std::move(ShortName),
- .Desc = std::string(Desc),
- .Kind = Kind,
- .Default = [&Val, DV = DefaultVal]() { Val = DV; },
- .FromString = [&Val, OptName = std::string(Name)](
- std::string_view S) -> Error {
- if (auto V = detail::parseValue<T>(S)) {
- Val = *V;
- return Error::success();
- }
- return make_error<StringError>(
- std::string("Invalid value for '") + OptName +
- "': '" + std::string(S) + "'");
- }});
- return *this;
- }
-
- std::string formatHelp(std::string_view ProgramName) const {
- StringOutputStream OS;
- OS << "Usage: " << ProgramName << " [options] [positional arguments]\n\n";
- OS << "OPTIONS:\n";
-
- bool AnyShortNames =
- std::any_of(Opts.begin(), Opts.end(),
- [](const Option &O) { return O.ShortName.has_value(); });
-
- size_t MaxWidth = 0;
- for (const auto &Opt : Opts) {
- size_t CurrentWidth = 2; // " "
- if (AnyShortNames)
- CurrentWidth += 4; // "-x, "
- CurrentWidth += 2 + Opt.Name.length(); // "--name"
- if (Opt.Kind == OptionKind::Value)
- CurrentWidth += 8; // " <value>"
- MaxWidth = std::max(MaxWidth, CurrentWidth);
- }
-
- for (const auto &Opt : Opts) {
- std::string FlagStr = " ";
- if (AnyShortNames) {
- if (Opt.ShortName) {
- FlagStr += "-";
- FlagStr += *Opt.ShortName;
- FlagStr += ", ";
- } else {
- FlagStr += " "; // Pad gutter
- }
- }
- FlagStr += "--" + Opt.Name;
- if (Opt.Kind == OptionKind::Value)
- FlagStr += " <value>";
-
- OS << ljust(FlagStr, MaxWidth + 2) << Opt.Desc << "\n";
- }
-
- return std::move(OS).str();
- }
-
- /// Parse an argument list.
- ///
- /// Iterators should be over program arguments only, and should not include
- /// the program name as the first argument.
- template <typename I> Error parse(I Begin, I End) {
- std::for_each(Opts.begin(), Opts.end(),
- [](const Option &O) { O.Default(); });
- Positionals.clear();
- bool AfterDashDash = false;
-
- for (auto It = Begin; It != End; ++It) {
- std::string_view Tok(*It);
- if (!AfterDashDash && Tok == "--") {
- AfterDashDash = true;
- continue;
- }
- if (!AfterDashDash && startsWith(Tok, "--")) {
- std::string_view K = Tok.substr(2);
- std::string_view V;
- bool HasValue = false;
- if (auto P = K.find('='); P != std::string_view::npos) {
- V = K.substr(P + 1);
- K = K.substr(0, P);
- HasValue = true;
- }
- auto FoundOpt = findOpt(K);
- if (!FoundOpt)
- return make_error<StringError>("Unknown option '" + std::string(Tok) +
- "'");
- if (auto Err = consumeValue(FoundOpt, V, HasValue, It, End))
- return Err;
- } else if (!AfterDashDash && startsWith(Tok, "-") && Tok.size() > 1) {
- std::string_view Group = Tok.substr(1);
- for (size_t i = 0; i < Group.size(); ++i) {
- auto FoundOpt = findOpt(Group[i]);
- if (!FoundOpt)
- return make_error<StringError>(
- std::string("Unknown short option '-") + Group[i] + "'");
- if (FoundOpt->Kind == OptionKind::Value) {
- std::string_view V = Group.substr(i + 1);
- bool HasValue = !V.empty();
- if (auto Err = consumeValue(FoundOpt, V, HasValue, It, End))
- return Err;
- break;
- } else {
- if (auto Err = FoundOpt->FromString("true"))
- return Err;
- }
- }
- } else {
- Positionals.emplace_back(Tok);
- }
- }
- return Error::success();
- }
-
- /// Parse main-like args: argc must be >= 1, and argv[0] must contain the
- /// program name.
- Error parseAsMainArgs(int argc, char **argv) {
- if (argc == 0)
- return make_error<StringError>("no program-name argument in argv[0]");
- return parse(argv + 1, argv + argc);
- }
-
- const std::vector<std::string> &positionals() const { return Positionals; }
-
-private:
- struct Option {
- std::string Name;
- std::optional<char> ShortName;
- std::string Desc;
- OptionKind Kind{};
- move_only_function<void() const> Default;
- move_only_function<Error(std::string_view) const> FromString;
- };
-
- std::vector<std::string> Positionals;
- std::vector<Option> Opts;
-
- const Option *findOpt(std::string_view L) const {
- auto It = std::find_if(Opts.begin(), Opts.end(),
- [&](const Option &O) { return O.Name == L; });
- return It != Opts.end() ? &(*It) : nullptr;
- }
-
- const Option *findOpt(char S) const {
- auto It = std::find_if(Opts.begin(), Opts.end(), [&](const Option &O) {
- return O.ShortName && *O.ShortName == S;
- });
- return It != Opts.end() ? &(*It) : nullptr;
- }
-
- template <typename I>
- Error consumeValue(const Option *Opt, std::string_view ExplicitV, bool HasV,
- I &It, I End) {
- std::string_view V = ExplicitV;
- if (Opt->Kind == OptionKind::Flag) {
- if (!HasV)
- V = "true";
- } else if (!HasV) {
- if (++It == End)
- return make_error<StringError>("Option '--" + Opt->Name +
- "' requires a value");
- V = *It;
- }
- return Opt->FromString(V);
- }
-
- static bool startsWith(std::string_view S, std::string_view P) {
- return S.size() >= P.size() && S.compare(0, P.size(), P) == 0;
- }
-};
-
-} // namespace orc_rt
-
-#endif // ORC_RT_INTERNAL_TOOLS_OPTIONPARSER_H
+//===- OptionParser.h -------------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Simple orc-rt command-line parser. Supports flags, values and positionals.
+// All storage owned by caller.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ORC_RT_INTERNAL_TOOLS_OPTIONPARSER_H
+#define ORC_RT_INTERNAL_TOOLS_OPTIONPARSER_H
+
+#include <algorithm>
+#include <charconv>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "orc-rt-internal/support/StringExtras.h"
+#include "orc-rt/support/Error.h"
+#include "orc-rt/support/move_only_function.h"
+
+namespace orc_rt {
+namespace detail {
+
+template <typename T> inline std::optional<T> parseValue(std::string_view Str);
+
+template <>
+inline std::optional<std::string>
+parseValue<std::string>(std::string_view Str) {
+ return std::string(Str);
+}
+
+template <>
+inline std::optional<std::string_view>
+parseValue<std::string_view>(std::string_view Str) {
+ return Str;
+}
+
+template <> inline std::optional<int> parseValue<int>(std::string_view Str) {
+ if (Str.empty())
+ return std::nullopt;
+ int Val{};
+ auto Ret = std::from_chars(Str.data(), Str.data() + Str.size(), Val);
+ if (Ret.ec != std::errc() || Ret.ptr != Str.data() + Str.size())
+ return std::nullopt;
+ return Val;
+}
+
+template <> inline std::optional<bool> parseValue<bool>(std::string_view Str) {
+ if (Str.empty())
+ return std::nullopt;
+
+ if (Str == "1")
+ return true;
+ if (Str == "0")
+ return false;
+
+ std::string Val;
+ std::transform(
+ Str.begin(), Str.end(), std::back_inserter(Val),
+ [](unsigned char C) { return static_cast<char>(std::tolower(C)); });
+
+ if (Val == "true")
+ return true;
+ if (Val == "false")
+ return false;
+
+ return std::nullopt;
+}
+} // namespace detail
+
+class OptionParser {
+public:
+ enum class OptionKind { Flag, Value };
+ OptionParser() = default;
+
+ OptionParser &addFlag(std::string_view Name, std::string_view Desc,
+ bool DefaultVal, bool &Val,
+ std::optional<char> ShortName = std::nullopt) {
+ return addValue(Name, Desc, DefaultVal, Val, OptionKind::Flag,
+ std::move(ShortName));
+ }
+
+ template <typename T>
+ OptionParser &addValue(std::string_view Name, std::string_view Desc,
+ T DefaultVal, T &Val,
+ OptionKind Kind = OptionKind::Value,
+ std::optional<char> ShortName = std::nullopt) {
+ Val = DefaultVal;
+ Opts.push_back({
+ std::string(Name),
+ std::move(ShortName),
+ std::string(Desc),
+ Kind,
+ [&Val, DV = DefaultVal]() { Val = DV; },
+ [&Val, OptName = std::string(Name)](
+ std::string_view S) -> orc_rt::Error {
+ if (auto V = detail::parseValue<T>(S)) {
+ Val = *V;
+ return orc_rt::Error::success();
+ }
+
+ return orc_rt::make_error<orc_rt::StringError>(
+ std::string("Invalid value for '") + OptName +
+ "': '" + std::string(S) + "'");
+ }});
+ return *this;
+ }
+
+ std::string formatHelp(std::string_view ProgramName) const {
+ StringOutputStream OS;
+ OS << "Usage: " << ProgramName << " [options] [positional arguments]\n\n";
+ OS << "OPTIONS:\n";
+
+ bool AnyShortNames =
+ std::any_of(Opts.begin(), Opts.end(),
+ [](const Option &O) { return O.ShortName.has_value(); });
+
+ size_t MaxWidth = 0;
+ for (const auto &Opt : Opts) {
+ size_t CurrentWidth = 2; // " "
+ if (AnyShortNames)
+ CurrentWidth += 4; // "-x, "
+ CurrentWidth += 2 + Opt.Name.length(); // "--name"
+ if (Opt.Kind == OptionKind::Value)
+ CurrentWidth += 8; // " <value>"
+ MaxWidth = std::max(MaxWidth, CurrentWidth);
+ }
+
+ for (const auto &Opt : Opts) {
+ std::string FlagStr = " ";
+ if (AnyShortNames) {
+ if (Opt.ShortName) {
+ FlagStr += "-";
+ FlagStr += *Opt.ShortName;
+ FlagStr += ", ";
+ } else {
+ FlagStr += " "; // Pad gutter
+ }
+ }
+ FlagStr += "--" + Opt.Name;
+ if (Opt.Kind == OptionKind::Value)
+ FlagStr += " <value>";
+
+ OS << ljust(FlagStr, MaxWidth + 2) << Opt.Desc << "\n";
+ }
+
+ return std::move(OS).str();
+ }
+
+ /// Parse an argument list.
+ ///
+ /// Iterators should be over program arguments only, and should not include
+ /// the program name as the first argument.
+ template <typename I> Error parse(I Begin, I End) {
+ std::for_each(Opts.begin(), Opts.end(),
+ [](const Option &O) { O.Default(); });
+ Positionals.clear();
+ bool AfterDashDash = false;
+
+ for (auto It = Begin; It != End; ++It) {
+ std::string_view Tok(*It);
+ if (!AfterDashDash && Tok == "--") {
+ AfterDashDash = true;
+ continue;
+ }
+ if (!AfterDashDash && startsWith(Tok, "--")) {
+ std::string_view K = Tok.substr(2);
+ std::string_view V;
+ bool HasValue = false;
+ if (auto P = K.find('='); P != std::string_view::npos) {
+ V = K.substr(P + 1);
+ K = K.substr(0, P);
+ HasValue = true;
+ }
+ auto FoundOpt = findOpt(K);
+ if (!FoundOpt)
+ return make_error<StringError>("Unknown option '" + std::string(Tok) +
+ "'");
+ if (auto Err = consumeValue(FoundOpt, V, HasValue, It, End))
+ return Err;
+ } else if (!AfterDashDash && startsWith(Tok, "-") && Tok.size() > 1) {
+ std::string_view Group = Tok.substr(1);
+ for (size_t i = 0; i < Group.size(); ++i) {
+ auto FoundOpt = findOpt(Group[i]);
+ if (!FoundOpt)
+ return make_error<StringError>(
+ std::string("Unknown short option '-") + Group[i] + "'");
+ if (FoundOpt->Kind == OptionKind::Value) {
+ std::string_view V = Group.substr(i + 1);
+ bool HasValue = !V.empty();
+ if (auto Err = consumeValue(FoundOpt, V, HasValue, It, End))
+ return Err;
+ break;
+ } else {
+ if (auto Err = FoundOpt->FromString("true"))
+ return Err;
+ }
+ }
+ } else {
+ Positionals.emplace_back(Tok);
+ }
+ }
+ return Error::success();
+ }
+
+ /// Parse main-like args: argc must be >= 1, and argv[0] must contain the
+ /// program name.
+ Error parseAsMainArgs(int argc, char **argv) {
+ if (argc == 0)
+ return make_error<StringError>("no program-name argument in argv[0]");
+ return parse(argv + 1, argv + argc);
+ }
+
+ const std::vector<std::string> &positionals() const { return Positionals; }
+
+private:
+ struct Option {
+ std::string Name;
+ std::optional<char> ShortName;
+ std::string Desc;
+ OptionKind Kind{};
+ move_only_function<void() const> Default;
+ move_only_function<Error(std::string_view) const> FromString;
+ };
+
+ std::vector<std::string> Positionals;
+ std::vector<Option> Opts;
+
+ const Option *findOpt(std::string_view L) const {
+ auto It = std::find_if(Opts.begin(), Opts.end(),
+ [&](const Option &O) { return O.Name == L; });
+ return It != Opts.end() ? &(*It) : nullptr;
+ }
+
+ const Option *findOpt(char S) const {
+ auto It = std::find_if(Opts.begin(), Opts.end(), [&](const Option &O) {
+ return O.ShortName && *O.ShortName == S;
+ });
+ return It != Opts.end() ? &(*It) : nullptr;
+ }
+
+ template <typename I>
+ Error consumeValue(const Option *Opt, std::string_view ExplicitV, bool HasV,
+ I &It, I End) {
+ std::string_view V = ExplicitV;
+ if (Opt->Kind == OptionKind::Flag) {
+ if (!HasV)
+ V = "true";
+ } else if (!HasV) {
+ if (++It == End)
+ return make_error<StringError>("Option '--" + Opt->Name +
+ "' requires a value");
+ V = *It;
+ }
+ return Opt->FromString(V);
+ }
+
+ static bool startsWith(std::string_view S, std::string_view P) {
+ return S.size() >= P.size() && S.compare(0, P.size(), P) == 0;
+ }
+};
+
+} // namespace orc_rt
+
+#endif // ORC_RT_INTERNAL_TOOLS_OPTIONPARSER_H
diff --git a/orc-rt/include/orc-rt/support/BitmaskEnum.h b/orc-rt/include/orc-rt/support/BitmaskEnum.h
index 85a863f99d6c2..a007f44c58882 100644
--- a/orc-rt/include/orc-rt/support/BitmaskEnum.h
+++ b/orc-rt/include/orc-rt/support/BitmaskEnum.h
@@ -1,180 +1,181 @@
-//===---- BitmaskEnum.h - Enable bitmask operations on enums ----*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Provides utilities for easily adding bitmask operation support to enums.
-//
-// This code was derived from LLVM's include/llvm/ADT/BitmaskEnum.h header, and
-// adapted for the ORC runtime.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_SUPPORT_BITMASKENUM_H
-#define ORC_RT_SUPPORT_BITMASKENUM_H
-
-#include "orc-rt/support/bit.h"
-
-#include <cassert>
-#include <limits>
-#include <type_traits>
-
-namespace orc_rt {
-
-/// ORC_RT_MARK_AS_BITMASK_ENUM lets you opt in an individual enum type so you
-/// can perform bitwise operations on it without putting static_cast everywhere.
-///
-/// \code
-/// enum MyEnum {
-/// E1 = 1, E2 = 2, E3 = 4, E4 = 8,
-/// ORC_RT_MARK_AS_BITMASK_ENUM(/* LargestValue = */ E4)
-/// };
-///
-/// void Foo() {
-/// MyEnum A = (E1 | E2) & E3 ^ ~E4; // Look, ma: No static_cast!
-/// }
-/// \endcode
-///
-/// Normally when you do a bitwise operation on an enum value, you get back an
-/// instance of the underlying type (e.g. int). But using this macro, bitwise
-/// ops on your enum will return you back instances of the enum. This is
-/// particularly useful for enums which represent a combination of flags.
-///
-/// The parameter to ORC_RT_MARK_AS_BITMASK_ENUM should be the largest
-/// individual value in your enum.
-///
-/// All of the enum's values must be non-negative.
-#define ORC_RT_MARK_AS_BITMASK_ENUM(LargestValue) \
- ORC_RT_BITMASK_LARGEST_ENUMERATOR = LargestValue
-
-/// ORC_RT_DECLARE_ENUM_AS_BITMASK can be used to declare an enum type as a bit
-/// set, so that bitwise operation on such enum does not require static_cast.
-///
-/// \code
-/// enum MyEnum { E1 = 1, E2 = 2, E3 = 4, E4 = 8 };
-/// ORC_RT_DECLARE_ENUM_AS_BITMASK(MyEnum, E4);
-///
-/// void Foo() {
-/// MyEnum A = (E1 | E2) & E3 ^ ~E4; // No static_cast
-/// }
-/// \endcode
-///
-/// The second parameter to ORC_RT_DECLARE_ENUM_AS_BITMASK specifies the largest
-/// bit value of the enum type.
-///
-/// ORC_RT_DECLARE_ENUM_AS_BITMASK should be used in __orc_rt namespace.
-///
-/// This a non-intrusive alternative for ORC_RT_MARK_AS_BITMASK_ENUM. It allows
-/// declaring more than one non-scoped enumerations as bitmask types in the same
-/// scope. Otherwise it provides the same functionality as
-/// ORC_RT_MARK_AS_BITMASK_ENUM.
-#define ORC_RT_DECLARE_ENUM_AS_BITMASK(Enum, LargestValue) \
- template <> struct is_bitmask_enum<Enum> : std::true_type {}; \
- template <> struct largest_bitmask_enum_bit<Enum> { \
- static constexpr std::underlying_type_t<Enum> value = LargestValue; \
- }
-
-/// Traits class to determine whether an enum has been declared as a bitwise
-/// enum via ORC_RT_DECLARE_ENUM_AS_BITMASK.
-template <typename E, typename Enable = void>
-struct is_bitmask_enum : std::false_type {};
-
-template <typename E>
-struct is_bitmask_enum<
- E, std::enable_if_t<sizeof(E::ORC_RT_BITMASK_LARGEST_ENUMERATOR) >= 0>>
- : std::true_type {};
-
-template <typename E>
-inline constexpr bool is_bitmask_enum_v = is_bitmask_enum<E>::value;
-
-/// Traits class to deermine bitmask enum largest bit.
-template <typename E, typename Enable = void> struct largest_bitmask_enum_bit;
-
-template <typename E>
-struct largest_bitmask_enum_bit<
- E, std::enable_if_t<sizeof(E::ORC_RT_BITMASK_LARGEST_ENUMERATOR) >= 0>> {
- using UnderlyingTy = std::underlying_type_t<E>;
- static_assert(std::is_unsigned_v<UnderlyingTy>,
- "Bitmask enums must have an unsigned underlying type. Declare "
- "the enum with an explicit unsigned base type, e.g. "
- "'enum class E : unsigned'; a scoped enum without one has an "
- "underlying type of int.");
- static constexpr UnderlyingTy value =
- static_cast<UnderlyingTy>(E::ORC_RT_BITMASK_LARGEST_ENUMERATOR);
-};
-
-template <typename E>
-constexpr std::underlying_type_t<E> bitmask_enum_mask() noexcept {
- using UnderlyingTy = std::underlying_type_t<E>;
- constexpr int Width = bit_width(largest_bitmask_enum_bit<E>::value);
- // Shifting by the full width of the type would be undefined, so handle a
- // largest bit in the top position separately: the mask is then every bit.
- return Width == std::numeric_limits<UnderlyingTy>::digits
- ? static_cast<UnderlyingTy>(~UnderlyingTy(0))
- : static_cast<UnderlyingTy>((UnderlyingTy(1) << Width) - 1);
-}
-
-template <typename E>
-constexpr std::underlying_type_t<E> bitmask_enum_to_underlying(E Val) noexcept {
- auto U = static_cast<std::underlying_type_t<E>>(Val);
- assert(U <= bitmask_enum_mask<E>() &&
- "Enum value too large (or langest val too small");
- return U;
-}
-
-template <typename E, typename _ = std::enable_if_t<is_bitmask_enum_v<E>>>
-struct bitmask_enum_num_bits {
- static constexpr int value = bit_width(largest_bitmask_enum_bit<E>::value);
-};
-
-template <typename E>
-inline constexpr int bitmask_enum_num_bits_v = bitmask_enum_num_bits<E>::value;
-
-template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
-constexpr E operator~(E Val) noexcept {
- return static_cast<E>(~bitmask_enum_to_underlying(Val) &
- bitmask_enum_mask<E>());
-}
-
-template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
-constexpr E operator|(E LHS, E RHS) noexcept {
- return static_cast<E>(bitmask_enum_to_underlying(LHS) |
- bitmask_enum_to_underlying(RHS));
-}
-
-template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
-constexpr E operator&(E LHS, E RHS) noexcept {
- return static_cast<E>(bitmask_enum_to_underlying(LHS) &
- bitmask_enum_to_underlying(RHS));
-}
-
-template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
-constexpr E operator^(E LHS, E RHS) noexcept {
- return static_cast<E>(bitmask_enum_to_underlying(LHS) ^
- bitmask_enum_to_underlying(RHS));
-}
-
-template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
-constexpr E &operator|=(E &LHS, E RHS) noexcept {
- LHS = LHS | RHS;
- return LHS;
-}
-
-template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
-constexpr E &operator&=(E &LHS, E RHS) noexcept {
- LHS = LHS & RHS;
- return LHS;
-}
-
-template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
-constexpr E &operator^=(E &LHS, E RHS) noexcept {
- LHS = LHS ^ RHS;
- return LHS;
-}
-
-} // namespace orc_rt
-
-#endif // ORC_RT_SUPPORT_BITMASKENUM_H
+//===---- BitmaskEnum.h - Enable bitmask operations on enums ----*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Provides utilities for easily adding bitmask operation support to enums.
+//
+// This code was derived from LLVM's include/llvm/ADT/BitmaskEnum.h header, and
+// adapted for the ORC runtime.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ORC_RT_SUPPORT_BITMASKENUM_H
+#define ORC_RT_SUPPORT_BITMASKENUM_H
+
+#include "orc-rt/support/bit.h"
+
+#include <cassert>
+#include <limits>
+#include <type_traits>
+
+namespace orc_rt {
+
+/// ORC_RT_MARK_AS_BITMASK_ENUM lets you opt in an individual enum type so you
+/// can perform bitwise operations on it without putting static_cast everywhere.
+///
+/// \code
+/// enum MyEnum {
+/// E1 = 1, E2 = 2, E3 = 4, E4 = 8,
+/// ORC_RT_MARK_AS_BITMASK_ENUM(/* LargestValue = */ E4)
+/// };
+///
+/// void Foo() {
+/// MyEnum A = (E1 | E2) & E3 ^ ~E4; // Look, ma: No static_cast!
+/// }
+/// \endcode
+///
+/// Normally when you do a bitwise operation on an enum value, you get back an
+/// instance of the underlying type (e.g. int). But using this macro, bitwise
+/// ops on your enum will return you back instances of the enum. This is
+/// particularly useful for enums which represent a combination of flags.
+///
+/// The parameter to ORC_RT_MARK_AS_BITMASK_ENUM should be the largest
+/// individual value in your enum.
+///
+/// All of the enum's values must be non-negative.
+#define ORC_RT_MARK_AS_BITMASK_ENUM(LargestValue) \
+ ORC_RT_BITMASK_LARGEST_ENUMERATOR = LargestValue
+
+/// ORC_RT_DECLARE_ENUM_AS_BITMASK can be used to declare an enum type as a bit
+/// set, so that bitwise operation on such enum does not require static_cast.
+///
+/// \code
+/// enum MyEnum { E1 = 1, E2 = 2, E3 = 4, E4 = 8 };
+/// ORC_RT_DECLARE_ENUM_AS_BITMASK(MyEnum, E4);
+///
+/// void Foo() {
+/// MyEnum A = (E1 | E2) & E3 ^ ~E4; // No static_cast
+/// }
+/// \endcode
+///
+/// The second parameter to ORC_RT_DECLARE_ENUM_AS_BITMASK specifies the largest
+/// bit value of the enum type.
+///
+/// ORC_RT_DECLARE_ENUM_AS_BITMASK should be used in __orc_rt namespace.
+///
+/// This a non-intrusive alternative for ORC_RT_MARK_AS_BITMASK_ENUM. It allows
+/// declaring more than one non-scoped enumerations as bitmask types in the same
+/// scope. Otherwise it provides the same functionality as
+/// ORC_RT_MARK_AS_BITMASK_ENUM.
+#define ORC_RT_DECLARE_ENUM_AS_BITMASK(Enum, LargestValue) \
+ template <> struct is_bitmask_enum<Enum> : std::true_type {}; \
+ template <> struct largest_bitmask_enum_bit<Enum> { \
+ static constexpr std::underlying_type_t<Enum> value = LargestValue; \
+ }
+
+/// Traits class to determine whether an enum has been declared as a bitwise
+/// enum via ORC_RT_DECLARE_ENUM_AS_BITMASK.
+template <typename E, typename Enable = void>
+struct is_bitmask_enum : std::false_type {};
+
+template <typename E>
+struct is_bitmask_enum<
+ E, std::enable_if_t<sizeof(E::ORC_RT_BITMASK_LARGEST_ENUMERATOR) >= 0>>
+ : std::true_type {};
+
+template <typename E>
+inline constexpr bool is_bitmask_enum_v = is_bitmask_enum<E>::value;
+
+/// Traits class to deermine bitmask enum largest bit.
+template <typename E, typename Enable = void> struct largest_bitmask_enum_bit;
+
+template <typename E>
+struct largest_bitmask_enum_bit<
+ E, std::enable_if_t<sizeof(E::ORC_RT_BITMASK_LARGEST_ENUMERATOR) >= 0>> {
+ using UnderlyingTy = std::underlying_type_t<E>;
+ static_assert(std::is_unsigned_v<UnderlyingTy>,
+ "Bitmask enums must have an unsigned underlying type. Declare "
+ "the enum with an explicit unsigned base type, e.g. "
+ "'enum class E : unsigned'; a scoped enum without one has an "
+ "underlying type of int.");
+ static constexpr UnderlyingTy value =
+ static_cast<UnderlyingTy>(E::ORC_RT_BITMASK_LARGEST_ENUMERATOR);
+};
+
+template <typename E>
+constexpr std::underlying_type_t<E> bitmask_enum_mask() noexcept {
+ using UnderlyingTy = std::underlying_type_t<E>;
+ constexpr int Width = bit_width_constexpr(largest_bitmask_enum_bit<E>::value);
+ // Shifting by the full width of the type would be undefined, so handle a
+ // largest bit in the top position separately: the mask is then every bit.
+ return Width == std::numeric_limits<UnderlyingTy>::digits
+ ? static_cast<UnderlyingTy>(~UnderlyingTy(0))
+ : static_cast<UnderlyingTy>((UnderlyingTy(1) << Width) - 1);
+}
+
+template <typename E>
+constexpr std::underlying_type_t<E> bitmask_enum_to_underlying(E Val) noexcept {
+ auto U = static_cast<std::underlying_type_t<E>>(Val);
+ assert(U <= bitmask_enum_mask<E>() &&
+ "Enum value too large (or langest val too small");
+ return U;
+}
+
+template <typename E, typename _ = std::enable_if_t<is_bitmask_enum_v<E>>>
+struct bitmask_enum_num_bits {
+ static constexpr int value =
+ orc_rt::bit_width_constexpr(largest_bitmask_enum_bit<E>::value);
+};
+
+template <typename E>
+inline constexpr int bitmask_enum_num_bits_v = bitmask_enum_num_bits<E>::value;
+
+template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
+constexpr E operator~(E Val) noexcept {
+ return static_cast<E>(~bitmask_enum_to_underlying(Val) &
+ bitmask_enum_mask<E>());
+}
+
+template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
+constexpr E operator|(E LHS, E RHS) noexcept {
+ return static_cast<E>(bitmask_enum_to_underlying(LHS) |
+ bitmask_enum_to_underlying(RHS));
+}
+
+template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
+constexpr E operator&(E LHS, E RHS) noexcept {
+ return static_cast<E>(bitmask_enum_to_underlying(LHS) &
+ bitmask_enum_to_underlying(RHS));
+}
+
+template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
+constexpr E operator^(E LHS, E RHS) noexcept {
+ return static_cast<E>(bitmask_enum_to_underlying(LHS) ^
+ bitmask_enum_to_underlying(RHS));
+}
+
+template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
+constexpr E &operator|=(E &LHS, E RHS) noexcept {
+ LHS = LHS | RHS;
+ return LHS;
+}
+
+template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
+constexpr E &operator&=(E &LHS, E RHS) noexcept {
+ LHS = LHS & RHS;
+ return LHS;
+}
+
+template <typename E, typename = std::enable_if_t<is_bitmask_enum_v<E>>>
+constexpr E &operator^=(E &LHS, E RHS) noexcept {
+ LHS = LHS ^ RHS;
+ return LHS;
+}
+
+} // namespace orc_rt
+
+#endif // ORC_RT_SUPPORT_BITMASKENUM_H
diff --git a/orc-rt/include/orc-rt/support/Error.h b/orc-rt/include/orc-rt/support/Error.h
index 02f876455905d..6ac21a8ec20db 100644
--- a/orc-rt/include/orc-rt/support/Error.h
+++ b/orc-rt/include/orc-rt/support/Error.h
@@ -1,727 +1,727 @@
-//===-------- Error.h - Enforced error checking for ORC RT ------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_SUPPORT_ERROR_H
-#define ORC_RT_SUPPORT_ERROR_H
-
-#include "orc-rt-c/config.h"
-#include "orc-rt-c/support/Error.h"
-#include "orc-rt/support/CallableTraitsHelper.h"
-#include "orc-rt/support/Compiler.h"
-#include "orc-rt/support/RTTI.h"
-
-#include <cassert>
-#include <cstdint>
-#include <cstdlib>
-#include <memory>
-#include <string>
-#include <string_view>
-#include <type_traits>
-
-#if ORC_RT_ENABLE_EXCEPTIONS
-#include <exception>
-#endif // ORC_RT_ENABLE_EXCEPTIONS
-
-namespace orc_rt {
-
-class Error;
-
-/// Base class for all errors.
-class ErrorInfoBase : public RTTIExtends<ErrorInfoBase, RTTIRoot> {
-public:
- static constexpr const char *RTTIName = "orc_rt::ErrorInfoBase";
-
- virtual std::string toString() const noexcept = 0;
-
-private:
-#if ORC_RT_ENABLE_EXCEPTIONS
- friend class Error;
- friend Error restore_error(ErrorInfoBase &&) noexcept;
-
- virtual void throwAsException() = 0;
-
- virtual Error restoreError() noexcept = 0;
-#endif // ORC_RT_ENABLE_EXCEPTIONS
-};
-
-/// Like RTTI-extends, but injects error-related helper methods.
-template <typename ThisT, typename ParentT>
-class ErrorExtends : public ParentT {
-public:
- static_assert(std::is_base_of_v<ErrorInfoBase, ParentT>,
- "ErrorExtends must extend ErrorInfoBase derivatives");
-
- // Inherit constructors from ParentT.
- using ParentT::ParentT;
-
- const char *dynamicRTTIName() const noexcept override {
- static_assert(std::string_view(ThisT::RTTIName) !=
- std::string_view(ParentT::RTTIName),
- "ThisT must define its own RTTIName, distinct from "
- "ParentT::RTTIName (did you forget to shadow it, or copy "
- "the parent's string literal instead of writing a new "
- "one?)");
- return ThisT::RTTIName;
- }
-
- static bool classof(const RTTIRoot *R) noexcept { return R->isA<ThisT>(); }
-
-#if ORC_RT_ENABLE_EXCEPTIONS
- void throwAsException() override {
- throw ThisT(std::move(static_cast<ThisT &>(*this)));
- }
-
- Error restoreError() noexcept override;
-#endif // ORC_RT_ENABLE_EXCEPTIONS
-
-protected:
- bool sameDylibIsA(const char *const ClassName) const noexcept override {
- return ClassName == ThisT::RTTIName || ParentT::sameDylibIsA(ClassName);
- }
-
- bool differentDylibIsA(const char *const ClassName) const noexcept override {
- return strcmp(ClassName, ThisT::RTTIName) == 0 ||
- ParentT::differentDylibIsA(ClassName);
- }
-};
-
-/// Represents an environmental error.
-class [[nodiscard]] Error {
-
- template <typename T> friend class Expected;
-
- friend Error make_error(std::unique_ptr<ErrorInfoBase> Payload) noexcept;
-
- template <typename... HandlerTs>
- friend Error handleErrors(Error E, HandlerTs &&...Hs);
-
- friend orc_rt_ErrorRef wrap(Error Err) noexcept;
-
-public:
- /// Destroy this error. Aborts if error was not checked, or was checked but
- /// not handled.
- ~Error() noexcept { assertIsChecked(); }
-
- Error(const Error &) = delete;
- Error &operator=(const Error &) = delete;
-
- /// Move-construct an error. The newly constructed error is considered
- /// unchecked, even if the source error had been checked. The original error
- /// becomes a checked success value.
- Error(Error &&Other) noexcept {
- setChecked(true);
- *this = std::move(Other);
- }
-
- /// Move-assign an error value. The current error must represent success, you
- /// you cannot overwrite an unhandled error. The current error is then
- /// considered unchecked. The source error becomes a checked success value,
- /// regardless of its original state.
- Error &operator=(Error &&Other) noexcept {
- // Don't allow overwriting of unchecked values.
- assertIsChecked();
- setPtr(Other.getPtr());
-
- // This Error is unchecked, even if the source error was checked.
- setChecked(false);
-
- // Null out Other's payload and set its checked bit.
- Other.setPtr(nullptr);
- Other.setChecked(true);
-
- return *this;
- }
-
- /// Create a success value.
- static Error success() noexcept { return Error(); }
-
- /// Error values convert to true for failure values, false otherwise.
- explicit operator bool() noexcept {
- setChecked(getPtr() == nullptr);
- return getPtr() != nullptr;
- }
-
- /// Return true if this Error contains a failure value of the given type.
- template <typename ErrT> bool isA() const noexcept {
- return getPtr() && getPtr()->isA<ErrT>();
- }
-
-#if ORC_RT_ENABLE_EXCEPTIONS
- void throwOnFailure() {
- if (auto P = takePayload())
- P->throwAsException();
- }
-#endif // ORC_RT_ENABLE_EXCEPTIONS
-
-private:
- Error() noexcept = default;
-
- Error(std::unique_ptr<ErrorInfoBase> ErrInfo) noexcept {
- auto RawErrPtr = reinterpret_cast<uintptr_t>(ErrInfo.release());
- assert((RawErrPtr & 0x1) == 0 && "ErrorInfo is insufficiently aligned");
- ErrPtr = RawErrPtr | 0x1;
- }
-
- void assertIsChecked() noexcept {
- if (ORC_RT_UNLIKELY(!isChecked() || getPtr())) {
- fprintf(stderr, "Error must be checked prior to destruction.\n");
- abort(); // Some sort of JIT program abort?
- }
- }
-
- template <typename ErrT = ErrorInfoBase> ErrT *getPtr() const noexcept {
- return reinterpret_cast<ErrT *>(ErrPtr & ~uintptr_t(1));
- }
-
- void setPtr(ErrorInfoBase *Ptr) noexcept {
- ErrPtr = (reinterpret_cast<uintptr_t>(Ptr) & ~uintptr_t(1)) | (ErrPtr & 1);
- }
-
- bool isChecked() const noexcept { return ErrPtr & 0x1; }
-
- void setChecked(bool Checked) noexcept {
- ErrPtr = (ErrPtr & ~uintptr_t(1)) | Checked;
- }
-
- template <typename ErrT = ErrorInfoBase>
- std::unique_ptr<ErrT> takePayload() noexcept {
- static_assert(std::is_base_of_v<ErrorInfoBase, ErrT>,
- "ErrT is not an ErrorInfoBase subclass");
- std::unique_ptr<ErrT> Tmp(getPtr<ErrT>());
- setPtr(nullptr);
- setChecked(true);
- return Tmp;
- }
-
- uintptr_t ErrPtr = 0;
-};
-
-/// Create an Error from an ErrorInfoBase.
-inline Error make_error(std::unique_ptr<ErrorInfoBase> Payload) noexcept {
- return Error(std::move(Payload));
-}
-
-#if ORC_RT_ENABLE_EXCEPTIONS
-
-template <typename ThisT, typename ParentT>
-Error ErrorExtends<ThisT, ParentT>::restoreError() noexcept {
- return make_error(
- std::make_unique<ThisT>(std::move(*static_cast<ThisT *>(this))));
-}
-
-inline Error restore_error(ErrorInfoBase &&EIB) noexcept {
- return EIB.restoreError();
-}
-
-#endif // ORC_RT_ENABLE_EXCEPTIONS
-
-/// Construct an error of ErrT with the given arguments.
-template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&...Args) {
- static_assert(std::is_base_of<ErrorInfoBase, ErrT>::value,
- "ErrT is not an ErrorInfoBase subclass");
- return make_error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
-}
-
-inline orc_rt_ErrorRef wrap(Error Err) noexcept {
- return reinterpret_cast<orc_rt_ErrorRef>(Err.takePayload().release());
-}
-
-inline Error unwrap(orc_rt_ErrorRef ErrRef) noexcept {
- return make_error(std::unique_ptr<ErrorInfoBase>(
- reinterpret_cast<ErrorInfoBase *>(ErrRef)));
-}
-
-namespace detail {
-
-template <typename RetT, typename ArgT> struct ErrorHandlerTraitsImpl;
-
-// Specialization for Error(ErrT&).
-template <typename ErrT> struct ErrorHandlerTraitsImpl<Error, ErrT &> {
- static bool appliesTo(const ErrorInfoBase &E) noexcept {
- return E.template isA<ErrT>();
- }
- template <typename HandlerT>
- static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
- assert(appliesTo(*E) && "Applying incorrect handler");
- return H(static_cast<ErrT &>(*E));
- }
-};
-
-// Specialization for void(ErrT&).
-template <typename ErrT> struct ErrorHandlerTraitsImpl<void, ErrT &> {
- static bool appliesTo(const ErrorInfoBase &E) noexcept {
- return E.template isA<ErrT>();
- }
- template <typename HandlerT>
- static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
- assert(appliesTo(*E) && "Applying incorrect handler");
- H(static_cast<ErrT &>(*E));
- return Error::success();
- }
-};
-
-// Specialization for Error(std::unique_ptr<ErrT>).
-template <typename ErrT>
-struct ErrorHandlerTraitsImpl<Error, std::unique_ptr<ErrT>> {
- static bool appliesTo(const ErrorInfoBase &E) noexcept {
- return E.template isA<ErrT>();
- }
- template <typename HandlerT>
- static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
- assert(appliesTo(*E) && "Applying incorrect handler");
- std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
- return H(std::move(SubE));
- }
-};
-
-// Specialization for void(std::unique_ptr<ErrT>).
-template <typename ErrT>
-struct ErrorHandlerTraitsImpl<void, std::unique_ptr<ErrT>> {
- static bool appliesTo(const ErrorInfoBase &E) noexcept {
- return E.template isA<ErrT>();
- }
- template <typename HandlerT>
- static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
- assert(appliesTo(*E) && "Applying incorrect handler");
- std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
- H(std::move(SubE));
- return Error::success();
- }
-};
-
-template <bool /* is_const */, bool /* is_noexcept */, typename RetT,
- typename ArgT>
-struct ErrorHandlerTraitsImplAdapter : ErrorHandlerTraitsImpl<RetT, ArgT> {};
-
-} // namespace detail.
-
-template <typename C>
-struct ErrorHandlerTraits
- : public CallableTraitsHelper<detail::ErrorHandlerTraitsImplAdapter, C> {};
-
-inline Error handleErrorsImpl(std::unique_ptr<ErrorInfoBase> Payload) {
- return make_error(std::move(Payload));
-}
-
-template <typename HandlerT, typename... HandlerTs>
-Error handleErrorsImpl(std::unique_ptr<ErrorInfoBase> Payload,
- HandlerT &&Handler, HandlerTs &&...Handlers) {
- if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
- return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
- std::move(Payload));
- return handleErrorsImpl(std::move(Payload),
- std::forward<HandlerTs>(Handlers)...);
-}
-
-/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
-/// unhandled errors (or Errors returned by handlers) are re-concatenated and
-/// returned.
-/// Because this function returns an error, its result must also be checked
-/// or returned. If you intend to handle all errors use handleAllErrors
-/// (which returns void, and will abort() on unhandled errors) instead.
-template <typename... HandlerTs>
-Error handleErrors(Error E, HandlerTs &&...Hs) {
- if (!E)
- return Error::success();
- return handleErrorsImpl(E.takePayload(), std::forward<HandlerTs>(Hs)...);
-}
-
-/// Behaves the same as handleErrors, except that by contract all errors
-/// *must* be handled by the given handlers (i.e. there must be no remaining
-/// errors after running the handlers, or llvm_unreachable is called).
-template <typename... HandlerTs>
-void handleAllErrors(Error E, HandlerTs &&...Handlers) {
- cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
-}
-
-/// Helper for Errors used as out-parameters.
-/// Sets the 'checked' flag on construction, resets it on destruction.
-class ErrorAsOutParameter {
-public:
- ErrorAsOutParameter(Error *Err) noexcept : Err(Err) {
- // Raise the checked bit if Err is success.
- if (Err)
- (void)!!*Err;
- }
-
- ErrorAsOutParameter(Error &Err) noexcept : Err(&Err) { (void)!!Err; }
-
- ~ErrorAsOutParameter() noexcept {
- // Clear the checked bit.
- if (Err && !*Err)
- *Err = Error::success();
- }
-
-private:
- Error *Err;
-};
-
-/// Tag to force construction of an Expected value in the success state. See
-/// Expected constructor for details.
-struct ForceExpectedSuccessValue {};
-
-template <typename T> class [[nodiscard]] Expected {
-
- template <class OtherT> friend class Expected;
-
- static constexpr bool IsRef = std::is_reference_v<T>;
- using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
- using error_type = std::unique_ptr<ErrorInfoBase>;
- using storage_type = std::conditional_t<IsRef, wrap, T>;
- using value_type = T;
-
- using reference = std::remove_reference_t<T> &;
- using const_reference = const std::remove_reference_t<T> &;
- using pointer = std::remove_reference_t<T> *;
- using const_pointer = const std::remove_reference_t<T> *;
-
-public:
- /// Create an Expected from a failure value.
- Expected(Error Err) noexcept : HasError(true), Unchecked(true) {
- assert(Err && "Cannot create Expected<T> from Error success value");
- new (getErrorStorage()) error_type(Err.takePayload());
- }
-
- template <typename OtherT>
- Expected(OtherT &&Val, ForceExpectedSuccessValue _,
- std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
- : HasError(false), Unchecked(true) {
- new (getStorage()) storage_type(std::forward<OtherT>(Val));
- }
-
- /// Create an Expected from a T value.
- template <typename OtherT>
- Expected(OtherT &&Val,
- std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
- : HasError(false), Unchecked(true) {
- new (getStorage()) storage_type(std::forward<OtherT>(Val));
- }
-
- /// Move-construct an Expected<T> from an Expected<OtherT>.
- Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
-
- /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
- /// must be convertible to T.
- template <class OtherT>
- Expected(Expected<OtherT> &&Other,
- std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) {
- moveConstruct(std::move(Other));
- }
-
- /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
- /// isn't convertible to T.
- template <class OtherT>
- explicit Expected(
- Expected<OtherT> &&Other,
- std::enable_if_t<!std::is_convertible_v<OtherT, T>> * = nullptr) {
- moveConstruct(std::move(Other));
- }
-
- /// Move-assign from another Expected<T>.
- Expected &operator=(Expected &&Other) {
- moveAssign(std::move(Other));
- return *this;
- }
-
- /// Destroy an Expected<T>.
- ~Expected() {
- assertIsChecked();
- if (!HasError)
- getStorage()->~storage_type();
- else
- getErrorStorage()->~error_type();
- }
-
- /// Returns true if this Expected value is in a success state (holding a T),
- /// and false if this Expected value is in a failure state.
- explicit operator bool() noexcept {
- Unchecked = HasError;
- return !HasError;
- }
-
- /// Returns true if this Expected value holds an Error of type error_type.
- template <typename ErrT> bool isFailureOfType() const noexcept {
- return HasError && (*getErrorStorage())->template isA<ErrT>();
- }
-
- /// Take ownership of the stored error.
- ///
- /// If this Expected value is in a success state (holding a T) then this
- /// method is a no-op and returns Error::success.
- ///
- /// If thsi Expected value is in a failure state (holding an Error) then this
- /// method returns the contained error and leaves this Expected in an
- /// 'empty' state from which it may be safely destructed but not otherwise
- /// accessed.
- Error takeError() noexcept {
- Unchecked = false;
- return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
- }
-
- /// Returns a pointer to the stored T value.
- pointer operator->() noexcept {
- assertIsChecked();
- return toPointer(getStorage());
- }
-
- /// Returns a pointer to the stored T value.
- const_pointer operator->() const noexcept {
- assertIsChecked();
- return toPointer(getStorage());
- }
-
- /// Returns a reference to the stored T value.
- reference operator*() noexcept {
- assertIsChecked();
- return *getStorage();
- }
-
- /// Returns a reference to the stored T value.
- const_reference operator*() const noexcept {
- assertIsChecked();
- return *getStorage();
- }
-
-private:
- template <class T1>
- static bool compareThisIfSameType(const T1 &a, const T1 &b) noexcept {
- return &a == &b;
- }
-
- template <class T1, class T2>
- static bool compareThisIfSameType(const T1 &a, const T2 &b) noexcept {
- return false;
- }
-
- template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
- HasError = Other.HasError;
- Unchecked = true;
- Other.Unchecked = false;
-
- if (!HasError)
- new (getStorage()) storage_type(std::move(*Other.getStorage()));
- else
- new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
- }
-
- template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
- assertIsChecked();
-
- if (compareThisIfSameType(*this, Other))
- return;
-
- this->~Expected();
- new (this) Expected(std::move(Other));
- }
-
- pointer toPointer(pointer Val) noexcept { return Val; }
-
- const_pointer toPointer(const_pointer Val) const noexcept { return Val; }
-
- pointer toPointer(wrap *Val) noexcept { return &Val->get(); }
-
- const_pointer toPointer(const wrap *Val) const noexcept {
- return &Val->get();
- }
-
- storage_type *getStorage() noexcept {
- assert(!HasError && "Cannot get value when an error exists!");
- return reinterpret_cast<storage_type *>(&TStorage);
- }
-
- const storage_type *getStorage() const noexcept {
- assert(!HasError && "Cannot get value when an error exists!");
- return reinterpret_cast<const storage_type *>(&TStorage);
- }
-
- error_type *getErrorStorage() noexcept {
- assert(HasError && "Cannot get error when a value exists!");
- return reinterpret_cast<error_type *>(&ErrorStorage);
- }
-
- const error_type *getErrorStorage() const noexcept {
- assert(HasError && "Cannot get error when a value exists!");
- return reinterpret_cast<const error_type *>(&ErrorStorage);
- }
-
- void assertIsChecked() noexcept {
- if (ORC_RT_UNLIKELY(Unchecked)) {
- fprintf(stderr,
- "Expected<T> must be checked before access or destruction.\n");
- abort();
- }
- }
-
- union {
- alignas(storage_type) char TStorage[sizeof(storage_type)];
- alignas(error_type) char ErrorStorage[sizeof(error_type)];
- };
-
- bool HasError : 1;
- bool Unchecked : 1;
-};
-
-/// Consume an error without doing anything.
-inline void consumeError(Error Err) {
- handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
-}
-
-/// Consumes success values. It is a programmatic error to call this function
-/// on a failure value.
-inline void cantFail(Error Err) noexcept {
-#ifndef NDEBUG
- // TODO: Log unhandled error.
- if (Err)
- abort();
-#else
- Err.operator bool(); // Reset checked flag.
-#endif
-}
-
-/// Auto-unwrap an Expected<T> value in the success state. It is a programmatic
-/// error to call this function on a failure value.
-template <typename T> T cantFail(Expected<T> E) {
- assert(E && "cantFail called on failure value");
- consumeError(E.takeError());
- return std::move(*E);
-}
-
-/// Auto-unwrap an Expected<T> value in the success state. It is a programmatic
-/// error to call this function on a failure value.
-template <typename T> T &cantFail(Expected<T &> E) {
- assert(E && "cantFail called on failure value");
- consumeError(E.takeError());
- return *E;
-}
-
-/// Convert the given error to a string. The error value is consumed in the
-/// process.
-inline std::string toString(Error Err) noexcept {
- assert(Err && "Cannot convert success value to string");
- std::string ErrMsg;
- handleAllErrors(std::move(Err),
- [&](const ErrorInfoBase &EIB) { ErrMsg = EIB.toString(); });
- return ErrMsg;
-}
-
-/// Simple string error type.
-class StringError : public ErrorExtends<StringError, ErrorInfoBase> {
-public:
- static constexpr const char *RTTIName = "orc_rt::StringError";
-
- StringError(std::string ErrMsg) noexcept : ErrMsg(std::move(ErrMsg)) {}
- std::string toString() const noexcept override { return ErrMsg; }
-
-private:
- std::string ErrMsg;
-};
-
-/// APIs for C++ exception interop.
-#if ORC_RT_ENABLE_EXCEPTIONS
-
-class ExceptionError : public ErrorExtends<ExceptionError, ErrorInfoBase> {
-public:
- static constexpr const char *RTTIName = "orc_rt::ExceptionError";
-
- ExceptionError(std::exception_ptr E) noexcept : E(std::move(E)) {}
- std::string toString() const noexcept override;
- void throwAsException() override { std::rethrow_exception(E); }
-
-private:
- mutable std::exception_ptr E;
-};
-
-namespace detail {
-
-// In general we need to wrap a return type of T with an Expected.
-template <typename RetT> struct ErrorWrapImpl {
- typedef Expected<RetT> return_type;
-
- template <typename OpFn> static return_type run(OpFn &&Op) { return Op(); }
-};
-
-// If the return is already an Expected value then we don't need to add
-// an additional level of wrapping.
-template <typename RetT> struct ErrorWrapImpl<Expected<RetT>> {
- typedef Expected<RetT> return_type;
-
- template <typename OpFn> static return_type run(OpFn &&Op) { return Op(); }
-};
-
-// Errors stay errors.
-template <> struct ErrorWrapImpl<Error> {
- typedef Error return_type;
-
- template <typename OpFn> static return_type run(OpFn &&Op) { return Op(); }
-};
-
-// void returns become Error returns.
-template <> struct ErrorWrapImpl<void> {
- typedef Error return_type;
-
- template <typename OpFn> static return_type run(OpFn &&Op) {
- Op();
- return Error::success();
- }
-};
-
-template <bool /* is_const */, bool /* is_noexcept */, typename RetT>
-struct ErrorWrapImplAdapter : ErrorWrapImpl<RetT> {};
-
-template <typename Callable>
-struct ErrorWrap
- : public CallableTraitsHelper<detail::ErrorWrapImplAdapter, Callable> {};
-
-} // namespace detail
-
-/// Run the given callback capturing any exceptions thrown into an
-/// Error / Expected failure value.
-///
-/// The return type depends on the return type of the callback:
-/// - void callbacks return Error
-/// - Error callbacks return Error
-/// - Expected<T> callbacks return Expected<T>
-/// - other T callbacks return Expected<T>
-///
-/// If the operation succeeds then...
-/// - If its result is non-void it is returned as an Expected<T> success
-/// value
-/// - If its result is void then Error::success() is retured
-///
-/// If the operation fails then...
-/// - If the exception type is std::unique_ptr<ErrorInfoBase> (i.e. a throw
-/// orc_rt failure value) then an Error is constructed to hold the
-/// failure value.
-/// - If the exception has any other type then it's captured as an
-/// ExceptionError.
-///
-/// The scheme allaws...
-/// 1. orc_rt::Error values that have been converted to exceptions via
-/// Error::throwOnFailure to be converted back into Errors without loss
-/// of dynamic type info.
-/// 2. Other Exceptions caught by this function to be converted back into
-/// exceptions via Error::throwOnFailure without loss of dynamic
-/// type info.
-
-template <typename OpFn>
-typename detail::ErrorWrap<OpFn>::return_type
-runCapturingExceptions(OpFn &&Op) noexcept {
- try {
- return detail::ErrorWrap<OpFn>::run(std::forward<OpFn>(Op));
- } catch (ErrorInfoBase &EIB) {
- return restore_error(std::move(EIB));
- } catch (...) {
- return make_error<ExceptionError>(std::current_exception());
- }
-}
-
-#endif // ORC_RT_ENABLE_EXCEPTIONS
-
-} // namespace orc_rt
-
-#endif // ORC_RT_SUPPORT_ERROR_H
+//===-------- Error.h - Enforced error checking for ORC RT ------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ORC_RT_SUPPORT_ERROR_H
+#define ORC_RT_SUPPORT_ERROR_H
+
+#include "orc-rt-c/config.h"
+#include "orc-rt-c/support/Error.h"
+#include "orc-rt/support/CallableTraitsHelper.h"
+#include "orc-rt/support/Compiler.h"
+#include "orc-rt/support/RTTI.h"
+
+#include <cassert>
+#include <cstdint>
+#include <cstdlib>
+#include <memory>
+#include <string>
+#include <string_view>
+#include <type_traits>
+
+#if ORC_RT_ENABLE_EXCEPTIONS
+#include <exception>
+#endif // ORC_RT_ENABLE_EXCEPTIONS
+
+namespace orc_rt {
+
+class Error;
+
+/// Base class for all errors.
+class ErrorInfoBase : public RTTIExtends<ErrorInfoBase, RTTIRoot> {
+public:
+ static constexpr const char *RTTIName = "orc_rt::ErrorInfoBase";
+
+ virtual std::string toString() const noexcept = 0;
+
+private:
+#if ORC_RT_ENABLE_EXCEPTIONS
+ friend class Error;
+ friend Error restore_error(ErrorInfoBase &&) noexcept;
+
+ virtual void throwAsException() = 0;
+
+ virtual Error restoreError() noexcept = 0;
+#endif // ORC_RT_ENABLE_EXCEPTIONS
+};
+
+/// Like RTTI-extends, but injects error-related helper methods.
+template <typename ThisT, typename ParentT>
+class ErrorExtends : public ParentT {
+public:
+ static_assert(std::is_base_of_v<ErrorInfoBase, ParentT>,
+ "ErrorExtends must extend ErrorInfoBase derivatives");
+
+ // Inherit constructors from ParentT.
+ using ParentT::ParentT;
+
+ const char *dynamicRTTIName() const noexcept override {
+ static_assert(std::string_view(ThisT::RTTIName) !=
+ std::string_view(ParentT::RTTIName),
+ "ThisT must define its own RTTIName, distinct from "
+ "ParentT::RTTIName (did you forget to shadow it, or copy "
+ "the parent's string literal instead of writing a new "
+ "one?)");
+ return ThisT::RTTIName;
+ }
+
+ static bool classof(const RTTIRoot *R) noexcept { return R->isA<ThisT>(); }
+
+#if ORC_RT_ENABLE_EXCEPTIONS
+ void throwAsException() override {
+ throw ThisT(std::move(static_cast<ThisT &>(*this)));
+ }
+
+ Error restoreError() noexcept override;
+#endif // ORC_RT_ENABLE_EXCEPTIONS
+
+protected:
+ bool sameDylibIsA(const char *const ClassName) const noexcept override {
+ return ClassName == ThisT::RTTIName || ParentT::sameDylibIsA(ClassName);
+ }
+
+ bool differentDylibIsA(const char *const ClassName) const noexcept override {
+ return strcmp(ClassName, ThisT::RTTIName) == 0 ||
+ ParentT::differentDylibIsA(ClassName);
+ }
+};
+
+/// Represents an environmental error.
+class [[nodiscard]] Error {
+
+ template <typename T> friend class Expected;
+
+ friend Error make_error(std::unique_ptr<ErrorInfoBase> Payload) noexcept;
+
+ template <typename... HandlerTs>
+ friend Error handleErrors(Error E, HandlerTs &&...Hs);
+
+ friend orc_rt_ErrorRef wrap(Error Err) noexcept;
+
+public:
+ /// Destroy this error. Aborts if error was not checked, or was checked but
+ /// not handled.
+ ~Error() noexcept { assertIsChecked(); }
+
+ Error(const Error &) = delete;
+ Error &operator=(const Error &) = delete;
+
+ /// Move-construct an error. The newly constructed error is considered
+ /// unchecked, even if the source error had been checked. The original error
+ /// becomes a checked success value.
+ Error(Error &&Other) noexcept {
+ setChecked(true);
+ *this = std::move(Other);
+ }
+
+ /// Move-assign an error value. The current error must represent success, you
+ /// you cannot overwrite an unhandled error. The current error is then
+ /// considered unchecked. The source error becomes a checked success value,
+ /// regardless of its original state.
+ Error &operator=(Error &&Other) noexcept {
+ // Don't allow overwriting of unchecked values.
+ assertIsChecked();
+ setPtr(Other.getPtr());
+
+ // This Error is unchecked, even if the source error was checked.
+ setChecked(false);
+
+ // Null out Other's payload and set its checked bit.
+ Other.setPtr(nullptr);
+ Other.setChecked(true);
+
+ return *this;
+ }
+
+ /// Create a success value.
+ static Error success() noexcept { return Error(); }
+
+ /// Error values convert to true for failure values, false otherwise.
+ explicit operator bool() noexcept {
+ setChecked(getPtr() == nullptr);
+ return getPtr() != nullptr;
+ }
+
+ /// Return true if this Error contains a failure value of the given type.
+ template <typename ErrT> bool isA() const noexcept {
+ return getPtr() && getPtr()->isA<ErrT>();
+ }
+
+#if ORC_RT_ENABLE_EXCEPTIONS
+ void throwOnFailure() {
+ if (auto P = takePayload())
+ P->throwAsException();
+ }
+#endif // ORC_RT_ENABLE_EXCEPTIONS
+
+private:
+ Error() noexcept = default;
+
+ Error(std::unique_ptr<ErrorInfoBase> ErrInfo) noexcept {
+ auto RawErrPtr = reinterpret_cast<uintptr_t>(ErrInfo.release());
+ assert((RawErrPtr & 0x1) == 0 && "ErrorInfo is insufficiently aligned");
+ ErrPtr = RawErrPtr | 0x1;
+ }
+
+ void assertIsChecked() noexcept {
+ if (ORC_RT_UNLIKELY(!isChecked() || getPtr())) {
+ fprintf(stderr, "Error must be checked prior to destruction.\n");
+ abort(); // Some sort of JIT program abort?
+ }
+ }
+
+ template <typename ErrT = ErrorInfoBase> ErrT *getPtr() const noexcept {
+ return reinterpret_cast<ErrT *>(ErrPtr & ~uintptr_t(1));
+ }
+
+ void setPtr(ErrorInfoBase *Ptr) noexcept {
+ ErrPtr = (reinterpret_cast<uintptr_t>(Ptr) & ~uintptr_t(1)) | (ErrPtr & 1);
+ }
+
+ bool isChecked() const noexcept { return ErrPtr & 0x1; }
+
+ void setChecked(bool Checked) noexcept {
+ ErrPtr = (ErrPtr & ~uintptr_t(1)) | (uintptr_t)Checked;
+ }
+
+ template <typename ErrT = ErrorInfoBase>
+ std::unique_ptr<ErrT> takePayload() noexcept {
+ static_assert(std::is_base_of_v<ErrorInfoBase, ErrT>,
+ "ErrT is not an ErrorInfoBase subclass");
+ std::unique_ptr<ErrT> Tmp(getPtr<ErrT>());
+ setPtr(nullptr);
+ setChecked(true);
+ return Tmp;
+ }
+
+ uintptr_t ErrPtr = 0;
+};
+
+/// Create an Error from an ErrorInfoBase.
+inline Error make_error(std::unique_ptr<ErrorInfoBase> Payload) noexcept {
+ return Error(std::move(Payload));
+}
+
+#if ORC_RT_ENABLE_EXCEPTIONS
+
+template <typename ThisT, typename ParentT>
+Error ErrorExtends<ThisT, ParentT>::restoreError() noexcept {
+ return make_error(
+ std::make_unique<ThisT>(std::move(*static_cast<ThisT *>(this))));
+}
+
+inline Error restore_error(ErrorInfoBase &&EIB) noexcept {
+ return EIB.restoreError();
+}
+
+#endif // ORC_RT_ENABLE_EXCEPTIONS
+
+/// Construct an error of ErrT with the given arguments.
+template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&...Args) {
+ static_assert(std::is_base_of<ErrorInfoBase, ErrT>::value,
+ "ErrT is not an ErrorInfoBase subclass");
+ return make_error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
+}
+
+inline orc_rt_ErrorRef wrap(Error Err) noexcept {
+ return reinterpret_cast<orc_rt_ErrorRef>(Err.takePayload().release());
+}
+
+inline Error unwrap(orc_rt_ErrorRef ErrRef) noexcept {
+ return make_error(std::unique_ptr<ErrorInfoBase>(
+ reinterpret_cast<ErrorInfoBase *>(ErrRef)));
+}
+
+namespace detail {
+
+template <typename RetT, typename ArgT> struct ErrorHandlerTraitsImpl;
+
+// Specialization for Error(ErrT&).
+template <typename ErrT> struct ErrorHandlerTraitsImpl<Error, ErrT &> {
+ static bool appliesTo(const ErrorInfoBase &E) noexcept {
+ return E.template isA<ErrT>();
+ }
+ template <typename HandlerT>
+ static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
+ assert(appliesTo(*E) && "Applying incorrect handler");
+ return H(static_cast<ErrT &>(*E));
+ }
+};
+
+// Specialization for void(ErrT&).
+template <typename ErrT> struct ErrorHandlerTraitsImpl<void, ErrT &> {
+ static bool appliesTo(const ErrorInfoBase &E) noexcept {
+ return E.template isA<ErrT>();
+ }
+ template <typename HandlerT>
+ static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
+ assert(appliesTo(*E) && "Applying incorrect handler");
+ H(static_cast<ErrT &>(*E));
+ return Error::success();
+ }
+};
+
+// Specialization for Error(std::unique_ptr<ErrT>).
+template <typename ErrT>
+struct ErrorHandlerTraitsImpl<Error, std::unique_ptr<ErrT>> {
+ static bool appliesTo(const ErrorInfoBase &E) noexcept {
+ return E.template isA<ErrT>();
+ }
+ template <typename HandlerT>
+ static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
+ assert(appliesTo(*E) && "Applying incorrect handler");
+ std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
+ return H(std::move(SubE));
+ }
+};
+
+// Specialization for void(std::unique_ptr<ErrT>).
+template <typename ErrT>
+struct ErrorHandlerTraitsImpl<void, std::unique_ptr<ErrT>> {
+ static bool appliesTo(const ErrorInfoBase &E) noexcept {
+ return E.template isA<ErrT>();
+ }
+ template <typename HandlerT>
+ static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
+ assert(appliesTo(*E) && "Applying incorrect handler");
+ std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
+ H(std::move(SubE));
+ return Error::success();
+ }
+};
+
+template <bool /* is_const */, bool /* is_noexcept */, typename RetT,
+ typename ArgT>
+struct ErrorHandlerTraitsImplAdapter : ErrorHandlerTraitsImpl<RetT, ArgT> {};
+
+} // namespace detail.
+
+template <typename C>
+struct ErrorHandlerTraits
+ : public CallableTraitsHelper<detail::ErrorHandlerTraitsImplAdapter, C> {};
+
+inline Error handleErrorsImpl(std::unique_ptr<ErrorInfoBase> Payload) {
+ return make_error(std::move(Payload));
+}
+
+template <typename HandlerT, typename... HandlerTs>
+Error handleErrorsImpl(std::unique_ptr<ErrorInfoBase> Payload,
+ HandlerT &&Handler, HandlerTs &&...Handlers) {
+ if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
+ return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
+ std::move(Payload));
+ return handleErrorsImpl(std::move(Payload),
+ std::forward<HandlerTs>(Handlers)...);
+}
+
+/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
+/// unhandled errors (or Errors returned by handlers) are re-concatenated and
+/// returned.
+/// Because this function returns an error, its result must also be checked
+/// or returned. If you intend to handle all errors use handleAllErrors
+/// (which returns void, and will abort() on unhandled errors) instead.
+template <typename... HandlerTs>
+Error handleErrors(Error E, HandlerTs &&...Hs) {
+ if (!E)
+ return Error::success();
+ return handleErrorsImpl(E.takePayload(), std::forward<HandlerTs>(Hs)...);
+}
+
+/// Behaves the same as handleErrors, except that by contract all errors
+/// *must* be handled by the given handlers (i.e. there must be no remaining
+/// errors after running the handlers, or llvm_unreachable is called).
+template <typename... HandlerTs>
+void handleAllErrors(Error E, HandlerTs &&...Handlers) {
+ cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
+}
+
+/// Helper for Errors used as out-parameters.
+/// Sets the 'checked' flag on construction, resets it on destruction.
+class ErrorAsOutParameter {
+public:
+ ErrorAsOutParameter(Error *Err) noexcept : Err(Err) {
+ // Raise the checked bit if Err is success.
+ if (Err)
+ (void)!!*Err;
+ }
+
+ ErrorAsOutParameter(Error &Err) noexcept : Err(&Err) { (void)!!Err; }
+
+ ~ErrorAsOutParameter() noexcept {
+ // Clear the checked bit.
+ if (Err && !*Err)
+ *Err = Error::success();
+ }
+
+private:
+ Error *Err;
+};
+
+/// Tag to force construction of an Expected value in the success state. See
+/// Expected constructor for details.
+struct ForceExpectedSuccessValue {};
+
+template <typename T> class [[nodiscard]] Expected {
+
+ template <class OtherT> friend class Expected;
+
+ static constexpr bool IsRef = std::is_reference_v<T>;
+ using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
+ using error_type = std::unique_ptr<ErrorInfoBase>;
+ using storage_type = std::conditional_t<IsRef, wrap, T>;
+ using value_type = T;
+
+ using reference = std::remove_reference_t<T> &;
+ using const_reference = const std::remove_reference_t<T> &;
+ using pointer = std::remove_reference_t<T> *;
+ using const_pointer = const std::remove_reference_t<T> *;
+
+public:
+ /// Create an Expected from a failure value.
+ Expected(Error Err) noexcept : HasError(true), Unchecked(true) {
+ assert(Err && "Cannot create Expected<T> from Error success value");
+ new (getErrorStorage()) error_type(Err.takePayload());
+ }
+
+ template <typename OtherT>
+ Expected(OtherT &&Val, ForceExpectedSuccessValue _,
+ std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
+ : HasError(false), Unchecked(true) {
+ new (getStorage()) storage_type(std::forward<OtherT>(Val));
+ }
+
+ /// Create an Expected from a T value.
+ template <typename OtherT>
+ Expected(OtherT &&Val,
+ std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr)
+ : HasError(false), Unchecked(true) {
+ new (getStorage()) storage_type(std::forward<OtherT>(Val));
+ }
+
+ /// Move-construct an Expected<T> from an Expected<OtherT>.
+ Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
+
+ /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
+ /// must be convertible to T.
+ template <class OtherT>
+ Expected(Expected<OtherT> &&Other,
+ std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) {
+ moveConstruct(std::move(Other));
+ }
+
+ /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
+ /// isn't convertible to T.
+ template <class OtherT>
+ explicit Expected(
+ Expected<OtherT> &&Other,
+ std::enable_if_t<!std::is_convertible_v<OtherT, T>> * = nullptr) {
+ moveConstruct(std::move(Other));
+ }
+
+ /// Move-assign from another Expected<T>.
+ Expected &operator=(Expected &&Other) {
+ moveAssign(std::move(Other));
+ return *this;
+ }
+
+ /// Destroy an Expected<T>.
+ ~Expected() {
+ assertIsChecked();
+ if (!HasError)
+ getStorage()->~storage_type();
+ else
+ getErrorStorage()->~error_type();
+ }
+
+ /// Returns true if this Expected value is in a success state (holding a T),
+ /// and false if this Expected value is in a failure state.
+ explicit operator bool() noexcept {
+ Unchecked = HasError;
+ return !HasError;
+ }
+
+ /// Returns true if this Expected value holds an Error of type error_type.
+ template <typename ErrT> bool isFailureOfType() const noexcept {
+ return HasError && (*getErrorStorage())->template isA<ErrT>();
+ }
+
+ /// Take ownership of the stored error.
+ ///
+ /// If this Expected value is in a success state (holding a T) then this
+ /// method is a no-op and returns Error::success.
+ ///
+ /// If thsi Expected value is in a failure state (holding an Error) then this
+ /// method returns the contained error and leaves this Expected in an
+ /// 'empty' state from which it may be safely destructed but not otherwise
+ /// accessed.
+ Error takeError() noexcept {
+ Unchecked = false;
+ return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
+ }
+
+ /// Returns a pointer to the stored T value.
+ pointer operator->() noexcept {
+ assertIsChecked();
+ return toPointer(getStorage());
+ }
+
+ /// Returns a pointer to the stored T value.
+ const_pointer operator->() const noexcept {
+ assertIsChecked();
+ return toPointer(getStorage());
+ }
+
+ /// Returns a reference to the stored T value.
+ reference operator*() noexcept {
+ assertIsChecked();
+ return *getStorage();
+ }
+
+ /// Returns a reference to the stored T value.
+ const_reference operator*() const noexcept {
+ assertIsChecked();
+ return *getStorage();
+ }
+
+private:
+ template <class T1>
+ static bool compareThisIfSameType(const T1 &a, const T1 &b) noexcept {
+ return &a == &b;
+ }
+
+ template <class T1, class T2>
+ static bool compareThisIfSameType(const T1 &a, const T2 &b) noexcept {
+ return false;
+ }
+
+ template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
+ HasError = Other.HasError;
+ Unchecked = true;
+ Other.Unchecked = false;
+
+ if (!HasError)
+ new (getStorage()) storage_type(std::move(*Other.getStorage()));
+ else
+ new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
+ }
+
+ template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
+ assertIsChecked();
+
+ if (compareThisIfSameType(*this, Other))
+ return;
+
+ this->~Expected();
+ new (this) Expected(std::move(Other));
+ }
+
+ pointer toPointer(pointer Val) noexcept { return Val; }
+
+ const_pointer toPointer(const_pointer Val) const noexcept { return Val; }
+
+ pointer toPointer(wrap *Val) noexcept { return &Val->get(); }
+
+ const_pointer toPointer(const wrap *Val) const noexcept {
+ return &Val->get();
+ }
+
+ storage_type *getStorage() noexcept {
+ assert(!HasError && "Cannot get value when an error exists!");
+ return reinterpret_cast<storage_type *>(&TStorage);
+ }
+
+ const storage_type *getStorage() const noexcept {
+ assert(!HasError && "Cannot get value when an error exists!");
+ return reinterpret_cast<const storage_type *>(&TStorage);
+ }
+
+ error_type *getErrorStorage() noexcept {
+ assert(HasError && "Cannot get error when a value exists!");
+ return reinterpret_cast<error_type *>(&ErrorStorage);
+ }
+
+ const error_type *getErrorStorage() const noexcept {
+ assert(HasError && "Cannot get error when a value exists!");
+ return reinterpret_cast<const error_type *>(&ErrorStorage);
+ }
+
+ void assertIsChecked() noexcept {
+ if (ORC_RT_UNLIKELY(Unchecked)) {
+ fprintf(stderr,
+ "Expected<T> must be checked before access or destruction.\n");
+ abort();
+ }
+ }
+
+ union {
+ alignas(storage_type) char TStorage[sizeof(storage_type)];
+ alignas(error_type) char ErrorStorage[sizeof(error_type)];
+ };
+
+ bool HasError : 1;
+ bool Unchecked : 1;
+};
+
+/// Consume an error without doing anything.
+inline void consumeError(Error Err) {
+ handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
+}
+
+/// Consumes success values. It is a programmatic error to call this function
+/// on a failure value.
+inline void cantFail(Error Err) noexcept {
+#ifndef NDEBUG
+ // TODO: Log unhandled error.
+ if (Err)
+ abort();
+#else
+ Err.operator bool(); // Reset checked flag.
+#endif
+}
+
+/// Auto-unwrap an Expected<T> value in the success state. It is a programmatic
+/// error to call this function on a failure value.
+template <typename T> T cantFail(Expected<T> E) {
+ assert(E && "cantFail called on failure value");
+ consumeError(E.takeError());
+ return std::move(*E);
+}
+
+/// Auto-unwrap an Expected<T> value in the success state. It is a programmatic
+/// error to call this function on a failure value.
+template <typename T> T &cantFail(Expected<T &> E) {
+ assert(E && "cantFail called on failure value");
+ consumeError(E.takeError());
+ return *E;
+}
+
+/// Convert the given error to a string. The error value is consumed in the
+/// process.
+inline std::string toString(Error Err) noexcept {
+ assert(Err && "Cannot convert success value to string");
+ std::string ErrMsg;
+ handleAllErrors(std::move(Err),
+ [&](const ErrorInfoBase &EIB) { ErrMsg = EIB.toString(); });
+ return ErrMsg;
+}
+
+/// Simple string error type.
+class StringError : public ErrorExtends<StringError, ErrorInfoBase> {
+public:
+ static constexpr const char *RTTIName = "orc_rt::StringError";
+
+ StringError(std::string ErrMsg) noexcept : ErrMsg(std::move(ErrMsg)) {}
+ std::string toString() const noexcept override { return ErrMsg; }
+
+private:
+ std::string ErrMsg;
+};
+
+/// APIs for C++ exception interop.
+#if ORC_RT_ENABLE_EXCEPTIONS
+
+class ExceptionError : public ErrorExtends<ExceptionError, ErrorInfoBase> {
+public:
+ static constexpr const char *RTTIName = "orc_rt::ExceptionError";
+
+ ExceptionError(std::exception_ptr E) noexcept : E(std::move(E)) {}
+ std::string toString() const noexcept override;
+ void throwAsException() override { std::rethrow_exception(E); }
+
+private:
+ mutable std::exception_ptr E;
+};
+
+namespace detail {
+
+// In general we need to wrap a return type of T with an Expected.
+template <typename RetT> struct ErrorWrapImpl {
+ typedef Expected<RetT> return_type;
+
+ template <typename OpFn> static return_type run(OpFn &&Op) { return Op(); }
+};
+
+// If the return is already an Expected value then we don't need to add
+// an additional level of wrapping.
+template <typename RetT> struct ErrorWrapImpl<Expected<RetT>> {
+ typedef Expected<RetT> return_type;
+
+ template <typename OpFn> static return_type run(OpFn &&Op) { return Op(); }
+};
+
+// Errors stay errors.
+template <> struct ErrorWrapImpl<Error> {
+ typedef Error return_type;
+
+ template <typename OpFn> static return_type run(OpFn &&Op) { return Op(); }
+};
+
+// void returns become Error returns.
+template <> struct ErrorWrapImpl<void> {
+ typedef Error return_type;
+
+ template <typename OpFn> static return_type run(OpFn &&Op) {
+ Op();
+ return Error::success();
+ }
+};
+
+template <bool /* is_const */, bool /* is_noexcept */, typename RetT>
+struct ErrorWrapImplAdapter : ErrorWrapImpl<RetT> {};
+
+template <typename Callable>
+struct ErrorWrap
+ : public CallableTraitsHelper<detail::ErrorWrapImplAdapter, Callable> {};
+
+} // namespace detail
+
+/// Run the given callback capturing any exceptions thrown into an
+/// Error / Expected failure value.
+///
+/// The return type depends on the return type of the callback:
+/// - void callbacks return Error
+/// - Error callbacks return Error
+/// - Expected<T> callbacks return Expected<T>
+/// - other T callbacks return Expected<T>
+///
+/// If the operation succeeds then...
+/// - If its result is non-void it is returned as an Expected<T> success
+/// value
+/// - If its result is void then Error::success() is retured
+///
+/// If the operation fails then...
+/// - If the exception type is std::unique_ptr<ErrorInfoBase> (i.e. a throw
+/// orc_rt failure value) then an Error is constructed to hold the
+/// failure value.
+/// - If the exception has any other type then it's captured as an
+/// ExceptionError.
+///
+/// The scheme allaws...
+/// 1. orc_rt::Error values that have been converted to exceptions via
+/// Error::throwOnFailure to be converted back into Errors without loss
+/// of dynamic type info.
+/// 2. Other Exceptions caught by this function to be converted back into
+/// exceptions via Error::throwOnFailure without loss of dynamic
+/// type info.
+
+template <typename OpFn>
+typename detail::ErrorWrap<OpFn>::return_type
+runCapturingExceptions(OpFn &&Op) noexcept {
+ try {
+ return detail::ErrorWrap<OpFn>::run(std::forward<OpFn>(Op));
+ } catch (ErrorInfoBase &EIB) {
+ return restore_error(std::move(EIB));
+ } catch (...) {
+ return make_error<ExceptionError>(std::current_exception());
+ }
+}
+
+#endif // ORC_RT_ENABLE_EXCEPTIONS
+
+} // namespace orc_rt
+
+#endif // ORC_RT_SUPPORT_ERROR_H
diff --git a/orc-rt/include/orc-rt/support/ExecutorAddress.h b/orc-rt/include/orc-rt/support/ExecutorAddress.h
index c3603a1708f66..0d1504dcf3e11 100644
--- a/orc-rt/include/orc-rt/support/ExecutorAddress.h
+++ b/orc-rt/include/orc-rt/support/ExecutorAddress.h
@@ -1,233 +1,233 @@
-//===------ ExecutorAddress.h - Executing process address -------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Utilites for representing addresses and address ranges in the executing
-// program that can be shared with an ORC controller.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_SUPPORT_EXECUTORADDRESS_H
-#define ORC_RT_SUPPORT_EXECUTORADDRESS_H
-
-#include "orc-rt/support/span.h"
-
-#include <cassert>
-#include <cstdint>
-#include <functional>
-#include <type_traits>
-
-namespace orc_rt {
-
-using ExecutorAddrDiff = uint64_t;
-
-/// Represents an address in the executor process.
-class ExecutorAddr {
-public:
- /// Return pointer unmodified.
- template <typename T> struct rawPtr {
- T *operator()(T *p) const { return p; }
- };
-
- /// Default wrap function to use on this host.
- template <typename T> using defaultWrap = rawPtr<T>;
-
- /// Default unwrap function to use on this host.
- template <typename T> using defaultUnwrap = rawPtr<T>;
-
- /// Merges a tag into the raw address value:
- /// P' = P | (TagValue << TagOffset).
- class Tag {
- public:
- constexpr Tag(uintptr_t TagValue, uintptr_t TagOffset)
- : TagMask(TagValue << TagOffset) {}
-
- template <typename T> constexpr T *operator()(T *P) {
- return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(P) | TagMask);
- }
-
- private:
- uintptr_t TagMask;
- };
-
- /// Strips a tag of the given length from the given offset within the pointer:
- /// P' = P & ~(((1 << TagLen) -1) << TagOffset)
- class Untag {
- public:
- constexpr Untag(uintptr_t TagLen, uintptr_t TagOffset)
- : UntagMask(~(((uintptr_t(1) << TagLen) - 1) << TagOffset)) {}
-
- template <typename T> constexpr T *operator()(T *P) {
- return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(P) & UntagMask);
- }
-
- private:
- uintptr_t UntagMask;
- };
-
- constexpr ExecutorAddr() noexcept = default;
- explicit constexpr ExecutorAddr(uint64_t Addr) noexcept : Addr(Addr) {}
-
- /// Create an ExecutorAddr from the given pointer.
- template <typename T, typename UnwrapFn = defaultUnwrap<T>>
- static constexpr ExecutorAddr fromPtr(T *Ptr,
- UnwrapFn &&Unwrap = UnwrapFn()) {
- return ExecutorAddr(
- static_cast<uint64_t>(reinterpret_cast<uintptr_t>(Unwrap(Ptr))));
- }
-
- /// Cast this ExecutorAddr to a pointer of the given type.
- template <typename T, typename WrapFn = defaultWrap<std::remove_pointer_t<T>>>
- constexpr std::enable_if_t<std::is_pointer<T>::value, T>
- toPtr(WrapFn &&Wrap = WrapFn()) const {
- uintptr_t IntPtr = static_cast<uintptr_t>(Addr);
- assert(IntPtr == Addr && "ExecutorAddr value out of range for uintptr_t");
- return Wrap(reinterpret_cast<T>(IntPtr));
- }
-
- /// Cast this ExecutorAddr to a pointer of the given function type.
- template <typename T, typename WrapFn = defaultWrap<T>>
- constexpr std::enable_if_t<std::is_function<T>::value, T *>
- toPtr(WrapFn &&Wrap = WrapFn()) const {
- uintptr_t IntPtr = static_cast<uintptr_t>(Addr);
- assert(IntPtr == Addr && "ExecutorAddr value out of range for uintptr_t");
- return Wrap(reinterpret_cast<T *>(IntPtr));
- }
-
- constexpr uint64_t getValue() const noexcept { return Addr; }
- constexpr void setValue(uint64_t Addr) noexcept { this->Addr = Addr; }
- constexpr bool isNull() const noexcept { return Addr == 0; }
-
- constexpr explicit operator bool() const noexcept { return Addr != 0; }
-
- friend constexpr bool operator==(const ExecutorAddr &LHS,
- const ExecutorAddr &RHS) noexcept {
- return LHS.Addr == RHS.Addr;
- }
-
- friend constexpr bool operator!=(const ExecutorAddr &LHS,
- const ExecutorAddr &RHS) noexcept {
- return LHS.Addr != RHS.Addr;
- }
-
- friend constexpr bool operator<(const ExecutorAddr &LHS,
- const ExecutorAddr &RHS) noexcept {
- return LHS.Addr < RHS.Addr;
- }
-
- friend constexpr bool operator<=(const ExecutorAddr &LHS,
- const ExecutorAddr &RHS) noexcept {
- return LHS.Addr <= RHS.Addr;
- }
-
- friend constexpr bool operator>(const ExecutorAddr &LHS,
- const ExecutorAddr &RHS) noexcept {
- return LHS.Addr > RHS.Addr;
- }
-
- friend constexpr bool operator>=(const ExecutorAddr &LHS,
- const ExecutorAddr &RHS) noexcept {
- return LHS.Addr >= RHS.Addr;
- }
-
- constexpr ExecutorAddr &operator++() noexcept {
- ++Addr;
- return *this;
- }
- constexpr ExecutorAddr &operator--() noexcept {
- --Addr;
- return *this;
- }
- constexpr ExecutorAddr operator++(int) noexcept {
- return ExecutorAddr(Addr++);
- }
- constexpr ExecutorAddr operator--(int) noexcept {
- return ExecutorAddr(Addr++);
- }
-
- constexpr ExecutorAddr &operator+=(const ExecutorAddrDiff Delta) noexcept {
- Addr += Delta;
- return *this;
- }
-
- constexpr ExecutorAddr &operator-=(const ExecutorAddrDiff Delta) noexcept {
- Addr -= Delta;
- return *this;
- }
-
-private:
- uint64_t Addr = 0;
-};
-
-/// Subtracting two addresses yields an offset.
-inline constexpr ExecutorAddrDiff operator-(const ExecutorAddr &LHS,
- const ExecutorAddr &RHS) noexcept {
- return ExecutorAddrDiff(LHS.getValue() - RHS.getValue());
-}
-
-/// Adding an offset and an address yields an address.
-inline constexpr ExecutorAddr operator+(const ExecutorAddr &LHS,
- const ExecutorAddrDiff &RHS) noexcept {
- return ExecutorAddr(LHS.getValue() + RHS);
-}
-
-/// Adding an address and an offset yields an address.
-inline constexpr ExecutorAddr operator+(const ExecutorAddrDiff &LHS,
- const ExecutorAddr &RHS) noexcept {
- return ExecutorAddr(LHS + RHS.getValue());
-}
-
-/// Represents an address range in the exceutor process.
-struct ExecutorAddrRange {
- constexpr ExecutorAddrRange() noexcept = default;
- constexpr ExecutorAddrRange(ExecutorAddr Start, ExecutorAddr End) noexcept
- : Start(Start), End(End) {}
- constexpr ExecutorAddrRange(ExecutorAddr Start,
- ExecutorAddrDiff Size) noexcept
- : Start(Start), End(Start + Size) {}
-
- constexpr bool empty() const noexcept { return Start == End; }
- constexpr ExecutorAddrDiff size() const noexcept { return End - Start; }
-
- friend constexpr bool operator==(const ExecutorAddrRange &LHS,
- const ExecutorAddrRange &RHS) noexcept {
- return LHS.Start == RHS.Start && LHS.End == RHS.End;
- }
- friend constexpr bool operator!=(const ExecutorAddrRange &LHS,
- const ExecutorAddrRange &RHS) noexcept {
- return !(LHS == RHS);
- }
- constexpr bool contains(ExecutorAddr Addr) const noexcept {
- return Start <= Addr && Addr < End;
- }
- constexpr bool contains(const ExecutorAddrRange &Other) const noexcept {
- return (Other.Start >= Start && Other.End <= End);
- }
- constexpr bool overlaps(const ExecutorAddrRange &Other) const noexcept {
- return !(Other.End <= Start || End <= Other.Start);
- }
-
- template <typename T> constexpr span<T> toSpan() const noexcept {
- assert(size() % sizeof(T) == 0 &&
- "AddressRange is not a multiple of sizeof(T)");
- return span<T>(Start.toPtr<T *>(), size() / sizeof(T));
- }
-
- ExecutorAddr Start;
- ExecutorAddr End;
-};
-
-} // namespace orc_rt
-
-// Make ExecutorAddr hashable.
-template <> struct std::hash<orc_rt::ExecutorAddr> {
- constexpr size_t operator()(const orc_rt::ExecutorAddr &A) const noexcept {
- return std::hash<uint64_t>()(A.getValue());
- }
-};
-
-#endif // ORC_RT_SUPPORT_EXECUTORADDRESS_H
+//===------ ExecutorAddress.h - Executing process address -------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Utilites for representing addresses and address ranges in the executing
+// program that can be shared with an ORC controller.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ORC_RT_SUPPORT_EXECUTORADDRESS_H
+#define ORC_RT_SUPPORT_EXECUTORADDRESS_H
+
+#include "orc-rt/support/span.h"
+
+#include <cassert>
+#include <cstdint>
+#include <functional>
+#include <type_traits>
+
+namespace orc_rt {
+
+using ExecutorAddrDiff = uint64_t;
+
+/// Represents an address in the executor process.
+class ExecutorAddr {
+public:
+ /// Return pointer unmodified.
+ template <typename T> struct rawPtr {
+ T *operator()(T *p) const { return p; }
+ };
+
+ /// Default wrap function to use on this host.
+ template <typename T> using defaultWrap = rawPtr<T>;
+
+ /// Default unwrap function to use on this host.
+ template <typename T> using defaultUnwrap = rawPtr<T>;
+
+ /// Merges a tag into the raw address value:
+ /// P' = P | (TagValue << TagOffset).
+ class Tag {
+ public:
+ constexpr Tag(uintptr_t TagValue, uintptr_t TagOffset)
+ : TagMask(TagValue << TagOffset) {}
+
+ template <typename T> constexpr T *operator()(T *P) {
+ return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(P) | TagMask);
+ }
+
+ private:
+ uintptr_t TagMask;
+ };
+
+ /// Strips a tag of the given length from the given offset within the pointer:
+ /// P' = P & ~(((1 << TagLen) -1) << TagOffset)
+ class Untag {
+ public:
+ constexpr Untag(uintptr_t TagLen, uintptr_t TagOffset)
+ : UntagMask(~(((uintptr_t(1) << TagLen) - 1) << TagOffset)) {}
+
+ template <typename T> constexpr T *operator()(T *P) {
+ return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(P) & UntagMask);
+ }
+
+ private:
+ uintptr_t UntagMask;
+ };
+
+ constexpr ExecutorAddr() noexcept = default;
+ explicit constexpr ExecutorAddr(uint64_t Addr) noexcept : Addr(Addr) {}
+
+ /// Create an ExecutorAddr from the given pointer.
+ template <typename T, typename UnwrapFn = defaultUnwrap<T>>
+ static constexpr ExecutorAddr fromPtr(T *Ptr,
+ UnwrapFn &&Unwrap = UnwrapFn()) {
+ return ExecutorAddr(
+ static_cast<uint64_t>(reinterpret_cast<uintptr_t>(Unwrap(Ptr))));
+ }
+
+ /// Cast this ExecutorAddr to a pointer of the given type.
+ template <typename T, typename WrapFn = defaultWrap<std::remove_pointer_t<T>>>
+ constexpr std::enable_if_t<std::is_pointer<T>::value, T>
+ toPtr(WrapFn &&Wrap = WrapFn()) const {
+ uintptr_t IntPtr = static_cast<uintptr_t>(Addr);
+ assert(IntPtr == Addr && "ExecutorAddr value out of range for uintptr_t");
+ return Wrap(reinterpret_cast<T>(IntPtr));
+ }
+
+ /// Cast this ExecutorAddr to a pointer of the given function type.
+ template <typename T, typename WrapFn = defaultWrap<T>>
+ constexpr std::enable_if_t<std::is_function<T>::value, T *>
+ toPtr(WrapFn &&Wrap = WrapFn()) const {
+ uintptr_t IntPtr = static_cast<uintptr_t>(Addr);
+ assert(IntPtr == Addr && "ExecutorAddr value out of range for uintptr_t");
+ return Wrap(reinterpret_cast<T *>(IntPtr));
+ }
+
+ constexpr uint64_t getValue() const noexcept { return Addr; }
+ constexpr void setValue(uint64_t Addr) noexcept { this->Addr = Addr; }
+ constexpr bool isNull() const noexcept { return Addr == 0; }
+
+ constexpr explicit operator bool() const noexcept { return Addr != 0; }
+
+ friend constexpr bool operator==(const ExecutorAddr &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return LHS.Addr == RHS.Addr;
+ }
+
+ friend constexpr bool operator!=(const ExecutorAddr &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return LHS.Addr != RHS.Addr;
+ }
+
+ friend constexpr bool operator<(const ExecutorAddr &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return LHS.Addr < RHS.Addr;
+ }
+
+ friend constexpr bool operator<=(const ExecutorAddr &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return LHS.Addr <= RHS.Addr;
+ }
+
+ friend constexpr bool operator>(const ExecutorAddr &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return LHS.Addr > RHS.Addr;
+ }
+
+ friend constexpr bool operator>=(const ExecutorAddr &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return LHS.Addr >= RHS.Addr;
+ }
+
+ constexpr ExecutorAddr &operator++() noexcept {
+ ++Addr;
+ return *this;
+ }
+ constexpr ExecutorAddr &operator--() noexcept {
+ --Addr;
+ return *this;
+ }
+ constexpr ExecutorAddr operator++(int) noexcept {
+ return ExecutorAddr(Addr++);
+ }
+ constexpr ExecutorAddr operator--(int) noexcept {
+ return ExecutorAddr(Addr++);
+ }
+
+ constexpr ExecutorAddr &operator+=(const ExecutorAddrDiff Delta) noexcept {
+ Addr += Delta;
+ return *this;
+ }
+
+ constexpr ExecutorAddr &operator-=(const ExecutorAddrDiff Delta) noexcept {
+ Addr -= Delta;
+ return *this;
+ }
+
+private:
+ uint64_t Addr = 0;
+};
+
+/// Subtracting two addresses yields an offset.
+inline constexpr ExecutorAddrDiff operator-(const ExecutorAddr &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return ExecutorAddrDiff(LHS.getValue() - RHS.getValue());
+}
+
+/// Adding an offset and an address yields an address.
+inline constexpr ExecutorAddr operator+(const ExecutorAddr &LHS,
+ const ExecutorAddrDiff &RHS) noexcept {
+ return ExecutorAddr(LHS.getValue() + RHS);
+}
+
+/// Adding an address and an offset yields an address.
+inline constexpr ExecutorAddr operator+(const ExecutorAddrDiff &LHS,
+ const ExecutorAddr &RHS) noexcept {
+ return ExecutorAddr(LHS + RHS.getValue());
+}
+
+/// Represents an address range in the exceutor process.
+struct ExecutorAddrRange {
+ constexpr ExecutorAddrRange() noexcept = default;
+ constexpr ExecutorAddrRange(ExecutorAddr Start, ExecutorAddr End) noexcept
+ : Start(Start), End(End) {}
+ constexpr ExecutorAddrRange(ExecutorAddr Start,
+ ExecutorAddrDiff Size) noexcept
+ : Start(Start), End(Start + Size) {}
+
+ constexpr bool empty() const noexcept { return Start == End; }
+ constexpr ExecutorAddrDiff size() const noexcept { return End - Start; }
+
+ friend constexpr bool operator==(const ExecutorAddrRange &LHS,
+ const ExecutorAddrRange &RHS) noexcept {
+ return LHS.Start == RHS.Start && LHS.End == RHS.End;
+ }
+ friend constexpr bool operator!=(const ExecutorAddrRange &LHS,
+ const ExecutorAddrRange &RHS) noexcept {
+ return !(LHS == RHS);
+ }
+ constexpr bool contains(ExecutorAddr Addr) const noexcept {
+ return Start <= Addr && Addr < End;
+ }
+ constexpr bool contains(const ExecutorAddrRange &Other) const noexcept {
+ return (Other.Start >= Start && Other.End <= End);
+ }
+ constexpr bool overlaps(const ExecutorAddrRange &Other) const noexcept {
+ return !(Other.End <= Start || End <= Other.Start);
+ }
+
+ template <typename T> constexpr span<T> toSpan() const noexcept {
+ assert(size() % sizeof(T) == 0 &&
+ "AddressRange is not a multiple of sizeof(T)");
+ return span<T>(Start.toPtr<T *>(), size() / sizeof(T));
+ }
+
+ ExecutorAddr Start;
+ ExecutorAddr End;
+};
+
+} // namespace orc_rt
+
+// Make ExecutorAddr hashable.
+template <> struct std::hash<orc_rt::ExecutorAddr> {
+ size_t operator()(const orc_rt::ExecutorAddr &A) const noexcept {
+ return std::hash<uint64_t>()(A.getValue());
+ }
+};
+
+#endif // ORC_RT_SUPPORT_EXECUTORADDRESS_H
diff --git a/orc-rt/include/orc-rt/support/bit.h b/orc-rt/include/orc-rt/support/bit.h
index 47cc3f91383df..d93c634540279 100644
--- a/orc-rt/include/orc-rt/support/bit.h
+++ b/orc-rt/include/orc-rt/support/bit.h
@@ -1,166 +1,189 @@
-//===-------- bit.h - Substitute for future STL bit APIs -------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Substitutes for STL <bit> APIs that aren't available to the ORC runtime yet.
-//
-// TODO: Replace all uses once the respective APIs are available.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef ORC_RT_SUPPORT_BIT_H
-#define ORC_RT_SUPPORT_BIT_H
-
-#include "orc-rt/support/Compiler.h"
-
-#include <cstddef>
-#include <cstdint>
-#include <limits>
-#include <type_traits>
-#if defined(_MSC_VER) && !defined(_DEBUG)
-#include <stdlib.h>
-#endif
-
-#if defined(__linux__) || defined(__GNU__) || defined(__HAIKU__) || \
- defined(__Fuchsia__) || defined(__EMSCRIPTEN__)
-#include <endian.h>
-#elif defined(_AIX)
-#include <sys/machine.h>
-#elif defined(__sun)
-/* Solaris provides _BIG_ENDIAN/_LITTLE_ENDIAN selector in sys/types.h */
-#include <sys/types.h>
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234
-#if defined(_BIG_ENDIAN)
-#define BYTE_ORDER BIG_ENDIAN
-#else
-#define BYTE_ORDER LITTLE_ENDIAN
-#endif
-#elif defined(__MVS__)
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234
-#define BYTE_ORDER BIG_ENDIAN
-#else
-#if !defined(BYTE_ORDER) && !defined(_WIN32)
-#include <machine/endian.h>
-#endif
-#endif
-
-namespace orc_rt {
-
-enum class endian {
- big,
- little,
-#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
- native = big
-#else
- native = little
-#endif
-};
-
-template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
-[[nodiscard]] constexpr T byteswap(T V) noexcept {
- // Implementation taken from llvm/include/ADT/bit.h.
- if constexpr (sizeof(T) == 1) {
- return V;
- } else if constexpr (sizeof(T) == 2) {
- uint16_t UV = V;
-#if defined(_MSC_VER) && !defined(_DEBUG)
- // The DLL version of the runtime lacks these functions (bug!?), but in a
- // release build they're replaced with BSWAP instructions anyway.
- return _byteswap_ushort(UV);
-#else
- uint16_t Hi = UV << 8;
- uint16_t Lo = UV >> 8;
- return Hi | Lo;
-#endif
- } else if constexpr (sizeof(T) == 4) {
- uint32_t UV = V;
-#if ORC_RT_HAS_BUILTIN(__builtin_bswap32)
- return __builtin_bswap32(UV);
-#elif defined(_MSC_VER) && !defined(_DEBUG)
- return _byteswap_ulong(UV);
-#else
- uint32_t Byte0 = UV & 0x000000FF;
- uint32_t Byte1 = UV & 0x0000FF00;
- uint32_t Byte2 = UV & 0x00FF0000;
- uint32_t Byte3 = UV & 0xFF000000;
- return (Byte0 << 24) | (Byte1 << 8) | (Byte2 >> 8) | (Byte3 >> 24);
-#endif
- } else if constexpr (sizeof(T) == 8) {
- uint64_t UV = V;
-#if ORC_RT_HAS_BUILTIN(__builtin_bswap64)
- return __builtin_bswap64(UV);
-#elif defined(_MSC_VER) && !defined(_DEBUG)
- return _byteswap_uint64(UV);
-#else
- uint64_t Hi = byteswap<uint32_t>(UV);
- uint32_t Lo = byteswap<uint32_t>(UV >> 32);
- return (Hi << 32) | Lo;
-#endif
- } else {
- static_assert(!sizeof(T *), "Don't know how to handle the given type.");
- return 0;
- }
-}
-
-/// Calculates the number of leading zeros.
-template <typename T, typename _ = std::enable_if_t<std::is_unsigned_v<T>>>
-[[nodiscard]] constexpr int countl_zero(T Val) noexcept {
- if (!Val)
- return std::numeric_limits<T>::digits;
-
- unsigned ZeroBits = 0;
- for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
- T Tmp = Val >> Shift;
- if (Tmp)
- Val = Tmp;
- else
- ZeroBits |= Shift;
- }
- return ZeroBits;
-}
-
-template <typename T, typename _ = std::enable_if_t<std::is_unsigned_v<T>>>
-[[nodiscard]] constexpr int bit_width(T x) noexcept {
- return std::numeric_limits<T>::digits - countl_zero(x);
-}
-
-template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
-[[nodiscard]] constexpr inline bool has_single_bit(T Value) noexcept {
- return (Value != 0) && ((Value & (Value - 1)) == 0);
-}
-
-template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
-[[nodiscard]] constexpr T rotl(T V, int R) {
- constexpr unsigned N = std::numeric_limits<T>::digits;
-
- static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
- R = R & (N - 1);
-
- if (R == 0)
- return V;
-
- return (V << R) | (V >> (N - R));
-}
-
-template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
-[[nodiscard]] constexpr T rotr(T V, int R) {
- constexpr unsigned N = std::numeric_limits<T>::digits;
-
- static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
- R = R & (N - 1);
-
- if (R == 0)
- return V;
-
- return (V >> R) | (V << (N - R));
-}
-
-} // namespace orc_rt
-
-#endif // ORC_RT_SUPPORT_BIT_H
+//===-------- bit.h - Substitute for future STL bit APIs -------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Substitutes for STL <bit> APIs that aren't available to the ORC runtime yet.
+//
+// TODO: Replace all uses once the respective APIs are available.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef ORC_RT_SUPPORT_BIT_H
+#define ORC_RT_SUPPORT_BIT_H
+
+#include "orc-rt/support/Compiler.h"
+
+#include <cstdint>
+#include <limits>
+#include <type_traits>
+#if defined(_MSC_VER) && !defined(_DEBUG)
+#include <stdlib.h>
+#endif
+
+#if defined(__linux__) || defined(__GNU__) || defined(__HAIKU__) || \
+ defined(__Fuchsia__) || defined(__EMSCRIPTEN__)
+#include <endian.h>
+#elif defined(_AIX)
+#include <sys/machine.h>
+#elif defined(__sun)
+/* Solaris provides _BIG_ENDIAN/_LITTLE_ENDIAN selector in sys/types.h */
+#include <sys/types.h>
+#define BIG_ENDIAN 4321
+#define LITTLE_ENDIAN 1234
+#if defined(_BIG_ENDIAN)
+#define BYTE_ORDER BIG_ENDIAN
+#else
+#define BYTE_ORDER LITTLE_ENDIAN
+#endif
+#elif defined(__MVS__)
+#define BIG_ENDIAN 4321
+#define LITTLE_ENDIAN 1234
+#define BYTE_ORDER BIG_ENDIAN
+#else
+#if !defined(BYTE_ORDER) && !defined(_WIN32)
+#include <machine/endian.h>
+#endif
+#endif
+
+#include "Compiler.h"
+
+namespace orc_rt {
+
+enum class endian {
+ big,
+ little,
+#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
+ native = big
+#else
+ native = little
+#endif
+};
+
+template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
+[[nodiscard]] constexpr T byteswap(T V) noexcept {
+ // Implementation taken from llvm/include/ADT/bit.h.
+ if constexpr (sizeof(T) == 1) {
+ return V;
+ } else if constexpr (sizeof(T) == 2) {
+ uint16_t UV = V;
+#if defined(_MSC_VER) && !defined(_DEBUG)
+ // The DLL version of the runtime lacks these functions (bug!?), but in a
+ // release build they're replaced with BSWAP instructions anyway.
+ return _byteswap_ushort(UV);
+#else
+ uint16_t Hi = UV << 8;
+ uint16_t Lo = UV >> 8;
+ return Hi | Lo;
+#endif
+ } else if constexpr (sizeof(T) == 4) {
+ uint32_t UV = V;
+#if ORC_RT_HAS_BUILTIN(__builtin_bswap32)
+ return __builtin_bswap32(UV);
+#elif defined(_MSC_VER) && !defined(_DEBUG)
+ return _byteswap_ulong(UV);
+#else
+ uint32_t Byte0 = UV & 0x000000FF;
+ uint32_t Byte1 = UV & 0x0000FF00;
+ uint32_t Byte2 = UV & 0x00FF0000;
+ uint32_t Byte3 = UV & 0xFF000000;
+ return (Byte0 << 24) | (Byte1 << 8) | (Byte2 >> 8) | (Byte3 >> 24);
+#endif
+ } else if constexpr (sizeof(T) == 8) {
+ uint64_t UV = V;
+#if ORC_RT_HAS_BUILTIN(__builtin_bswap64)
+ return __builtin_bswap64(UV);
+#elif defined(_MSC_VER) && !defined(_DEBUG)
+ return _byteswap_uint64(UV);
+#else
+ uint64_t Hi = byteswap<uint32_t>(UV);
+ uint32_t Lo = byteswap<uint32_t>(UV >> 32);
+ return (Hi << 32) | Lo;
+#endif
+ } else {
+ static_assert(!sizeof(T *), "Don't know how to handle the given type.");
+ return 0;
+ }
+}
+
+/// Calculates the number of leading zeros.
+template <typename T, typename _ = std::enable_if_t<std::is_unsigned_v<T>>>
+[[nodiscard]] constexpr int countl_zero(T Val) noexcept {
+ if (!Val)
+ return std::numeric_limits<T>::digits;
+
+ unsigned ZeroBits = 0;
+ for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
+ T Tmp = Val >> Shift;
+ if (Tmp)
+ Val = Tmp;
+ else
+ ZeroBits |= Shift;
+ }
+ return ZeroBits;
+}
+
+/// Returns the number of bits needed to represent Value if Value is nonzero.
+/// Returns 0 otherwise.
+///
+/// Ex. bit_width(5) == 3.
+template <typename T> [[nodiscard]] int bit_width(T Value) {
+ static_assert(std::is_unsigned_v<T>,
+ "Only unsigned integral types are allowed.");
+ return std::numeric_limits<T>::digits - orc_rt::countl_zero(Value);
+}
+
+/// Returns the number of bits needed to represent Value if Value is nonzero.
+/// Returns 0 otherwise.
+///
+/// A constexpr version of bit_width.
+///
+/// Ex. bit_width_constexpr(5) == 3.
+template <typename T> [[nodiscard]] constexpr int bit_width_constexpr(T Value) {
+ static_assert(std::is_unsigned_v<T>,
+ "Only unsigned integral types are allowed.");
+ int Width = 0;
+ while (Value > 0) {
+ Value >>= 1;
+ ++Width;
+ }
+ return Width;
+}
+
+template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
+[[nodiscard]] constexpr inline bool has_single_bit(T Value) noexcept {
+ return (Value != 0) && ((Value & (Value - 1)) == 0);
+}
+
+template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
+[[nodiscard]] constexpr T rotl(T V, int R) {
+ constexpr unsigned N = std::numeric_limits<T>::digits;
+
+ static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
+ R = R & (N - 1);
+
+ if (R == 0)
+ return V;
+
+ return (V << R) | (V >> (N - R));
+}
+
+template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
+[[nodiscard]] constexpr T rotr(T V, int R) {
+ constexpr unsigned N = std::numeric_limits<T>::digits;
+
+ static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
+ R = R & (N - 1);
+
+ if (R == 0)
+ return V;
+
+ return (V >> R) | (V << (N - R));
+}
+
+} // namespace orc_rt
+
+#endif // ORC_RT_SUPPORT_BIT_H
diff --git a/orc-rt/lib/bedrock/CMakeLists.txt b/orc-rt/lib/bedrock/CMakeLists.txt
index 0d8e41d4633d8..097d9dad57240 100644
--- a/orc-rt/lib/bedrock/CMakeLists.txt
+++ b/orc-rt/lib/bedrock/CMakeLists.txt
@@ -1,108 +1,107 @@
-
-set(ORC_RT_BEDROCK_SOURCES
- BootstrapInfo.cpp
- ExecutorProcessInfo.cpp
- GDBJITRegistrar.cpp
- InProcessControllerAccess.cpp
- NativeDylibManager.cpp
- Service.cpp
- Session.cpp
- SimpleNativeMemoryMap.cpp
- SimpleSymbolTable.cpp
- StandaloneMachOUnwindInfoRegistrar.cpp
- ThreadPoolRunner.cpp
- sps/AllSPSCI.cpp
- sps/CallSPSCI.cpp
- sps/GDBJITRegistrarSPSCI.cpp
- sps/MemoryAccessSPSCI.cpp
- sps/NativeDylibManagerSPSCI.cpp
- sps/SimpleNativeMemoryMapSPSCI.cpp
- sps/SimpleRemoteCA.cpp
- sps/StandaloneMachOUnwindInfoRegistrarSPSCI.cpp
- )
-
-# System implementations are composed, not merely selected: a target gets one
-# source list per capability it has. POSIX systems share sys/posix/, and add
-# their OS-specific list on top; Windows shares nothing with them.
-#
-# A file belongs in a shared list only if it is uniform across every member of
-# it. Where a function needs an OS conditional, it moves down into the
-# per-OS lists instead of growing an #ifdef here -- or, if it wants to inline,
-# becomes a header with per-system definitions under
-# include/orc-rt-internal/support/ (see support/sys/CacheControl.h and
-# support/sys/Errno.h).
-#
-# These live in Bedrock rather than Support because Support is embedded into
-# SPIRE, which is JIT-linked on every execution of every JIT'd program. SPIRE
-# reaches these services through Bedrock's C API instead of carrying its own
-# copy of them.
-
-set(ORC_RT_BEDROCK_POSIX_SOURCES
- sys/posix/DynamicLibrary.cpp
- sys/posix/Memory.cpp
- sys/posix/PageSize.cpp
- sys/posix/SocketHandle.cpp
-)
-
-set(ORC_RT_BEDROCK_DARWIN_SOURCES
- sys/darwin/CPUFeatures.cpp
- sys/darwin/TargetTriple.cpp
-)
-
-set(ORC_RT_BEDROCK_LINUX_SOURCES
- sys/linux/CPUFeatures.cpp
- sys/linux/TargetTriple.cpp
-)
-
-# TODO: Windows has no counterparts for the sys/posix/ sources yet
-# (DynamicLibrary, Memory, PageSize, SocketHandle), so Windows builds are
-# incomplete.
-set(ORC_RT_BEDROCK_WINDOWS_SOURCES
- sys/windows/CPUFeatures.cpp
- sys/windows/TargetTriple.cpp
-)
-
-if (APPLE)
- list(APPEND ORC_RT_BEDROCK_SOURCES
- ${ORC_RT_BEDROCK_POSIX_SOURCES} ${ORC_RT_BEDROCK_DARWIN_SOURCES})
-elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux")
- list(APPEND ORC_RT_BEDROCK_SOURCES
- ${ORC_RT_BEDROCK_POSIX_SOURCES} ${ORC_RT_BEDROCK_LINUX_SOURCES})
-elseif (WIN32)
- list(APPEND ORC_RT_BEDROCK_SOURCES ${ORC_RT_BEDROCK_WINDOWS_SOURCES})
-else()
- message(WARNING
- "orc-rt: no system implementation for ${CMAKE_SYSTEM_NAME}; "
- "add an orc-rt/lib/bedrock/sys/<system>/ directory and compose it above")
-endif()
-
-add_library(orc-rt-bedrock-objects OBJECT ${ORC_RT_BEDROCK_SOURCES})
-
-set_target_properties(orc-rt-bedrock-objects PROPERTIES
- POSITION_INDEPENDENT_CODE ${ORC_RT_ENABLE_PIC}
- C_VISIBILITY_PRESET hidden
- CXX_VISIBILITY_PRESET hidden
- VISIBILITY_INLINES_HIDDEN ON
-)
-
-target_link_libraries(orc-rt-bedrock-objects PUBLIC orc-rt-headers)
-
-# Apply RTTI and exceptions compile flags
-target_compile_options(orc-rt-bedrock-objects PRIVATE ${ORC_RT_COMPILE_FLAGS})
-
-# The shipped library: Bedrock's objects plus Support's (Support is never
-# shipped on its own).
-add_library(orc-rt-bedrock ${ORC_RT_BEDROCK_LIBRARY_TYPE})
-
-target_link_libraries(orc-rt-bedrock PUBLIC orc-rt-headers)
-
-target_link_libraries(orc-rt-bedrock
- PRIVATE $<BUILD_INTERFACE:orc-rt-bedrock-objects>
- $<BUILD_INTERFACE:orc-rt-support-objects>)
-
-# TODO: Use common runtimes infrastructure for output and install paths
-install(TARGETS orc-rt-bedrock
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- COMPONENT OrcRT_Development
- PUBLIC_HEADER DESTINATION include COMPONENT OrcRT_Development
-)
+
+set(ORC_RT_BEDROCK_SOURCES
+ BootstrapInfo.cpp
+ ExecutorProcessInfo.cpp
+ GDBJITRegistrar.cpp
+ InProcessControllerAccess.cpp
+ NativeDylibManager.cpp
+ Service.cpp
+ Session.cpp
+ SimpleNativeMemoryMap.cpp
+ SimpleSymbolTable.cpp
+ ThreadPoolRunner.cpp
+ sps/AllSPSCI.cpp
+ sps/CallSPSCI.cpp
+ sps/GDBJITRegistrarSPSCI.cpp
+ sps/MemoryAccessSPSCI.cpp
+ sps/NativeDylibManagerSPSCI.cpp
+ sps/SimpleNativeMemoryMapSPSCI.cpp
+ sps/SimpleRemoteCA.cpp
+ )
+
+# System implementations are composed, not merely selected: a target gets one
+# source list per capability it has. POSIX systems share sys/posix/, and add
+# their OS-specific list on top; Windows shares nothing with them.
+#
+# A file belongs in a shared list only if it is uniform across every member of
+# it. Where a function needs an OS conditional, it moves down into the
+# per-OS lists instead of growing an #ifdef here -- or, if it wants to inline,
+# becomes a header with per-system definitions under
+# include/orc-rt-internal/support/ (see support/sys/CacheControl.h and
+# support/sys/Errno.h).
+#
+# These live in Bedrock rather than Support because Support is embedded into
+# SPIRE, which is JIT-linked on every execution of every JIT'd program. SPIRE
+# reaches these services through Bedrock's C API instead of carrying its own
+# copy of them.
+
+set(ORC_RT_BEDROCK_POSIX_SOURCES
+ sys/posix/DynamicLibrary.cpp
+ sys/posix/Memory.cpp
+ sys/posix/PageSize.cpp
+ sys/posix/SocketHandle.cpp
+)
+
+set(ORC_RT_BEDROCK_DARWIN_SOURCES
+ sys/darwin/CPUFeatures.cpp
+ sys/darwin/TargetTriple.cpp
+ StandaloneMachOUnwindInfoRegistrar.cpp
+ sps/StandaloneMachOUnwindInfoRegistrarSPSCI.cpp
+)
+
+set(ORC_RT_BEDROCK_LINUX_SOURCES
+ sys/linux/CPUFeatures.cpp
+ sys/linux/TargetTriple.cpp
+)
+
+set(ORC_RT_BEDROCK_WINDOWS_SOURCES
+ sys/windows/DynamicLibrary.cpp
+ sys/windows/Memory.cpp
+ sys/windows/CPUFeatures.cpp
+ sys/windows/TargetTriple.cpp
+)
+
+if (APPLE)
+ list(APPEND ORC_RT_BEDROCK_SOURCES
+ ${ORC_RT_BEDROCK_POSIX_SOURCES} ${ORC_RT_BEDROCK_DARWIN_SOURCES})
+elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ list(APPEND ORC_RT_BEDROCK_SOURCES
+ ${ORC_RT_BEDROCK_POSIX_SOURCES} ${ORC_RT_BEDROCK_LINUX_SOURCES})
+elseif (WIN32)
+ list(APPEND ORC_RT_BEDROCK_SOURCES ${ORC_RT_BEDROCK_WINDOWS_SOURCES})
+else()
+ message(WARNING
+ "orc-rt: no system implementation for ${CMAKE_SYSTEM_NAME}; "
+ "add an orc-rt/lib/bedrock/sys/<system>/ directory and compose it above")
+endif()
+
+add_library(orc-rt-bedrock-objects OBJECT ${ORC_RT_BEDROCK_SOURCES})
+
+set_target_properties(orc-rt-bedrock-objects PROPERTIES
+ POSITION_INDEPENDENT_CODE ${ORC_RT_ENABLE_PIC}
+ C_VISIBILITY_PRESET hidden
+ CXX_VISIBILITY_PRESET hidden
+ VISIBILITY_INLINES_HIDDEN ON
+)
+
+target_link_libraries(orc-rt-bedrock-objects PUBLIC orc-rt-headers)
+
+# Apply RTTI and exceptions compile flags
+target_compile_options(orc-rt-bedrock-objects PRIVATE ${ORC_RT_COMPILE_FLAGS})
+
+# The shipped library: Bedrock's objects plus Support's (Support is never
+# shipped on its own).
+add_library(orc-rt-bedrock ${ORC_RT_BEDROCK_LIBRARY_TYPE})
+
+target_link_libraries(orc-rt-bedrock PUBLIC orc-rt-headers)
+
+target_link_libraries(orc-rt-bedrock
+ PRIVATE $<BUILD_INTERFACE:orc-rt-bedrock-objects>
+ $<BUILD_INTERFACE:orc-rt-support-objects>)
+
+# TODO: Use common runtimes infrastructure for output and install paths
+install(TARGETS orc-rt-bedrock
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ COMPONENT OrcRT_Development
+ PUBLIC_HEADER DESTINATION include COMPONENT OrcRT_Development
+)
diff --git a/orc-rt/lib/bedrock/sps/AllSPSCI.cpp b/orc-rt/lib/bedrock/sps/AllSPSCI.cpp
index 0148f7615b47d..c7bfb76613fc9 100644
--- a/orc-rt/lib/bedrock/sps/AllSPSCI.cpp
+++ b/orc-rt/lib/bedrock/sps/AllSPSCI.cpp
@@ -1,39 +1,42 @@
-//===- AllSPSCI.cpp -------------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Implementation of sps_ci::addAll.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/bedrock/sps/AllSPSCI.h"
-#include "orc-rt/bedrock/sps/CallSPSCI.h"
-#include "orc-rt/bedrock/sps/GDBJITRegistrarSPSCI.h"
-#include "orc-rt/bedrock/sps/MemoryAccessSPSCI.h"
-#include "orc-rt/bedrock/sps/NativeDylibManagerSPSCI.h"
-#include "orc-rt/bedrock/sps/SimpleNativeMemoryMapSPSCI.h"
-#include "orc-rt/bedrock/sps/StandaloneMachOUnwindInfoRegistrarSPSCI.h"
-
-namespace orc_rt::sps_ci {
-
-Error addAll(SimpleSymbolTable &ST) {
- using AdderFn = Error (*)(SimpleSymbolTable &);
- AdderFn Adders[] = {addCall,
- addGDBJITRegistrar,
- addMemoryAccess,
- addNativeDylibManager,
- addSimpleNativeMemoryMap,
- addStandaloneMachOUnwindInfoRegistrar};
-
- for (auto *Adder : Adders)
- if (auto Err = Adder(ST))
- return Err;
-
- return Error::success();
-}
-
-} // namespace orc_rt::sps_ci
+//===- AllSPSCI.cpp -------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Implementation of sps_ci::addAll.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/bedrock/sps/AllSPSCI.h"
+#include "orc-rt/bedrock/sps/CallSPSCI.h"
+#include "orc-rt/bedrock/sps/GDBJITRegistrarSPSCI.h"
+#include "orc-rt/bedrock/sps/MemoryAccessSPSCI.h"
+#include "orc-rt/bedrock/sps/NativeDylibManagerSPSCI.h"
+#include "orc-rt/bedrock/sps/SimpleNativeMemoryMapSPSCI.h"
+#include "orc-rt/bedrock/sps/StandaloneMachOUnwindInfoRegistrarSPSCI.h"
+
+namespace orc_rt::sps_ci {
+
+Error addAll(SimpleSymbolTable &ST) {
+ using AdderFn = Error (*)(SimpleSymbolTable &);
+ AdderFn Adders[] = {addCall,
+ addGDBJITRegistrar,
+ addMemoryAccess,
+ addNativeDylibManager,
+ addSimpleNativeMemoryMap,
+ #if defined(__APPLE__)
+ addStandaloneMachOUnwindInfoRegistrar,
+ #endif
+ };
+
+ for (auto *Adder : Adders)
+ if (auto Err = Adder(ST))
+ return Err;
+
+ return Error::success();
+}
+
+} // namespace orc_rt::sps_ci
diff --git a/orc-rt/lib/bedrock/sys/windows/DynamicLibrary.cpp b/orc-rt/lib/bedrock/sys/windows/DynamicLibrary.cpp
new file mode 100644
index 0000000000000..2cda3f42ec3b7
--- /dev/null
+++ b/orc-rt/lib/bedrock/sys/windows/DynamicLibrary.cpp
@@ -0,0 +1,30 @@
+//===- DynamicLibrary.cpp -------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt-internal/bedrock/sys/DynamicLibrary.h"
+
+namespace orc_rt::sys {
+
+void *globalLookupHandle() {
+ return nullptr;
+}
+
+Expected<void *> loadLibrary(const std::string &) {
+ return make_error<StringError>("Windows loadLibrary not implemented");
+}
+
+Error unloadLibrary(void *) {
+ return make_error<StringError>("Windows unloadLibrary not implemented");
+}
+
+std::vector<std::optional<void *>>
+lookupLibrarySymbols(void *, const std::vector<std::string> &Names) {
+ return std::vector<std::optional<void *>>(Names.size(), std::nullopt);
+}
+
+} // namespace orc_rt::sys
diff --git a/orc-rt/lib/bedrock/sys/windows/Memory.cpp b/orc-rt/lib/bedrock/sys/windows/Memory.cpp
new file mode 100644
index 0000000000000..df93699794b97
--- /dev/null
+++ b/orc-rt/lib/bedrock/sys/windows/Memory.cpp
@@ -0,0 +1,29 @@
+//===- Memory.cpp ----------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt-internal/bedrock/sys/Memory.h"
+
+namespace orc_rt::sys {
+
+Expected<uint64_t> detectPageSize() {
+ return make_error<StringError>("Windows detectPageSize not implemented");
+}
+
+Expected<void *> reserveMemory(uint64_t) {
+ return make_error<StringError>("Windows reserveMemory not implemented");
+}
+
+Error releaseMemory(void *, uint64_t) {
+ return make_error<StringError>("Windows releaseMemory not implemented");
+}
+
+Error protectMemory(void *, uint64_t, MemProt) {
+ return make_error<StringError>("Windows protectMemory not implemented");
+}
+
+} // namespace orc_rt::sys
diff --git a/orc-rt/test/unit/CMakeLists.txt b/orc-rt/test/unit/CMakeLists.txt
index f750799ad75bf..5947f718fbacc 100644
--- a/orc-rt/test/unit/CMakeLists.txt
+++ b/orc-rt/test/unit/CMakeLists.txt
@@ -1,137 +1,162 @@
-add_custom_target(OrcRTUnitTests)
-set_target_properties(OrcRTUnitTests PROPERTIES FOLDER "orc-rt/Tests")
-
-if (NOT TARGET llvm_gtest)
- message(WARNING "orc-rt unittests disabled due to GTest being unavailable; "
- "Try LLVM_INSTALL_GTEST=ON for the LLVM build")
- return ()
-endif ()
-
-# Adds a unit test suite. Sources come first; LINK_LIBS names the object
-# libraries the suite links and must come last.
-function(add_orc_rt_unittest test_name)
- cmake_parse_arguments(ARG "" "" "LINK_LIBS" ${ARGN})
- add_unittest(OrcRTUnitTests ${test_name} ${ARG_UNPARSED_ARGUMENTS}
- DISABLE_LLVM_LINK_LLVM_DYLIB)
- target_compile_options(${test_name} PRIVATE ${ORC_RT_COMPILE_FLAGS})
- # Shared test helpers (CommonTestUtils.h, DirectCaller.h, ...) live at the
- # root of this directory, so tests in the layer subdirectories can include
- # them by bare name.
- target_include_directories(${test_name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
- target_link_libraries(${test_name} PRIVATE ${ARG_LINK_LIBS})
-endfunction()
-
-# SupportTests links the Support objects and nothing else, so a new
-# support-to-bedrock dependency shows up here as a link error rather than going
-# unnoticed. BedrockTests links both, Bedrock being a Support client.
-add_orc_rt_unittest(SupportTests
- support/AllocActionTest.cpp
- support/BitmaskEnumTest.cpp
- support/CAPICompileTest.c
- support/CCallbackTest.cpp
- support/CallableTraitsHelperTest.cpp
- support/CompilerTest.cpp
- support/EndianTest.cpp
- support/ErrorCAPITest.cpp
- support/ErrorExceptionInteropTest.cpp
- support/ErrorTest.cpp
- support/ExecutorAddressTest.cpp
- support/IntervalMapTest.cpp
- support/IntervalSetTest.cpp
- support/LockedAccessTest.cpp
- support/LoggingTest.cpp
- support/MacroUtilsTest.cpp
- support/ManglingTest.cpp
- support/MemoryFlagsTest.cpp
- support/ProxyTest.cpp
- support/RTTICrossDylibTest.cpp
- support/RTTITest.cpp
- support/StringExtrasTest.cpp
- support/StringPoolTest.cpp
- support/WrapperFunctionBufferTest.cpp
- support/bind-test.cpp
- support/bit-test.cpp
- support/iterator_range-test.cpp
- support/move_only_function-test.cpp
- support/scope_exit-test.cpp
- support/span-test.cpp
-
- support/sps/SPSAllocActionTest.cpp
- support/sps/SPSMemoryFlagsTest.cpp
- support/sps/SPSWrapperFunctionBufferTest.cpp
- support/sps/SPSWrapperFunctionTest.cpp
- support/sps/SimplePackedSerializationTest.cpp
-
- support/sys/ErrnoTest.cpp
-
- tools/OptionParserTest.cpp
-
- LINK_LIBS orc-rt-support-objects
- )
-
-# Per-system test helpers, composed the way lib/ composes its per-system
-# implementations; see the note in lib/bedrock/CMakeLists.txt. Tests of portable
-# APIs stay in the shared list and reach the system through these.
-set(ORC_RT_BEDROCK_TEST_POSIX_SOURCES
- bedrock/sys/posix/SocketTestUtils.cpp
-)
-
-if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
- set(ORC_RT_BEDROCK_TEST_SYS_SOURCES ${ORC_RT_BEDROCK_TEST_POSIX_SOURCES})
-else()
- # No list yet, so tests needing a socket will fail to link.
- set(ORC_RT_BEDROCK_TEST_SYS_SOURCES)
-endif()
-
-add_orc_rt_unittest(BedrockTests
- bedrock/BootstrapInfoTest.cpp
- bedrock/ExecutorProcessInfoTest.cpp
- bedrock/InProcessControllerAccessTest.cpp
- bedrock/NativeDylibManagerTest.cpp
- bedrock/QueueingRunnerTest.cpp
- bedrock/SessionTest.cpp
- bedrock/SimpleNativeMemoryMapTest.cpp
- bedrock/SimpleSymbolTableTest.cpp
- bedrock/SocketHandleTest.cpp
- bedrock/StandaloneMachOUnwindInfoRegistrarTest.cpp
- bedrock/TaskGroupTest.cpp
- bedrock/ThreadPoolRunnerTest.cpp
-
- bedrock/sps/CallSPSCITest.cpp
- bedrock/sps/MemoryAccessSPSCITest.cpp
- bedrock/sps/NativeDylibManagerSPSCITest.cpp
- bedrock/sps/SimpleNativeMemoryMapSPSCITest.cpp
- bedrock/sps/SimpleRemoteCATest.cpp
-
- bedrock/sys/CPUFeaturesTest.cpp
- bedrock/sys/TargetTripleTest.cpp
-
- ${ORC_RT_BEDROCK_TEST_SYS_SOURCES}
-
- LINK_LIBS orc-rt-bedrock-objects orc-rt-support-objects
- )
-
-# Build a shared library for NativeDylibManager tests.
-add_library(NativeDylibManagerTestLib SHARED
- Inputs/NativeDylibManagerTestLib.cpp)
-set_target_properties(NativeDylibManagerTestLib PROPERTIES
- PREFIX "")
-target_compile_definitions(BedrockTests PRIVATE
- "NDM_TEST_LIB_PATH=\"$<TARGET_FILE:NativeDylibManagerTestLib>\"")
-add_dependencies(BedrockTests NativeDylibManagerTestLib)
-
-# Build a shared library for RTTICrossDylibTest. It links its own copy of the
-# runtime objects, giving it a LibraryID distinct from SupportTests's, so the
-# test exercises RTTI identity across a real library boundary rather than
-# simulating one within a single binary. SupportTests links it directly, the
-# same way any other consumer of orc-rt would.
-add_library(RTTICrossDylibTestLib SHARED
- Inputs/RTTICrossDylibTestLib.cpp)
-set_target_properties(RTTICrossDylibTestLib PROPERTIES
- PREFIX ""
- CXX_VISIBILITY_PRESET hidden
- VISIBILITY_INLINES_HIDDEN ON)
-target_compile_options(RTTICrossDylibTestLib PRIVATE ${ORC_RT_COMPILE_FLAGS})
-target_link_libraries(RTTICrossDylibTestLib
- PRIVATE orc-rt-bedrock-objects orc-rt-support-objects)
-target_link_libraries(SupportTests PRIVATE RTTICrossDylibTestLib)
+add_custom_target(OrcRTUnitTests)
+set_target_properties(OrcRTUnitTests PROPERTIES FOLDER "orc-rt/Tests")
+
+if (NOT TARGET llvm_gtest)
+ message(WARNING "orc-rt unittests disabled due to GTest being unavailable; "
+ "Try LLVM_INSTALL_GTEST=ON for the LLVM build")
+ return ()
+endif ()
+
+set(LLVM_REQUIRES_RTTI ON)
+set(LLVM_REQUIRES_EH ON)
+
+# Adds a unit test suite. Sources come first; LINK_LIBS names the object
+# libraries the suite links and must come last.
+function(add_orc_rt_unittest test_name)
+ cmake_parse_arguments(ARG "" "" "LINK_LIBS" ${ARGN})
+ add_unittest(OrcRTUnitTests ${test_name} ${ARG_UNPARSED_ARGUMENTS}
+ DISABLE_LLVM_LINK_LLVM_DYLIB)
+ target_compile_options(${test_name} PRIVATE ${ORC_RT_COMPILE_FLAGS})
+
+ # Shared test helpers (CommonTestUtils.h, DirectCaller.h, ...) live at the
+ # root of this directory, so tests in the layer subdirectories can include
+ # them by bare name.
+ target_include_directories(${test_name} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
+ target_link_libraries(${test_name} PRIVATE ${ARG_LINK_LIBS})
+endfunction()
+
+if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ set(ORC_RT_SUPPORT_TEST_SYS_SOURCES
+ support/sys/ErrnoTest.cpp
+ )
+else()
+ set(ORC_RT_SUPPORT_TEST_SYS_SOURCES)
+endif()
+
+# SupportTests links the Support objects and nothing else, so a new
+# support-to-bedrock dependency shows up here as a link error rather than going
+# unnoticed. BedrockTests links both, Bedrock being a Support client.
+add_orc_rt_unittest(SupportTests
+ support/AllocActionTest.cpp
+ support/BitmaskEnumTest.cpp
+ support/CAPICompileTest.c
+ support/CCallbackTest.cpp
+ support/CallableTraitsHelperTest.cpp
+ support/CompilerTest.cpp
+ support/EndianTest.cpp
+ support/ErrorCAPITest.cpp
+ support/ErrorExceptionInteropTest.cpp
+ support/ErrorTest.cpp
+ support/ExecutorAddressTest.cpp
+ support/IntervalMapTest.cpp
+ support/IntervalSetTest.cpp
+ support/LockedAccessTest.cpp
+ support/LoggingTest.cpp
+ support/MacroUtilsTest.cpp
+ support/ManglingTest.cpp
+ support/MemoryFlagsTest.cpp
+ support/ProxyTest.cpp
+ support/RTTICrossDylibTest.cpp
+ support/RTTITest.cpp
+ support/StringExtrasTest.cpp
+ support/StringPoolTest.cpp
+ support/WrapperFunctionBufferTest.cpp
+ support/bind-test.cpp
+ support/bit-test.cpp
+ support/iterator_range-test.cpp
+ support/move_only_function-test.cpp
+ support/scope_exit-test.cpp
+ support/span-test.cpp
+
+ support/sps/SPSAllocActionTest.cpp
+ support/sps/SPSMemoryFlagsTest.cpp
+ support/sps/SPSWrapperFunctionBufferTest.cpp
+ support/sps/SPSWrapperFunctionTest.cpp
+ support/sps/SimplePackedSerializationTest.cpp
+
+ ${ORC_RT_SUPPORT_TEST_SYS_SOURCES}
+
+ tools/OptionParserTest.cpp
+
+ LINK_LIBS orc-rt-support-objects
+ )
+
+# Per-system test helpers, composed the way lib/ composes its per-system
+# implementations; see the note in lib/bedrock/CMakeLists.txt. Tests of portable
+# APIs stay in the shared list and reach the system through these.
+set(ORC_RT_BEDROCK_TEST_POSIX_SOURCES
+ bedrock/SocketHandleTest.cpp
+ bedrock/sys/posix/SocketTestUtils.cpp
+ )
+
+if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ set(ORC_RT_BEDROCK_TEST_SYS_SOURCES ${ORC_RT_BEDROCK_TEST_POSIX_SOURCES})
+else()
+ # No list yet, so tests needing a socket will fail to link.
+ set(ORC_RT_BEDROCK_TEST_SYS_SOURCES)
+endif()
+
+if (APPLE)
+ set(ORC_RT_BEDROCK_TEST_APPLE_SOURCES
+ bedrock/StandaloneMachOUnwindInfoRegistrarTest.cpp
+ )
+else()
+ set(ORC_RT_BEDROCK_TEST_APPLE_SOURCES)
+endif()
+
+add_orc_rt_unittest(BedrockTests
+ bedrock/BootstrapInfoTest.cpp
+ bedrock/ExecutorProcessInfoTest.cpp
+ bedrock/InProcessControllerAccessTest.cpp
+ bedrock/NativeDylibManagerTest.cpp
+ bedrock/QueueingRunnerTest.cpp
+ bedrock/SessionTest.cpp
+ bedrock/SimpleNativeMemoryMapTest.cpp
+ bedrock/SimpleSymbolTableTest.cpp
+ bedrock/TaskGroupTest.cpp
+ bedrock/ThreadPoolRunnerTest.cpp
+
+ bedrock/sps/CallSPSCITest.cpp
+ bedrock/sps/MemoryAccessSPSCITest.cpp
+ bedrock/sps/NativeDylibManagerSPSCITest.cpp
+ bedrock/sps/SimpleNativeMemoryMapSPSCITest.cpp
+ bedrock/sps/SimpleRemoteCATest.cpp
+
+ bedrock/sys/CPUFeaturesTest.cpp
+ bedrock/sys/TargetTripleTest.cpp
+
+ ${ORC_RT_BEDROCK_TEST_SYS_SOURCES}
+ ${ORC_RT_BEDROCK_TEST_APPLE_SOURCES}
+
+ LINK_LIBS orc-rt-bedrock-objects orc-rt-support-objects
+ )
+
+# Build a shared library for NativeDylibManager tests.
+add_library(NativeDylibManagerTestLib SHARED
+ Inputs/NativeDylibManagerTestLib.cpp)
+set_target_properties(NativeDylibManagerTestLib PROPERTIES
+ PREFIX ""
+ FOLDER "orc-rt/Tests")
+target_compile_options(NativeDylibManagerTestLib PRIVATE
+ ${ORC_RT_COMPILE_FLAGS})
+target_compile_definitions(BedrockTests PRIVATE
+ "NDM_TEST_LIB_PATH=\"$<TARGET_FILE:NativeDylibManagerTestLib>\"")
+add_dependencies(BedrockTests NativeDylibManagerTestLib)
+
+# Build a shared library for RTTICrossDylibTest. It links its own copy of the
+# runtime objects, giving it a LibraryID distinct from SupportTests's, so the
+# test exercises RTTI identity across a real library boundary rather than
+# simulating one within a single binary. SupportTests links it directly, the
+# same way any other consumer of orc-rt would.
+add_library(RTTICrossDylibTestLib SHARED
+ Inputs/RTTICrossDylibTestLib.cpp)
+set_target_properties(RTTICrossDylibTestLib PROPERTIES
+ PREFIX ""
+ CXX_VISIBILITY_PRESET hidden
+ VISIBILITY_INLINES_HIDDEN ON
+ WINDOWS_EXPORT_ALL_SYMBOLS ON
+ FOLDER "orc-rt/Tests")
+target_compile_options(RTTICrossDylibTestLib PRIVATE ${ORC_RT_COMPILE_FLAGS})
+target_link_libraries(RTTICrossDylibTestLib
+ PRIVATE orc-rt-bedrock-objects orc-rt-support-objects)
+target_link_libraries(SupportTests PRIVATE RTTICrossDylibTestLib)
diff --git a/orc-rt/test/unit/Inputs/RTTICrossDylibTestLib.cpp b/orc-rt/test/unit/Inputs/RTTICrossDylibTestLib.cpp
index a3612e75bb04e..765df348010ab 100644
--- a/orc-rt/test/unit/Inputs/RTTICrossDylibTestLib.cpp
+++ b/orc-rt/test/unit/Inputs/RTTICrossDylibTestLib.cpp
@@ -1,33 +1,33 @@
-// A minimal shared library for RTTICrossDylibTest: constructs a
-// CrossDylibTestError using its own linked copy of orc-rt's RTTI state, so
-// that the test binary can confirm that isA<>() and casting still work when
-// the object's RTTIRoot::LibraryID differs from the caller's.
-
-#include "RTTICrossDylibTestLib.h"
-#include "RTTICrossDylibTestError.h"
-
-#if defined(_WIN32)
-#define TEST_EXPORT __declspec(dllexport)
-#else
-#define TEST_EXPORT __attribute__((visibility("default")))
-#endif
-
-using namespace orc_rt;
-using orc_rt_test::CrossDylibTestError;
-
-extern "C" TEST_EXPORT ErrorInfoBase *rttiCrossDylibTest_makeError(int Code) {
- return new CrossDylibTestError(Code);
-}
-
-extern "C" TEST_EXPORT void rttiCrossDylibTest_destroyError(ErrorInfoBase *E) {
- delete E;
-}
-
-// Exposes this library's own RTTIRoot::LibraryID, so the test binary can
-// confirm the two libraries are genuinely using distinct identities (i.e.
-// that the test below exercises the cross-library strcmp path, not the
-// same-library pointer-equality fast path).
-extern "C" TEST_EXPORT const void *rttiCrossDylibTest_libraryID() {
- CrossDylibTestError E(0);
- return E.libraryID();
-}
+// A minimal shared library for RTTICrossDylibTest: constructs a
+// CrossDylibTestError using its own linked copy of orc-rt's RTTI state, so
+// that the test binary can confirm that isA<>() and casting still work when
+// the object's RTTIRoot::LibraryID differs from the caller's.
+
+#include "RTTICrossDylibTestLib.h"
+#include "RTTICrossDylibTestError.h"
+
+#if defined(_WIN32)
+#define TEST_EXPORT
+#else
+#define TEST_EXPORT __attribute__((visibility("default")))
+#endif
+
+using namespace orc_rt;
+using orc_rt_test::CrossDylibTestError;
+
+extern "C" TEST_EXPORT ErrorInfoBase *rttiCrossDylibTest_makeError(int Code) {
+ return new CrossDylibTestError(Code);
+}
+
+extern "C" TEST_EXPORT void rttiCrossDylibTest_destroyError(ErrorInfoBase *E) {
+ delete E;
+}
+
+// Exposes this library's own RTTIRoot::LibraryID, so the test binary can
+// confirm the two libraries are genuinely using distinct identities (i.e.
+// that the test below exercises the cross-library strcmp path, not the
+// same-library pointer-equality fast path).
+extern "C" TEST_EXPORT const void *rttiCrossDylibTest_libraryID() {
+ CrossDylibTestError E(0);
+ return E.libraryID();
+}
diff --git a/orc-rt/test/unit/bedrock/ExecutorProcessInfoTest.cpp b/orc-rt/test/unit/bedrock/ExecutorProcessInfoTest.cpp
index fb9faa5641f73..08d2e1aef5bc8 100644
--- a/orc-rt/test/unit/bedrock/ExecutorProcessInfoTest.cpp
+++ b/orc-rt/test/unit/bedrock/ExecutorProcessInfoTest.cpp
@@ -1,47 +1,53 @@
-//===- ExecutorProcessInfoTest.cpp ----------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for ExecutorProcessInfo APIs.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/bedrock/ExecutorProcessInfo.h"
-#include "orc-rt/support/bit.h"
-#include "gtest/gtest.h"
-
-#include <unistd.h>
-
-using namespace orc_rt;
-
-TEST(ExecutorProcessInfoTest, DetectSucceeds) {
- auto EPI = ExecutorProcessInfo::Detect();
- EXPECT_TRUE(!!EPI);
-}
-
-TEST(ExecutorProcessInfoTest, DetectPageSizeIsPowerOfTwo) {
- auto EPI = cantFail(ExecutorProcessInfo::Detect());
- EXPECT_GT(EPI.pageSize(), 0U);
- EXPECT_TRUE(has_single_bit(EPI.pageSize()));
-}
-
-TEST(ExecutorProcessInfoTest, DetectPageSizeAtLeast4096) {
- auto EPI = cantFail(ExecutorProcessInfo::Detect());
- EXPECT_GE(EPI.pageSize(), 4096U);
-}
-
-TEST(ExecutorProcessInfoTest, DetectPageSizeMatchesSysconf) {
- auto EPI = cantFail(ExecutorProcessInfo::Detect());
- EXPECT_EQ(EPI.pageSize(), static_cast<size_t>(sysconf(_SC_PAGESIZE)));
-}
-
-TEST(ExecutorProcessInfoTest, ConstructWithExplicitValues) {
- ExecutorProcessInfo EPI("x86_64-unknown-linux-gnu", 4096, "+x,+a,+b");
- EXPECT_EQ(EPI.targetTriple(), "x86_64-unknown-linux-gnu");
- EXPECT_EQ(EPI.pageSize(), 4096U);
- EXPECT_EQ(EPI.targetCPUFeatures(), "+x,+a,+b");
-}
+//===- ExecutorProcessInfoTest.cpp ----------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for ExecutorProcessInfo APIs.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/bedrock/ExecutorProcessInfo.h"
+#include "orc-rt/support/bit.h"
+#include "gtest/gtest.h"
+
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+
+using namespace orc_rt;
+#ifndef _WIN32
+TEST(ExecutorProcessInfoTest, DetectSucceeds) {
+ auto EPI = ExecutorProcessInfo::Detect();
+ EXPECT_TRUE(!!EPI);
+}
+
+TEST(ExecutorProcessInfoTest, DetectPageSizeIsPowerOfTwo) {
+ auto EPI = cantFail(ExecutorProcessInfo::Detect());
+ EXPECT_GT(EPI.pageSize(), 0U);
+ EXPECT_TRUE(has_single_bit(EPI.pageSize()));
+}
+
+TEST(ExecutorProcessInfoTest, DetectPageSizeAtLeast4096) {
+ auto EPI = cantFail(ExecutorProcessInfo::Detect());
+ EXPECT_GE(EPI.pageSize(), 4096U);
+}
+
+
+TEST(ExecutorProcessInfoTest, DetectPageSizeMatchesSystem) {
+ auto EPI = ExecutorProcessInfo::Detect();
+ ASSERT_TRUE(EPI);
+
+ EXPECT_EQ(EPI->PageSize, static_cast<uint64_t>(sysconf(_SC_PAGESIZE)));
+}
+#endif
+
+TEST(ExecutorProcessInfoTest, ConstructWithExplicitValues) {
+ ExecutorProcessInfo EPI("x86_64-unknown-linux-gnu", 4096, "+x,+a,+b");
+ EXPECT_EQ(EPI.targetTriple(), "x86_64-unknown-linux-gnu");
+ EXPECT_EQ(EPI.pageSize(), 4096U);
+ EXPECT_EQ(EPI.targetCPUFeatures(), "+x,+a,+b");
+}
diff --git a/orc-rt/test/unit/bedrock/NativeDylibManagerTest.cpp b/orc-rt/test/unit/bedrock/NativeDylibManagerTest.cpp
index d8227f3f4987d..ac40e8bdaaa8c 100644
--- a/orc-rt/test/unit/bedrock/NativeDylibManagerTest.cpp
+++ b/orc-rt/test/unit/bedrock/NativeDylibManagerTest.cpp
@@ -1,199 +1,200 @@
-//===- NativeDylibManagerTest.cpp -----------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Test NativeDylibManager APIs.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/bedrock/NativeDylibManager.h"
-#include "orc-rt/bedrock/Session.h"
-
-#include "gtest/gtest.h"
-
-#include "BedrockTestUtils.h"
-#include "CommonTestUtils.h"
-
-#include <optional>
-
-using namespace orc_rt;
-
-namespace {
-// Local aliases for brevity in test bodies.
-constexpr auto Req = NativeDylibManager::RequiredSymbol;
-constexpr auto Weak = NativeDylibManager::WeaklyReferencedSymbol;
-} // namespace
-
-// Wrap a symbol-name string literal in the platform's linker-mangling.
-// NativeDylibManager::lookup takes linker-mangled names; on Darwin the
-// linker prefixes C names with '_'.
-#if defined(__APPLE__)
-#define MANGLED(name) "_" name
-#else
-#define MANGLED(name) name
-#endif
-
-#ifndef NDM_TEST_LIB_PATH
-#error \
- "NDM_TEST_LIB_PATH must be defined to the path of the test shared library"
-#endif
-
-// Helper: synchronously run load and return result.
-static Expected<void *> syncLoad(NativeDylibManager &NDM, std::string Path) {
- std::optional<Expected<void *>> Result;
- NDM.load([&](Expected<void *> R) { Result = std::move(R); }, std::move(Path));
- return std::move(*Result);
-}
-
-// Helper: synchronously run lookup and return results.
-static Expected<std::vector<std::optional<void *>>>
-syncLookup(NativeDylibManager &NDM, void *Handle,
- NativeDylibManager::SymbolLookupSet Symbols) {
- std::optional<Expected<std::vector<std::optional<void *>>>> Result;
- NDM.lookup(
- [&](Expected<std::vector<std::optional<void *>>> R) {
- Result = std::move(R);
- },
- Handle, std::move(Symbols));
- return std::move(*Result);
-}
-
-TEST(NativeDylibManagerTest, Create) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = NativeDylibManager::Create(S, ST);
- ASSERT_TRUE(!!NDM) << toString(NDM.takeError());
-}
-
-TEST(NativeDylibManagerTest, Load) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- auto LoadResult = syncLoad(*NDM, NDM_TEST_LIB_PATH);
- ASSERT_TRUE(!!LoadResult) << toString(LoadResult.takeError());
- EXPECT_NE(*LoadResult, nullptr);
-}
-
-TEST(NativeDylibManagerTest, LoadNonExistent) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- auto LoadResult = syncLoad(*NDM, "/no/such/library.dylib");
- EXPECT_FALSE(!!LoadResult);
- consumeError(LoadResult.takeError());
-}
-
-TEST(NativeDylibManagerTest, LoadEmptyPathReturnsGlobalHandle) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- // The global handle's value is implementation-defined, so verify by looking
- // up through it.
- auto LoadResult = syncLoad(*NDM, "");
- ASSERT_TRUE(!!LoadResult) << toString(LoadResult.takeError());
- void *Handle = *LoadResult;
-
- auto Result = syncLookup(*NDM, Handle, {{MANGLED("malloc"), Req}});
- ASSERT_TRUE(!!Result) << toString(Result.takeError());
- ASSERT_EQ(Result->size(), 1U);
- ASSERT_TRUE((*Result)[0].has_value())
- << "malloc should be findable via the process's global lookup handle";
- EXPECT_NE(*(*Result)[0], nullptr);
-}
-
-TEST(NativeDylibManagerTest, LookupSingleSymbol) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
-
- auto Result =
- syncLookup(*NDM, Handle, {{MANGLED("NativeDylibManagerTestFunc"), Req}});
- ASSERT_TRUE(!!Result) << toString(Result.takeError());
- ASSERT_EQ(Result->size(), 1U);
- ASSERT_TRUE((*Result)[0].has_value());
- EXPECT_NE(*(*Result)[0], nullptr);
-
- // Verify the symbol points to the right function.
- auto *Func = reinterpret_cast<int (*)()>(*(*Result)[0]);
- EXPECT_EQ(Func(), 42);
-}
-
-TEST(NativeDylibManagerTest, LookupMultipleSymbols) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
-
- auto Result = syncLookup(*NDM, Handle,
- {{MANGLED("NativeDylibManagerTestFunc"), Req},
- {MANGLED("NativeDylibManagerTestFunc2"), Req}});
- ASSERT_TRUE(!!Result) << toString(Result.takeError());
- ASSERT_EQ(Result->size(), 2U);
- ASSERT_TRUE((*Result)[0].has_value());
- ASSERT_TRUE((*Result)[1].has_value());
- EXPECT_NE(*(*Result)[0], nullptr);
- EXPECT_NE(*(*Result)[1], nullptr);
-
- auto *Func1 = reinterpret_cast<int (*)()>(*(*Result)[0]);
- auto *Func2 = reinterpret_cast<int (*)()>(*(*Result)[1]);
- EXPECT_EQ(Func1(), 42);
- EXPECT_EQ(Func2(), 7);
-}
-
-TEST(NativeDylibManagerTest, LookupWeakMissingSymbol) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
-
- auto Result = syncLookup(*NDM, Handle, {{MANGLED("no_such_symbol"), Weak}});
- ASSERT_TRUE(!!Result) << toString(Result.takeError());
- ASSERT_EQ(Result->size(), 1U);
- ASSERT_TRUE((*Result)[0].has_value())
- << "weak-missing symbol should be reported as a present optional";
- EXPECT_EQ(*(*Result)[0], nullptr);
-}
-
-TEST(NativeDylibManagerTest, LookupRequiredMissingSymbol) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
-
- auto Result = syncLookup(*NDM, Handle, {{MANGLED("no_such_symbol"), Req}});
- ASSERT_TRUE(!!Result) << toString(Result.takeError());
- ASSERT_EQ(Result->size(), 1U);
- EXPECT_FALSE((*Result)[0].has_value())
- << "required-missing symbol should be reported as an empty optional";
-}
-
-TEST(NativeDylibManagerTest, LookupMixedRequiredAndWeak) {
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ST;
- auto NDM = cantFail(NativeDylibManager::Create(S, ST));
-
- void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
-
- auto Result = syncLookup(*NDM, Handle,
- {{MANGLED("NativeDylibManagerTestFunc"), Req},
- {MANGLED("no_such_symbol"), Weak}});
- ASSERT_TRUE(!!Result) << toString(Result.takeError());
- ASSERT_EQ(Result->size(), 2U);
- ASSERT_TRUE((*Result)[0].has_value());
- EXPECT_NE(*(*Result)[0], nullptr);
- ASSERT_TRUE((*Result)[1].has_value())
- << "weak-missing symbol should be reported as a present optional";
- EXPECT_EQ(*(*Result)[1], nullptr);
-}
+//===- NativeDylibManagerTest.cpp -----------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Test NativeDylibManager APIs.
+//
+//===----------------------------------------------------------------------===//
+#ifndef _WIN32
+#include "orc-rt/bedrock/NativeDylibManager.h"
+#include "orc-rt/bedrock/Session.h"
+
+#include "gtest/gtest.h"
+
+#include "BedrockTestUtils.h"
+#include "CommonTestUtils.h"
+
+#include <optional>
+
+using namespace orc_rt;
+
+namespace {
+// Local aliases for brevity in test bodies.
+constexpr auto Req = NativeDylibManager::RequiredSymbol;
+constexpr auto Weak = NativeDylibManager::WeaklyReferencedSymbol;
+} // namespace
+
+// Wrap a symbol-name string literal in the platform's linker-mangling.
+// NativeDylibManager::lookup takes linker-mangled names; on Darwin the
+// linker prefixes C names with '_'.
+#if defined(__APPLE__)
+#define MANGLED(name) "_" name
+#else
+#define MANGLED(name) name
+#endif
+
+#ifndef NDM_TEST_LIB_PATH
+#error \
+ "NDM_TEST_LIB_PATH must be defined to the path of the test shared library"
+#endif
+
+// Helper: synchronously run load and return result.
+static Expected<void *> syncLoad(NativeDylibManager &NDM, std::string Path) {
+ std::optional<Expected<void *>> Result;
+ NDM.load([&](Expected<void *> R) { Result = std::move(R); }, std::move(Path));
+ return std::move(*Result);
+}
+
+// Helper: synchronously run lookup and return results.
+static Expected<std::vector<std::optional<void *>>>
+syncLookup(NativeDylibManager &NDM, void *Handle,
+ NativeDylibManager::SymbolLookupSet Symbols) {
+ std::optional<Expected<std::vector<std::optional<void *>>>> Result;
+ NDM.lookup(
+ [&](Expected<std::vector<std::optional<void *>>> R) {
+ Result = std::move(R);
+ },
+ Handle, std::move(Symbols));
+ return std::move(*Result);
+}
+
+TEST(NativeDylibManagerTest, Create) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = NativeDylibManager::Create(S, ST);
+ ASSERT_TRUE(!!NDM) << toString(NDM.takeError());
+}
+
+TEST(NativeDylibManagerTest, Load) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ auto LoadResult = syncLoad(*NDM, NDM_TEST_LIB_PATH);
+ ASSERT_TRUE(!!LoadResult) << toString(LoadResult.takeError());
+ EXPECT_NE(*LoadResult, nullptr);
+}
+
+TEST(NativeDylibManagerTest, LoadNonExistent) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ auto LoadResult = syncLoad(*NDM, "/no/such/library.dylib");
+ EXPECT_FALSE(!!LoadResult);
+ consumeError(LoadResult.takeError());
+}
+
+TEST(NativeDylibManagerTest, LoadEmptyPathReturnsGlobalHandle) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ // The global handle's value is implementation-defined, so verify by looking
+ // up through it.
+ auto LoadResult = syncLoad(*NDM, "");
+ ASSERT_TRUE(!!LoadResult) << toString(LoadResult.takeError());
+ void *Handle = *LoadResult;
+
+ auto Result = syncLookup(*NDM, Handle, {{MANGLED("malloc"), Req}});
+ ASSERT_TRUE(!!Result) << toString(Result.takeError());
+ ASSERT_EQ(Result->size(), 1U);
+ ASSERT_TRUE((*Result)[0].has_value())
+ << "malloc should be findable via the process's global lookup handle";
+ EXPECT_NE(*(*Result)[0], nullptr);
+}
+
+TEST(NativeDylibManagerTest, LookupSingleSymbol) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
+
+ auto Result =
+ syncLookup(*NDM, Handle, {{MANGLED("NativeDylibManagerTestFunc"), Req}});
+ ASSERT_TRUE(!!Result) << toString(Result.takeError());
+ ASSERT_EQ(Result->size(), 1U);
+ ASSERT_TRUE((*Result)[0].has_value());
+ EXPECT_NE(*(*Result)[0], nullptr);
+
+ // Verify the symbol points to the right function.
+ auto *Func = reinterpret_cast<int (*)()>(*(*Result)[0]);
+ EXPECT_EQ(Func(), 42);
+}
+
+TEST(NativeDylibManagerTest, LookupMultipleSymbols) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
+
+ auto Result = syncLookup(*NDM, Handle,
+ {{MANGLED("NativeDylibManagerTestFunc"), Req},
+ {MANGLED("NativeDylibManagerTestFunc2"), Req}});
+ ASSERT_TRUE(!!Result) << toString(Result.takeError());
+ ASSERT_EQ(Result->size(), 2U);
+ ASSERT_TRUE((*Result)[0].has_value());
+ ASSERT_TRUE((*Result)[1].has_value());
+ EXPECT_NE(*(*Result)[0], nullptr);
+ EXPECT_NE(*(*Result)[1], nullptr);
+
+ auto *Func1 = reinterpret_cast<int (*)()>(*(*Result)[0]);
+ auto *Func2 = reinterpret_cast<int (*)()>(*(*Result)[1]);
+ EXPECT_EQ(Func1(), 42);
+ EXPECT_EQ(Func2(), 7);
+}
+
+TEST(NativeDylibManagerTest, LookupWeakMissingSymbol) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
+
+ auto Result = syncLookup(*NDM, Handle, {{MANGLED("no_such_symbol"), Weak}});
+ ASSERT_TRUE(!!Result) << toString(Result.takeError());
+ ASSERT_EQ(Result->size(), 1U);
+ ASSERT_TRUE((*Result)[0].has_value())
+ << "weak-missing symbol should be reported as a present optional";
+ EXPECT_EQ(*(*Result)[0], nullptr);
+}
+
+TEST(NativeDylibManagerTest, LookupRequiredMissingSymbol) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
+
+ auto Result = syncLookup(*NDM, Handle, {{MANGLED("no_such_symbol"), Req}});
+ ASSERT_TRUE(!!Result) << toString(Result.takeError());
+ ASSERT_EQ(Result->size(), 1U);
+ EXPECT_FALSE((*Result)[0].has_value())
+ << "required-missing symbol should be reported as an empty optional";
+}
+
+TEST(NativeDylibManagerTest, LookupMixedRequiredAndWeak) {
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ST;
+ auto NDM = cantFail(NativeDylibManager::Create(S, ST));
+
+ void *Handle = cantFail(syncLoad(*NDM, NDM_TEST_LIB_PATH));
+
+ auto Result = syncLookup(*NDM, Handle,
+ {{MANGLED("NativeDylibManagerTestFunc"), Req},
+ {MANGLED("no_such_symbol"), Weak}});
+ ASSERT_TRUE(!!Result) << toString(Result.takeError());
+ ASSERT_EQ(Result->size(), 2U);
+ ASSERT_TRUE((*Result)[0].has_value());
+ EXPECT_NE(*(*Result)[0], nullptr);
+ ASSERT_TRUE((*Result)[1].has_value())
+ << "weak-missing symbol should be reported as a present optional";
+ EXPECT_EQ(*(*Result)[1], nullptr);
+}
+#endif
diff --git a/orc-rt/test/unit/bedrock/SimpleNativeMemoryMapTest.cpp b/orc-rt/test/unit/bedrock/SimpleNativeMemoryMapTest.cpp
index 23d3cd7393d2b..d374b1f761465 100644
--- a/orc-rt/test/unit/bedrock/SimpleNativeMemoryMapTest.cpp
+++ b/orc-rt/test/unit/bedrock/SimpleNativeMemoryMapTest.cpp
@@ -1,324 +1,326 @@
-//===-- SimpleNativeMemoryMapTest.cpp -------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Test SimpleNativeMemoryMap APIs.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/bedrock/SimpleNativeMemoryMap.h"
-#include "orc-rt/bedrock/Session.h"
-#include "orc-rt/support/sps/SPSAllocAction.h"
-
-#include "AllocActionTestUtils.h"
-#include "BedrockTestUtils.h"
-#include "CommonTestUtils.h"
-#include "gtest/gtest.h"
-
-#include <cstring>
-#include <string>
-#include <vector>
-
-using namespace orc_rt;
-
-// Write the given value to the address pointed to by P.
-static orc_rt_WrapperFunctionBuffer
-write_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
- return SPSAllocActionFunction<SPSExecutorAddr, uint64_t>::handle(
- ArgData, ArgSize,
- [](ExecutorAddr P, uint64_t Val) {
- *P.toPtr<uint64_t *>() = Val;
- return WrapperFunctionBuffer();
- })
- .release();
-}
-
-// Read the uint64_t value at Src and write it to Dst.
-static orc_rt_WrapperFunctionBuffer
-read_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
- return SPSAllocActionFunction<SPSExecutorAddr, SPSExecutorAddr>::handle(
- ArgData, ArgSize,
- [](ExecutorAddr Dst, ExecutorAddr Src) {
- *Dst.toPtr<uint64_t *>() = *Src.toPtr<uint64_t *>();
- return WrapperFunctionBuffer();
- })
- .release();
-}
-
-TEST(SimpleNativeMemoryMapTest, CreateAndDestroy) {
- // Test that we can create and destroy a SimpleNativeMemoryMap instance as
- // expected.
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-}
-
-TEST(SimpleNativeMemoryMapTest, ReserveAndRelease) {
- // Test that we can reserve and release a slab of address space as expected,
- // without finalizing any memory within it.
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- std::future<Expected<void *>> ReserveResult;
- SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
- void *Addr = cantFail(ReserveResult.get());
-
- std::future<Error> ReleaseResult;
- SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
- cantFail(ReleaseResult.get());
-}
-
-TEST(SimpleNativeMemoryMapTest, FullPipelineForOneRWSegment) {
- // Test that we can:
- // 1. reserve some address space.
- // 2. initialize a range within it as read/write, and that finalize actions
- // are applied as expected.
- // 3. deinitialize the initialized range, with deallocation actions applied as
- // expected.
- // 4. release the address range.
-
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- std::future<Expected<void *>> ReserveResult;
- SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
- void *Addr = cantFail(ReserveResult.get());
-
- char *InitializeBase = // Initialize addr at non-zero (64kb) offset from base.
- reinterpret_cast<char *>(Addr) + 64 * 1024;
- uint64_t SentinelValue1 = 0; // Read from pre-filled content
- uint64_t SentinelValue2 =
- 0; // Written in initialize, read back during dealloc.
- uint64_t SentinelValue3 = 42; // Read from zero-filled region.
-
- // Build initial content vector.
- std::vector<char> Content;
- Content.resize(sizeof(uint64_t) * 2);
- memcpy(Content.data(), &SentinelValue3, sizeof(uint64_t));
- memcpy(Content.data() + sizeof(uint64_t), &SentinelValue1, sizeof(uint64_t));
-
- SimpleNativeMemoryMap::InitializeRequest IR;
- IR.Segments.push_back({MemProt::Read | MemProt::Write,
- InitializeBase,
- 64 * 1024,
- {Content.data(), Content.size()}});
-
- // Read initial content into Sentinel 1.
- IR.AAPs.push_back({
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue1),
- ExecutorAddr::fromPtr(InitializeBase)),
- {} // No dealloc action.
- });
-
- // Write value in finalize action, then read back into Sentinel 2.
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
- write_value_sps_allocaction,
- ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t),
- uint64_t(42)),
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue2),
- ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t))});
-
- // Read first 64 bits of the zero-fill region.
- IR.AAPs.push_back({
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue3),
- ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t) * 2),
- {} // No dealloc action.
- });
-
- std::future<Expected<void *>> InitializeResult;
- SNMM->initialize(waitFor(InitializeResult), std::move(IR));
- void *InitializeKeyAddr = cantFail(InitializeResult.get());
-
- EXPECT_EQ(SentinelValue1, 42U);
- EXPECT_EQ(SentinelValue2, 0U);
- EXPECT_EQ(SentinelValue3, 0U);
-
- std::future<Error> DeallocResult;
- SNMM->deinitializeMultiple(waitFor(DeallocResult), {InitializeKeyAddr});
- cantFail(DeallocResult.get());
-
- EXPECT_EQ(SentinelValue1, 42U);
- EXPECT_EQ(SentinelValue2, 42U);
- EXPECT_EQ(SentinelValue3, 0U);
-
- std::future<Error> ReleaseResult;
- SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
- cantFail(ReleaseResult.get());
-}
-
-TEST(SimpleNativeMemoryMapTest, ReserveRejectsNonPageSizeMultiple) {
- // Verify that reserve rejects sizes that aren't page-size multiples.
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- std::future<Expected<void *>> ReserveResult;
- SNMM->reserve(waitFor(ReserveResult), S.processInfo().pageSize() + 1);
- auto Result = ReserveResult.get();
- EXPECT_FALSE(!!Result);
- consumeError(Result.takeError());
-}
-
-TEST(SimpleNativeMemoryMapTest, ReserveAcceptsPageSizeMultiple) {
- // Verify that reserve accepts a size that's an exact page-size multiple.
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- std::future<Expected<void *>> ReserveResult;
- SNMM->reserve(waitFor(ReserveResult), S.processInfo().pageSize());
- void *Addr = cantFail(ReserveResult.get());
-
- std::future<Error> ReleaseResult;
- SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
- cantFail(ReleaseResult.get());
-}
-
-TEST(SimpleNativeMemoryMapTest, ReleaseMultipleReportsErrors) {
- // Test that releaseMultiple reports errors via Session::reportError
- // when some addresses aren't recognized.
- std::vector<std::string> Errors;
- Session S(mockExecutorProcessInfo(), noDispatch,
- [&](Error Err) { Errors.push_back(toString(std::move(Err))); });
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- // Try to release an address that was never reserved.
- int Dummy;
- std::future<Error> ReleaseResult;
- SNMM->releaseMultiple(waitFor(ReleaseResult), {&Dummy});
- auto Err = ReleaseResult.get();
- EXPECT_TRUE(!!Err);
- consumeError(std::move(Err));
-
- // The error for the unrecognized address should have been reported
- // via reportError (not silently consumed).
- EXPECT_EQ(Errors.size(), 1U);
-}
-
-TEST(SimpleNativeMemoryMapTest, DeinitializeMultipleReportsErrors) {
- // Test that deinitializeMultiple reports errors via Session::reportError
- // when some addresses aren't recognized.
- std::vector<std::string> Errors;
- Session S(mockExecutorProcessInfo(), noDispatch,
- [&](Error Err) { Errors.push_back(toString(std::move(Err))); });
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- // Reserve and initialize a slab so we have a valid context.
- std::future<Expected<void *>> ReserveResult;
- SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
- void *Addr = cantFail(ReserveResult.get());
-
- // Try to deinitialize an address that was never initialized.
- // This should fail and report the error.
- std::future<Error> DeinitResult;
- SNMM->deinitializeMultiple(waitFor(DeinitResult), {Addr});
- auto Err = DeinitResult.get();
- EXPECT_TRUE(!!Err);
- consumeError(std::move(Err));
-
- EXPECT_EQ(Errors.size(), 1U);
-
- std::future<Error> ReleaseResult;
- SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
- cantFail(ReleaseResult.get());
-}
-
-TEST(SimpleNativeMemoryMapTest, ReserveInitializeShutdown) {
- // Test that memory is deinitialized in the case where we reserve and
- // initialize some memory, then just shut down the memory manager.
-
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- std::future<Expected<void *>> ReserveResult;
- SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
- void *Addr = cantFail(ReserveResult.get());
-
- char *InitializeBase = // Initialize addr at non-zero (64kb) offset from base.
- reinterpret_cast<char *>(Addr) + 64 * 1024;
- uint64_t SentinelValue = 0;
-
- SimpleNativeMemoryMap::InitializeRequest IR;
- IR.Segments.push_back(
- {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024, {}});
-
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
- write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
- uint64_t(42)),
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
- ExecutorAddr::fromPtr(InitializeBase))});
-
- std::future<Expected<void *>> InitializeResult;
- SNMM->initialize(waitFor(InitializeResult), std::move(IR));
- cantFail(InitializeResult.get());
-
- EXPECT_EQ(SentinelValue, 0U);
-
- std::future<void> ShutdownResult;
- SNMM->onShutdown(waitFor(ShutdownResult));
- ShutdownResult.get();
-
- EXPECT_EQ(SentinelValue, 42);
-}
-
-TEST(SimpleNativeMemoryMapTest, ReserveInitializeDetachShutdown) {
- // Test that memory is deinitialized in the case where we reserve and
- // initialize some memory, then just shut down the memory manager.
-
- Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
- SimpleSymbolTable ThrowAway;
- auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
-
- std::future<Expected<void *>> ReserveResult;
- SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
- void *Addr = cantFail(ReserveResult.get());
-
- char *InitializeBase = // Initialize addr at non-zero (64kb) offset from base.
- reinterpret_cast<char *>(Addr) + 64 * 1024;
- uint64_t SentinelValue = 0;
-
- SimpleNativeMemoryMap::InitializeRequest IR;
- IR.Segments.push_back(
- {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024, {}});
-
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
- write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
- uint64_t(42)),
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
- ExecutorAddr::fromPtr(InitializeBase))});
-
- std::future<Expected<void *>> InitializeResult;
- SNMM->initialize(waitFor(InitializeResult), std::move(IR));
- cantFail(InitializeResult.get());
-
- EXPECT_EQ(SentinelValue, 0U);
-
- std::future<void> DetachResult;
- SNMM->onDetach(waitFor(DetachResult), /* ShutdownRequested */ false);
- DetachResult.get();
-
- EXPECT_EQ(SentinelValue, 0);
-
- std::future<void> ShutdownResult;
- SNMM->onShutdown(waitFor(ShutdownResult));
- ShutdownResult.get();
-
- EXPECT_EQ(SentinelValue, 42);
-}
+//===-- SimpleNativeMemoryMapTest.cpp -------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Test SimpleNativeMemoryMap APIs.
+//
+//===----------------------------------------------------------------------===//
+#ifndef _WIN32
+
+#include "orc-rt/bedrock/SimpleNativeMemoryMap.h"
+#include "orc-rt/bedrock/Session.h"
+#include "orc-rt/support/sps/SPSAllocAction.h"
+
+#include "AllocActionTestUtils.h"
+#include "BedrockTestUtils.h"
+#include "CommonTestUtils.h"
+#include "gtest/gtest.h"
+
+#include <cstring>
+#include <string>
+#include <vector>
+
+using namespace orc_rt;
+
+// Write the given value to the address pointed to by P.
+static orc_rt_WrapperFunctionBuffer
+write_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
+ return SPSAllocActionFunction<SPSExecutorAddr, uint64_t>::handle(
+ ArgData, ArgSize,
+ [](ExecutorAddr P, uint64_t Val) {
+ *P.toPtr<uint64_t *>() = Val;
+ return WrapperFunctionBuffer();
+ })
+ .release();
+}
+
+// Read the uint64_t value at Src and write it to Dst.
+static orc_rt_WrapperFunctionBuffer
+read_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
+ return SPSAllocActionFunction<SPSExecutorAddr, SPSExecutorAddr>::handle(
+ ArgData, ArgSize,
+ [](ExecutorAddr Dst, ExecutorAddr Src) {
+ *Dst.toPtr<uint64_t *>() = *Src.toPtr<uint64_t *>();
+ return WrapperFunctionBuffer();
+ })
+ .release();
+}
+
+TEST(SimpleNativeMemoryMapTest, CreateAndDestroy) {
+ // Test that we can create and destroy a SimpleNativeMemoryMap instance as
+ // expected.
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+}
+
+TEST(SimpleNativeMemoryMapTest, ReserveAndRelease) {
+ // Test that we can reserve and release a slab of address space as expected,
+ // without finalizing any memory within it.
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ std::future<Expected<void *>> ReserveResult;
+ SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
+ void *Addr = cantFail(ReserveResult.get());
+
+ std::future<Error> ReleaseResult;
+ SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
+ cantFail(ReleaseResult.get());
+}
+
+TEST(SimpleNativeMemoryMapTest, FullPipelineForOneRWSegment) {
+ // Test that we can:
+ // 1. reserve some address space.
+ // 2. initialize a range within it as read/write, and that finalize actions
+ // are applied as expected.
+ // 3. deinitialize the initialized range, with deallocation actions applied as
+ // expected.
+ // 4. release the address range.
+
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ std::future<Expected<void *>> ReserveResult;
+ SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
+ void *Addr = cantFail(ReserveResult.get());
+
+ char *InitializeBase = // Initialize addr at non-zero (64kb) offset from base.
+ reinterpret_cast<char *>(Addr) + 64 * 1024;
+ uint64_t SentinelValue1 = 0; // Read from pre-filled content
+ uint64_t SentinelValue2 =
+ 0; // Written in initialize, read back during dealloc.
+ uint64_t SentinelValue3 = 42; // Read from zero-filled region.
+
+ // Build initial content vector.
+ std::vector<char> Content;
+ Content.resize(sizeof(uint64_t) * 2);
+ memcpy(Content.data(), &SentinelValue3, sizeof(uint64_t));
+ memcpy(Content.data() + sizeof(uint64_t), &SentinelValue1, sizeof(uint64_t));
+
+ SimpleNativeMemoryMap::InitializeRequest IR;
+ IR.Segments.push_back({MemProt::Read | MemProt::Write,
+ InitializeBase,
+ 64 * 1024,
+ {Content.data(), Content.size()}});
+
+ // Read initial content into Sentinel 1.
+ IR.AAPs.push_back({
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue1),
+ ExecutorAddr::fromPtr(InitializeBase)),
+ {} // No dealloc action.
+ });
+
+ // Write value in finalize action, then read back into Sentinel 2.
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
+ write_value_sps_allocaction,
+ ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t),
+ uint64_t(42)),
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue2),
+ ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t))});
+
+ // Read first 64 bits of the zero-fill region.
+ IR.AAPs.push_back({
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue3),
+ ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t) * 2),
+ {} // No dealloc action.
+ });
+
+ std::future<Expected<void *>> InitializeResult;
+ SNMM->initialize(waitFor(InitializeResult), std::move(IR));
+ void *InitializeKeyAddr = cantFail(InitializeResult.get());
+
+ EXPECT_EQ(SentinelValue1, 42U);
+ EXPECT_EQ(SentinelValue2, 0U);
+ EXPECT_EQ(SentinelValue3, 0U);
+
+ std::future<Error> DeallocResult;
+ SNMM->deinitializeMultiple(waitFor(DeallocResult), {InitializeKeyAddr});
+ cantFail(DeallocResult.get());
+
+ EXPECT_EQ(SentinelValue1, 42U);
+ EXPECT_EQ(SentinelValue2, 42U);
+ EXPECT_EQ(SentinelValue3, 0U);
+
+ std::future<Error> ReleaseResult;
+ SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
+ cantFail(ReleaseResult.get());
+}
+
+TEST(SimpleNativeMemoryMapTest, ReserveRejectsNonPageSizeMultiple) {
+ // Verify that reserve rejects sizes that aren't page-size multiples.
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ std::future<Expected<void *>> ReserveResult;
+ SNMM->reserve(waitFor(ReserveResult), S.processInfo().pageSize() + 1);
+ auto Result = ReserveResult.get();
+ EXPECT_FALSE(!!Result);
+ consumeError(Result.takeError());
+}
+
+TEST(SimpleNativeMemoryMapTest, ReserveAcceptsPageSizeMultiple) {
+ // Verify that reserve accepts a size that's an exact page-size multiple.
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ std::future<Expected<void *>> ReserveResult;
+ SNMM->reserve(waitFor(ReserveResult), S.processInfo().pageSize());
+ void *Addr = cantFail(ReserveResult.get());
+
+ std::future<Error> ReleaseResult;
+ SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
+ cantFail(ReleaseResult.get());
+}
+
+TEST(SimpleNativeMemoryMapTest, ReleaseMultipleReportsErrors) {
+ // Test that releaseMultiple reports errors via Session::reportError
+ // when some addresses aren't recognized.
+ std::vector<std::string> Errors;
+ Session S(mockExecutorProcessInfo(), noDispatch,
+ [&](Error Err) { Errors.push_back(toString(std::move(Err))); });
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ // Try to release an address that was never reserved.
+ int Dummy;
+ std::future<Error> ReleaseResult;
+ SNMM->releaseMultiple(waitFor(ReleaseResult), {&Dummy});
+ auto Err = ReleaseResult.get();
+ EXPECT_TRUE(!!Err);
+ consumeError(std::move(Err));
+
+ // The error for the unrecognized address should have been reported
+ // via reportError (not silently consumed).
+ EXPECT_EQ(Errors.size(), 1U);
+}
+
+TEST(SimpleNativeMemoryMapTest, DeinitializeMultipleReportsErrors) {
+ // Test that deinitializeMultiple reports errors via Session::reportError
+ // when some addresses aren't recognized.
+ std::vector<std::string> Errors;
+ Session S(mockExecutorProcessInfo(), noDispatch,
+ [&](Error Err) { Errors.push_back(toString(std::move(Err))); });
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ // Reserve and initialize a slab so we have a valid context.
+ std::future<Expected<void *>> ReserveResult;
+ SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
+ void *Addr = cantFail(ReserveResult.get());
+
+ // Try to deinitialize an address that was never initialized.
+ // This should fail and report the error.
+ std::future<Error> DeinitResult;
+ SNMM->deinitializeMultiple(waitFor(DeinitResult), {Addr});
+ auto Err = DeinitResult.get();
+ EXPECT_TRUE(!!Err);
+ consumeError(std::move(Err));
+
+ EXPECT_EQ(Errors.size(), 1U);
+
+ std::future<Error> ReleaseResult;
+ SNMM->releaseMultiple(waitFor(ReleaseResult), {Addr});
+ cantFail(ReleaseResult.get());
+}
+
+TEST(SimpleNativeMemoryMapTest, ReserveInitializeShutdown) {
+ // Test that memory is deinitialized in the case where we reserve and
+ // initialize some memory, then just shut down the memory manager.
+
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ std::future<Expected<void *>> ReserveResult;
+ SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
+ void *Addr = cantFail(ReserveResult.get());
+
+ char *InitializeBase = // Initialize addr at non-zero (64kb) offset from base.
+ reinterpret_cast<char *>(Addr) + 64 * 1024;
+ uint64_t SentinelValue = 0;
+
+ SimpleNativeMemoryMap::InitializeRequest IR;
+ IR.Segments.push_back(
+ {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024, {}});
+
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
+ write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
+ uint64_t(42)),
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
+ ExecutorAddr::fromPtr(InitializeBase))});
+
+ std::future<Expected<void *>> InitializeResult;
+ SNMM->initialize(waitFor(InitializeResult), std::move(IR));
+ cantFail(InitializeResult.get());
+
+ EXPECT_EQ(SentinelValue, 0U);
+
+ std::future<void> ShutdownResult;
+ SNMM->onShutdown(waitFor(ShutdownResult));
+ ShutdownResult.get();
+
+ EXPECT_EQ(SentinelValue, 42);
+}
+
+TEST(SimpleNativeMemoryMapTest, ReserveInitializeDetachShutdown) {
+ // Test that memory is deinitialized in the case where we reserve and
+ // initialize some memory, then just shut down the memory manager.
+
+ Session S(mockExecutorProcessInfo(), noDispatch, noErrors);
+ SimpleSymbolTable ThrowAway;
+ auto SNMM = cantFail(SimpleNativeMemoryMap::Create(S, ThrowAway));
+
+ std::future<Expected<void *>> ReserveResult;
+ SNMM->reserve(waitFor(ReserveResult), 1024 * 1024 * 1024);
+ void *Addr = cantFail(ReserveResult.get());
+
+ char *InitializeBase = // Initialize addr at non-zero (64kb) offset from base.
+ reinterpret_cast<char *>(Addr) + 64 * 1024;
+ uint64_t SentinelValue = 0;
+
+ SimpleNativeMemoryMap::InitializeRequest IR;
+ IR.Segments.push_back(
+ {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024, {}});
+
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
+ write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
+ uint64_t(42)),
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
+ ExecutorAddr::fromPtr(InitializeBase))});
+
+ std::future<Expected<void *>> InitializeResult;
+ SNMM->initialize(waitFor(InitializeResult), std::move(IR));
+ cantFail(InitializeResult.get());
+
+ EXPECT_EQ(SentinelValue, 0U);
+
+ std::future<void> DetachResult;
+ SNMM->onDetach(waitFor(DetachResult), /* ShutdownRequested */ false);
+ DetachResult.get();
+
+ EXPECT_EQ(SentinelValue, 0);
+
+ std::future<void> ShutdownResult;
+ SNMM->onShutdown(waitFor(ShutdownResult));
+ ShutdownResult.get();
+
+ EXPECT_EQ(SentinelValue, 42);
+}
+#endif
diff --git a/orc-rt/test/unit/bedrock/sps/NativeDylibManagerSPSCITest.cpp b/orc-rt/test/unit/bedrock/sps/NativeDylibManagerSPSCITest.cpp
index b4252a14575dc..e972841bb5b35 100644
--- a/orc-rt/test/unit/bedrock/sps/NativeDylibManagerSPSCITest.cpp
+++ b/orc-rt/test/unit/bedrock/sps/NativeDylibManagerSPSCITest.cpp
@@ -1,237 +1,238 @@
-//===- NativeDylibManagerSPSCITest.cpp ------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for NativeDylibManager's SPS Controller Interface.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/bedrock/sps/NativeDylibManagerSPSCI.h"
-#include "orc-rt/bedrock/NativeDylibManager.h"
-#include "orc-rt/bedrock/Session.h"
-#include "orc-rt/support/sps/SPSWrapperFunction.h"
-
-#include "BedrockTestUtils.h"
-#include "CommonTestUtils.h"
-#include "DirectCaller.h"
-#include "gtest/gtest.h"
-
-using namespace orc_rt;
-
-namespace orc_rt {
-
-/// SPS serialization for NativeDylibManager::LookupFlags as a bool.
-///
-/// Duplicated from NativeDylibManagerSPSCI.cpp so the test can serialize
-/// SymbolLookupSet values when invoking the SPS wrapper via
-/// SPSWrapperFunction<...>::call.
-template <>
-class SPSSerializationTraits<bool, NativeDylibManager::LookupFlags> {
-public:
- static size_t size(NativeDylibManager::LookupFlags) { return sizeof(bool); }
-
- static bool serialize(SPSOutputBuffer &OB,
- NativeDylibManager::LookupFlags L) {
- return SPSSerializationTraits<bool, bool>::serialize(
- OB, L == NativeDylibManager::RequiredSymbol);
- }
-
- static bool deserialize(SPSInputBuffer &IB,
- NativeDylibManager::LookupFlags &L) {
- bool Required;
- if (!SPSSerializationTraits<bool, bool>::deserialize(IB, Required))
- return false;
- L = Required ? NativeDylibManager::RequiredSymbol
- : NativeDylibManager::WeaklyReferencedSymbol;
- return true;
- }
-};
-
-} // namespace orc_rt
-
-namespace {
-// Local aliases for brevity in test bodies.
-constexpr auto Req = NativeDylibManager::RequiredSymbol;
-constexpr auto Weak = NativeDylibManager::WeaklyReferencedSymbol;
-} // namespace
-
-// Wrap a symbol-name string literal in the platform's linker-mangling.
-// NativeDylibManager::lookup takes linker-mangled names; on Darwin the
-// linker prefixes C names with '_'.
-#if defined(__APPLE__)
-#define MANGLED(name) "_" name
-#else
-#define MANGLED(name) name
-#endif
-
-#ifndef NDM_TEST_LIB_PATH
-#error \
- "NDM_TEST_LIB_PATH must be defined to the path of the test shared library"
-#endif
-
-static DirectCaller caller(orc_rt_WrapperFunction Fn) { return {nullptr, Fn}; }
-
-class NativeDylibManagerSPSCITest : public ::testing::Test {
-protected:
- void SetUp() override {
- S = std::make_unique<Session>(mockExecutorProcessInfo(), noDispatch,
- noErrors);
- NDM = cantFail(NativeDylibManager::Create(*S, CI));
- }
-
- template <typename OnCompleteFn>
- void spsLoad(OnCompleteFn &&OnComplete, std::string Path) {
- using SPSSig = SPSExpected<SPSExecutorAddr>(SPSExecutorAddr, SPSString);
- SPSWrapperFunction<SPSSig>::call(
- caller(orc_rt_ci_sps_NativeDylibManager_load),
- std::forward<OnCompleteFn>(OnComplete), NDM.get(), std::move(Path));
- }
-
- template <typename OnCompleteFn>
- void spsLookup(OnCompleteFn &&OnComplete, void *Handle,
- NativeDylibManager::SymbolLookupSet Symbols) {
- using SPSSig = SPSExpected<SPSSequence<SPSOptional<SPSExecutorAddr>>>(
- SPSExecutorAddr, SPSExecutorAddr,
- SPSSequence<SPSTuple<SPSString, bool>>);
- SPSWrapperFunction<SPSSig>::call(
- caller(orc_rt_ci_sps_NativeDylibManager_lookup),
- std::forward<OnCompleteFn>(OnComplete), NDM.get(), Handle,
- std::move(Symbols));
- }
-
- SimpleSymbolTable CI;
- std::unique_ptr<Session> S;
- std::unique_ptr<NativeDylibManager> NDM;
-};
-
-TEST_F(NativeDylibManagerSPSCITest, Registration) {
- EXPECT_TRUE(
- CI.count(SymbolNameSpec::c("orc_rt_ci_sps_NativeDylibManager_load")));
- EXPECT_TRUE(
- CI.count(SymbolNameSpec::c("orc_rt_ci_sps_NativeDylibManager_lookup")));
-}
-
-TEST_F(NativeDylibManagerSPSCITest, Load) {
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
- void *Handle = cantFail(cantFail(LoadResult.get()));
- EXPECT_NE(Handle, nullptr);
-}
-
-TEST_F(NativeDylibManagerSPSCITest, LoadNonExistent) {
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), "/no/such/library.dylib");
- auto Handle = cantFail(LoadResult.get());
- EXPECT_FALSE(!!Handle);
- consumeError(Handle.takeError());
-}
-
-TEST_F(NativeDylibManagerSPSCITest, LoadEmptyPathReturnsGlobalHandle) {
- // The global handle's value is implementation-defined, so verify by looking
- // up through it.
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), "");
- void *Handle = cantFail(cantFail(LoadResult.get()));
-
- std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
- LookupResult;
- spsLookup(waitFor(LookupResult), Handle, {{MANGLED("malloc"), Req}});
- auto Addrs = cantFail(cantFail(LookupResult.get()));
- ASSERT_EQ(Addrs.size(), 1U);
- ASSERT_TRUE(Addrs[0].has_value())
- << "malloc should be findable via the process's global lookup handle";
- EXPECT_NE(*Addrs[0], nullptr);
-}
-
-TEST_F(NativeDylibManagerSPSCITest, LookupSingleSymbol) {
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
- void *Handle = cantFail(cantFail(LoadResult.get()));
-
- std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
- LookupResult;
- spsLookup(waitFor(LookupResult), Handle,
- {{MANGLED("NativeDylibManagerTestFunc"), Req}});
- auto Addrs = cantFail(cantFail(LookupResult.get()));
- ASSERT_EQ(Addrs.size(), 1U);
- ASSERT_TRUE(Addrs[0].has_value());
- EXPECT_NE(*Addrs[0], nullptr);
-
- auto *Func = reinterpret_cast<int (*)()>(*Addrs[0]);
- EXPECT_EQ(Func(), 42);
-}
-
-TEST_F(NativeDylibManagerSPSCITest, LookupMultipleSymbols) {
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
- void *Handle = cantFail(cantFail(LoadResult.get()));
-
- std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
- LookupResult;
- spsLookup(waitFor(LookupResult), Handle,
- {{MANGLED("NativeDylibManagerTestFunc"), Req},
- {MANGLED("NativeDylibManagerTestFunc2"), Req}});
- auto Addrs = cantFail(cantFail(LookupResult.get()));
- ASSERT_EQ(Addrs.size(), 2U);
- ASSERT_TRUE(Addrs[0].has_value());
- ASSERT_TRUE(Addrs[1].has_value());
- EXPECT_NE(*Addrs[0], nullptr);
- EXPECT_NE(*Addrs[1], nullptr);
-
- auto *Func1 = reinterpret_cast<int (*)()>(*Addrs[0]);
- auto *Func2 = reinterpret_cast<int (*)()>(*Addrs[1]);
- EXPECT_EQ(Func1(), 42);
- EXPECT_EQ(Func2(), 7);
-}
-
-TEST_F(NativeDylibManagerSPSCITest, LookupWeakMissingSymbol) {
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
- void *Handle = cantFail(cantFail(LoadResult.get()));
-
- std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
- LookupResult;
- spsLookup(waitFor(LookupResult), Handle, {{MANGLED("no_such_symbol"), Weak}});
- auto Addrs = cantFail(cantFail(LookupResult.get()));
- ASSERT_EQ(Addrs.size(), 1U);
- ASSERT_TRUE(Addrs[0].has_value())
- << "weak-missing symbol should be reported as a present optional";
- EXPECT_EQ(*Addrs[0], nullptr);
-}
-
-TEST_F(NativeDylibManagerSPSCITest, LookupRequiredMissingSymbol) {
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
- void *Handle = cantFail(cantFail(LoadResult.get()));
-
- std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
- LookupResult;
- spsLookup(waitFor(LookupResult), Handle, {{MANGLED("no_such_symbol"), Req}});
- auto Addrs = cantFail(cantFail(LookupResult.get()));
- ASSERT_EQ(Addrs.size(), 1U);
- EXPECT_FALSE(Addrs[0].has_value())
- << "required-missing symbol should be reported as an empty optional";
-}
-
-TEST_F(NativeDylibManagerSPSCITest, LookupMixedRequiredAndWeak) {
- std::future<Expected<Expected<void *>>> LoadResult;
- spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
- void *Handle = cantFail(cantFail(LoadResult.get()));
-
- std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
- LookupResult;
- spsLookup(waitFor(LookupResult), Handle,
- {{MANGLED("NativeDylibManagerTestFunc"), Req},
- {MANGLED("no_such_symbol"), Weak}});
- auto Addrs = cantFail(cantFail(LookupResult.get()));
- ASSERT_EQ(Addrs.size(), 2U);
- ASSERT_TRUE(Addrs[0].has_value());
- EXPECT_NE(*Addrs[0], nullptr);
- ASSERT_TRUE(Addrs[1].has_value())
- << "weak-missing symbol should be reported as a present optional";
- EXPECT_EQ(*Addrs[1], nullptr);
-}
+//===- NativeDylibManagerSPSCITest.cpp ------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for NativeDylibManager's SPS Controller Interface.
+//
+//===----------------------------------------------------------------------===//
+#ifndef _WIN32
+#include "orc-rt/bedrock/sps/NativeDylibManagerSPSCI.h"
+#include "orc-rt/bedrock/NativeDylibManager.h"
+#include "orc-rt/bedrock/Session.h"
+#include "orc-rt/support/sps/SPSWrapperFunction.h"
+
+#include "BedrockTestUtils.h"
+#include "CommonTestUtils.h"
+#include "DirectCaller.h"
+#include "gtest/gtest.h"
+
+using namespace orc_rt;
+
+namespace orc_rt {
+
+/// SPS serialization for NativeDylibManager::LookupFlags as a bool.
+///
+/// Duplicated from NativeDylibManagerSPSCI.cpp so the test can serialize
+/// SymbolLookupSet values when invoking the SPS wrapper via
+/// SPSWrapperFunction<...>::call.
+template <>
+class SPSSerializationTraits<bool, NativeDylibManager::LookupFlags> {
+public:
+ static size_t size(NativeDylibManager::LookupFlags) { return sizeof(bool); }
+
+ static bool serialize(SPSOutputBuffer &OB,
+ NativeDylibManager::LookupFlags L) {
+ return SPSSerializationTraits<bool, bool>::serialize(
+ OB, L == NativeDylibManager::RequiredSymbol);
+ }
+
+ static bool deserialize(SPSInputBuffer &IB,
+ NativeDylibManager::LookupFlags &L) {
+ bool Required;
+ if (!SPSSerializationTraits<bool, bool>::deserialize(IB, Required))
+ return false;
+ L = Required ? NativeDylibManager::RequiredSymbol
+ : NativeDylibManager::WeaklyReferencedSymbol;
+ return true;
+ }
+};
+
+} // namespace orc_rt
+
+namespace {
+// Local aliases for brevity in test bodies.
+constexpr auto Req = NativeDylibManager::RequiredSymbol;
+constexpr auto Weak = NativeDylibManager::WeaklyReferencedSymbol;
+} // namespace
+
+// Wrap a symbol-name string literal in the platform's linker-mangling.
+// NativeDylibManager::lookup takes linker-mangled names; on Darwin the
+// linker prefixes C names with '_'.
+#if defined(__APPLE__)
+#define MANGLED(name) "_" name
+#else
+#define MANGLED(name) name
+#endif
+
+#ifndef NDM_TEST_LIB_PATH
+#error \
+ "NDM_TEST_LIB_PATH must be defined to the path of the test shared library"
+#endif
+
+static DirectCaller caller(orc_rt_WrapperFunction Fn) { return {nullptr, Fn}; }
+
+class NativeDylibManagerSPSCITest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ S = std::make_unique<Session>(mockExecutorProcessInfo(), noDispatch,
+ noErrors);
+ NDM = cantFail(NativeDylibManager::Create(*S, CI));
+ }
+
+ template <typename OnCompleteFn>
+ void spsLoad(OnCompleteFn &&OnComplete, std::string Path) {
+ using SPSSig = SPSExpected<SPSExecutorAddr>(SPSExecutorAddr, SPSString);
+ SPSWrapperFunction<SPSSig>::call(
+ caller(orc_rt_ci_sps_NativeDylibManager_load),
+ std::forward<OnCompleteFn>(OnComplete), NDM.get(), std::move(Path));
+ }
+
+ template <typename OnCompleteFn>
+ void spsLookup(OnCompleteFn &&OnComplete, void *Handle,
+ NativeDylibManager::SymbolLookupSet Symbols) {
+ using SPSSig = SPSExpected<SPSSequence<SPSOptional<SPSExecutorAddr>>>(
+ SPSExecutorAddr, SPSExecutorAddr,
+ SPSSequence<SPSTuple<SPSString, bool>>);
+ SPSWrapperFunction<SPSSig>::call(
+ caller(orc_rt_ci_sps_NativeDylibManager_lookup),
+ std::forward<OnCompleteFn>(OnComplete), NDM.get(), Handle,
+ std::move(Symbols));
+ }
+
+ SimpleSymbolTable CI;
+ std::unique_ptr<Session> S;
+ std::unique_ptr<NativeDylibManager> NDM;
+};
+
+TEST_F(NativeDylibManagerSPSCITest, Registration) {
+ EXPECT_TRUE(
+ CI.count(SymbolNameSpec::c("orc_rt_ci_sps_NativeDylibManager_load")));
+ EXPECT_TRUE(
+ CI.count(SymbolNameSpec::c("orc_rt_ci_sps_NativeDylibManager_lookup")));
+}
+
+TEST_F(NativeDylibManagerSPSCITest, Load) {
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
+ void *Handle = cantFail(cantFail(LoadResult.get()));
+ EXPECT_NE(Handle, nullptr);
+}
+
+TEST_F(NativeDylibManagerSPSCITest, LoadNonExistent) {
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), "/no/such/library.dylib");
+ auto Handle = cantFail(LoadResult.get());
+ EXPECT_FALSE(!!Handle);
+ consumeError(Handle.takeError());
+}
+
+TEST_F(NativeDylibManagerSPSCITest, LoadEmptyPathReturnsGlobalHandle) {
+ // The global handle's value is implementation-defined, so verify by looking
+ // up through it.
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), "");
+ void *Handle = cantFail(cantFail(LoadResult.get()));
+
+ std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
+ LookupResult;
+ spsLookup(waitFor(LookupResult), Handle, {{MANGLED("malloc"), Req}});
+ auto Addrs = cantFail(cantFail(LookupResult.get()));
+ ASSERT_EQ(Addrs.size(), 1U);
+ ASSERT_TRUE(Addrs[0].has_value())
+ << "malloc should be findable via the process's global lookup handle";
+ EXPECT_NE(*Addrs[0], nullptr);
+}
+
+TEST_F(NativeDylibManagerSPSCITest, LookupSingleSymbol) {
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
+ void *Handle = cantFail(cantFail(LoadResult.get()));
+
+ std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
+ LookupResult;
+ spsLookup(waitFor(LookupResult), Handle,
+ {{MANGLED("NativeDylibManagerTestFunc"), Req}});
+ auto Addrs = cantFail(cantFail(LookupResult.get()));
+ ASSERT_EQ(Addrs.size(), 1U);
+ ASSERT_TRUE(Addrs[0].has_value());
+ EXPECT_NE(*Addrs[0], nullptr);
+
+ auto *Func = reinterpret_cast<int (*)()>(*Addrs[0]);
+ EXPECT_EQ(Func(), 42);
+}
+
+TEST_F(NativeDylibManagerSPSCITest, LookupMultipleSymbols) {
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
+ void *Handle = cantFail(cantFail(LoadResult.get()));
+
+ std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
+ LookupResult;
+ spsLookup(waitFor(LookupResult), Handle,
+ {{MANGLED("NativeDylibManagerTestFunc"), Req},
+ {MANGLED("NativeDylibManagerTestFunc2"), Req}});
+ auto Addrs = cantFail(cantFail(LookupResult.get()));
+ ASSERT_EQ(Addrs.size(), 2U);
+ ASSERT_TRUE(Addrs[0].has_value());
+ ASSERT_TRUE(Addrs[1].has_value());
+ EXPECT_NE(*Addrs[0], nullptr);
+ EXPECT_NE(*Addrs[1], nullptr);
+
+ auto *Func1 = reinterpret_cast<int (*)()>(*Addrs[0]);
+ auto *Func2 = reinterpret_cast<int (*)()>(*Addrs[1]);
+ EXPECT_EQ(Func1(), 42);
+ EXPECT_EQ(Func2(), 7);
+}
+
+TEST_F(NativeDylibManagerSPSCITest, LookupWeakMissingSymbol) {
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
+ void *Handle = cantFail(cantFail(LoadResult.get()));
+
+ std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
+ LookupResult;
+ spsLookup(waitFor(LookupResult), Handle, {{MANGLED("no_such_symbol"), Weak}});
+ auto Addrs = cantFail(cantFail(LookupResult.get()));
+ ASSERT_EQ(Addrs.size(), 1U);
+ ASSERT_TRUE(Addrs[0].has_value())
+ << "weak-missing symbol should be reported as a present optional";
+ EXPECT_EQ(*Addrs[0], nullptr);
+}
+
+TEST_F(NativeDylibManagerSPSCITest, LookupRequiredMissingSymbol) {
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
+ void *Handle = cantFail(cantFail(LoadResult.get()));
+
+ std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
+ LookupResult;
+ spsLookup(waitFor(LookupResult), Handle, {{MANGLED("no_such_symbol"), Req}});
+ auto Addrs = cantFail(cantFail(LookupResult.get()));
+ ASSERT_EQ(Addrs.size(), 1U);
+ EXPECT_FALSE(Addrs[0].has_value())
+ << "required-missing symbol should be reported as an empty optional";
+}
+
+TEST_F(NativeDylibManagerSPSCITest, LookupMixedRequiredAndWeak) {
+ std::future<Expected<Expected<void *>>> LoadResult;
+ spsLoad(waitFor(LoadResult), NDM_TEST_LIB_PATH);
+ void *Handle = cantFail(cantFail(LoadResult.get()));
+
+ std::future<Expected<Expected<std::vector<std::optional<void *>>>>>
+ LookupResult;
+ spsLookup(waitFor(LookupResult), Handle,
+ {{MANGLED("NativeDylibManagerTestFunc"), Req},
+ {MANGLED("no_such_symbol"), Weak}});
+ auto Addrs = cantFail(cantFail(LookupResult.get()));
+ ASSERT_EQ(Addrs.size(), 2U);
+ ASSERT_TRUE(Addrs[0].has_value());
+ EXPECT_NE(*Addrs[0], nullptr);
+ ASSERT_TRUE(Addrs[1].has_value())
+ << "weak-missing symbol should be reported as a present optional";
+ EXPECT_EQ(*Addrs[1], nullptr);
+}
+#endif
diff --git a/orc-rt/test/unit/bedrock/sps/SimpleNativeMemoryMapSPSCITest.cpp b/orc-rt/test/unit/bedrock/sps/SimpleNativeMemoryMapSPSCITest.cpp
index e455afb209574..16e7f21094b30 100644
--- a/orc-rt/test/unit/bedrock/sps/SimpleNativeMemoryMapSPSCITest.cpp
+++ b/orc-rt/test/unit/bedrock/sps/SimpleNativeMemoryMapSPSCITest.cpp
@@ -1,323 +1,324 @@
-//===- SimpleNativeMemoryMapSPSControllerInterfaceTest.cpp ----------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for SimpleNativeMemoryMap's SPS Controller Interface.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/bedrock/sps/SimpleNativeMemoryMapSPSCI.h"
-#include "orc-rt/bedrock/Session.h"
-#include "orc-rt/bedrock/SimpleNativeMemoryMap.h"
-#include "orc-rt/support/sps/SPSAllocAction.h"
-#include "orc-rt/support/sps/SPSMemoryFlags.h"
-#include "orc-rt/support/sps/SPSWrapperFunction.h"
-
-#include "AllocActionTestUtils.h"
-#include "BedrockTestUtils.h"
-#include "CommonTestUtils.h"
-#include "DirectCaller.h"
-#include "gtest/gtest.h"
-
-using namespace orc_rt;
-
-namespace orc_rt {
-
-struct SPSSimpleNativeMemoryMapSegment;
-struct SPSSimpleNativeMemoryMapInitializeRequest;
-
-/// A SimpleNativeMemoryMap::InitializeRequest::Segment plus segment content (if
-/// segment content type is regular).
-struct TestSNMMSegment
- : public SimpleNativeMemoryMap::InitializeRequest::Segment {
-
- TestSNMMSegment(AllocGroup AG, char *Address, size_t Size,
- std::vector<char> C = {})
- : SimpleNativeMemoryMap::InitializeRequest::Segment(
- {AG, Address, Size, {}}),
- OwnedContent(std::move(C)) {
- this->Content = {OwnedContent.data(), OwnedContent.size()};
- }
-
- std::vector<char> OwnedContent;
-};
-
-template <>
-class SPSSerializationTraits<SPSSimpleNativeMemoryMapSegment, TestSNMMSegment> {
- using SPSType =
- SPSTuple<SPSAllocGroup, SPSExecutorAddr, uint64_t, SPSSequence<char>>;
-
-public:
- static size_t size(const TestSNMMSegment &S) {
- return SPSType::AsArgList::size(S.AG, ExecutorAddr::fromPtr(S.Address),
- static_cast<uint64_t>(S.Size), S.Content);
- }
-
- static bool serialize(SPSOutputBuffer &OB, const TestSNMMSegment &S) {
- return SPSType::AsArgList::serialize(
- OB, S.AG, ExecutorAddr::fromPtr(S.Address),
- static_cast<uint64_t>(S.Size), S.Content);
- }
-};
-
-struct TestSNMMInitializeRequest {
- std::vector<TestSNMMSegment> Segments;
- std::vector<AllocActionPair> AAPs;
-};
-
-template <>
-class SPSSerializationTraits<SPSSimpleNativeMemoryMapInitializeRequest,
- TestSNMMInitializeRequest> {
- using SPSType = SPSTuple<SPSSequence<SPSSimpleNativeMemoryMapSegment>,
- SPSSequence<SPSAllocActionPair>>;
-
-public:
- static size_t size(const TestSNMMInitializeRequest &IR) {
- return SPSType::AsArgList::size(IR.Segments, IR.AAPs);
- }
- static bool serialize(SPSOutputBuffer &OB,
- const TestSNMMInitializeRequest &IR) {
- return SPSType::AsArgList::serialize(OB, IR.Segments, IR.AAPs);
- }
-};
-
-} // namespace orc_rt
-
-// Write the given value to the address pointed to by P.
-static orc_rt_WrapperFunctionBuffer
-write_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
- return SPSAllocActionFunction<SPSExecutorAddr, uint64_t>::handle(
- ArgData, ArgSize,
- [](ExecutorAddr P, uint64_t Val) {
- *P.toPtr<uint64_t *>() = Val;
- return WrapperFunctionBuffer();
- })
- .release();
-}
-
-// Read the uint64_t value at Src and write it to Dst.
-static orc_rt_WrapperFunctionBuffer
-read_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
- return SPSAllocActionFunction<SPSExecutorAddr, SPSExecutorAddr>::handle(
- ArgData, ArgSize,
- [](ExecutorAddr Dst, ExecutorAddr Src) {
- *Dst.toPtr<uint64_t *>() = *Src.toPtr<uint64_t *>();
- return WrapperFunctionBuffer();
- })
- .release();
-}
-
-DirectCaller caller(orc_rt_WrapperFunction Fn) { return {nullptr, Fn}; }
-
-class SimpleNativeMemoryMapSPSCITest : public ::testing::Test {
-protected:
- void SetUp() override {
- S = std::make_unique<Session>(mockExecutorProcessInfo(), noDispatch,
- noErrors);
- SNMM = cantFail(SimpleNativeMemoryMap::Create(*S, CI));
- }
-
- void TearDown() override {
- if (SNMM) {
- std::future<void> F;
- SNMM->onShutdown(waitFor(F));
- F.get();
- }
- }
-
- template <typename OnCompleteFn>
- void spsReserve(OnCompleteFn &&OnComplete, size_t Size) {
- using SPSSig = SPSExpected<SPSExecutorAddr>(SPSExecutorAddr, SPSSize);
- SPSWrapperFunction<SPSSig>::call(
- caller(orc_rt_ci_sps_SimpleNativeMemoryMap_reserve),
- std::forward<OnCompleteFn>(OnComplete), SNMM.get(), Size);
- }
-
- template <typename OnCompleteFn>
- void spsReleaseMultiple(OnCompleteFn &&OnComplete, span<void *> Addrs) {
- using SPSSig = SPSError(SPSExecutorAddr, SPSSequence<SPSExecutorAddr>);
- SPSWrapperFunction<SPSSig>::call(
- caller(orc_rt_ci_sps_SimpleNativeMemoryMap_releaseMultiple),
- std::forward<OnCompleteFn>(OnComplete), SNMM.get(), Addrs);
- }
-
- template <typename OnCompleteFn>
- void spsInitialize(OnCompleteFn &&OnComplete, TestSNMMInitializeRequest IR) {
- using SPSSig = SPSExpected<SPSExecutorAddr>(
- SPSExecutorAddr, SPSSimpleNativeMemoryMapInitializeRequest);
- SPSWrapperFunction<SPSSig>::call(
- caller(orc_rt_ci_sps_SimpleNativeMemoryMap_initialize),
- std::forward<OnCompleteFn>(OnComplete), SNMM.get(), std::move(IR));
- }
-
- template <typename OnCompleteFn>
- void spsDeinitializeMultiple(OnCompleteFn &&OnComplete, span<void *> Bases) {
- using SPSSig = SPSError(SPSExecutorAddr, SPSSequence<SPSExecutorAddr>);
- SPSWrapperFunction<SPSSig>::call(
- caller(orc_rt_ci_sps_SimpleNativeMemoryMap_deinitializeMultiple),
- std::forward<OnCompleteFn>(OnComplete), SNMM.get(), Bases);
- }
-
- SimpleSymbolTable CI;
- std::unique_ptr<Session> S;
- std::unique_ptr<SimpleNativeMemoryMap> SNMM;
-};
-
-TEST_F(SimpleNativeMemoryMapSPSCITest, Registration) {
-
- EXPECT_TRUE(CI.count(
- SymbolNameSpec::c("orc_rt_ci_sps_SimpleNativeMemoryMap_reserve")));
- EXPECT_TRUE(CI.count(SymbolNameSpec::c(
- "orc_rt_ci_sps_SimpleNativeMemoryMap_releaseMultiple")));
- EXPECT_TRUE(CI.count(
- SymbolNameSpec::c("orc_rt_ci_sps_SimpleNativeMemoryMap_initialize")));
- EXPECT_TRUE(CI.count(SymbolNameSpec::c(
- "orc_rt_ci_sps_SimpleNativeMemoryMap_deinitializeMultiple")));
-}
-
-TEST_F(SimpleNativeMemoryMapSPSCITest, ReserveAndRelease) {
- std::future<Expected<Expected<void *>>> ReserveAddr;
- spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
- auto *Addr = cantFail(cantFail(ReserveAddr.get()));
-
- std::future<Expected<Error>> ReleaseResult;
- spsReleaseMultiple(waitFor(ReleaseResult), {&Addr, 1});
- cantFail(cantFail(ReleaseResult.get()));
-}
-
-TEST_F(SimpleNativeMemoryMapSPSCITest, FullPipelineForOneRWSegment) {
- std::future<Expected<Expected<void *>>> ReserveAddr;
- spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
- void *Addr = cantFail(cantFail(ReserveAddr.get()));
-
- std::future<Expected<Expected<void *>>> InitializeKey;
- TestSNMMInitializeRequest IR;
- char *InitializeBase = reinterpret_cast<char *>(Addr) + 64 * 1024;
- uint64_t SentinelValue1 = 0;
- uint64_t SentinelValue2 = 0;
- uint64_t SentinelValue3 = 42;
-
- std::vector<char> Content;
- Content.resize(sizeof(uint64_t) * 2);
- memcpy(Content.data(), &SentinelValue3, sizeof(uint64_t));
- memcpy(Content.data() + sizeof(uint64_t), &SentinelValue1, sizeof(uint64_t));
-
- IR.Segments.push_back({MemProt::Read | MemProt::Write, InitializeBase,
- 64 * 1024, std::move(Content)});
-
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue1),
- ExecutorAddr::fromPtr(InitializeBase)),
- {}});
-
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
- write_value_sps_allocaction,
- ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t),
- uint64_t(42)),
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue2),
- ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t))});
-
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue3),
- ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t) * 2),
- {}});
-
- spsInitialize(waitFor(InitializeKey), std::move(IR));
- void *InitializeKeyAddr = cantFail(cantFail(InitializeKey.get()));
-
- EXPECT_EQ(SentinelValue1, 42U);
- EXPECT_EQ(SentinelValue2, 0U);
- EXPECT_EQ(SentinelValue3, 0U);
-
- std::future<Expected<Error>> DeallocResult;
- spsDeinitializeMultiple(waitFor(DeallocResult), {&InitializeKeyAddr, 1});
- cantFail(cantFail(DeallocResult.get()));
-
- EXPECT_EQ(SentinelValue1, 42U);
- EXPECT_EQ(SentinelValue2, 42U);
- EXPECT_EQ(SentinelValue3, 0U);
-
- std::future<Expected<Error>> ReleaseResult;
- spsReleaseMultiple(waitFor(ReleaseResult), {&Addr, 1});
- cantFail(cantFail(ReleaseResult.get()));
-}
-
-TEST_F(SimpleNativeMemoryMapSPSCITest, ReserveInitializeShutdown) {
- std::future<Expected<Expected<void *>>> ReserveAddr;
- spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
- void *Addr = cantFail(cantFail(ReserveAddr.get()));
-
- std::future<Expected<Expected<void *>>> InitializeKey;
- TestSNMMInitializeRequest IR;
- char *InitializeBase = reinterpret_cast<char *>(Addr) + 64 * 1024;
- uint64_t SentinelValue = 0;
-
- IR.Segments.push_back(
- {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024});
-
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
- write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
- uint64_t(42)),
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
- ExecutorAddr::fromPtr(InitializeBase))});
- spsInitialize(waitFor(InitializeKey), std::move(IR));
- cantFail(cantFail(InitializeKey.get()));
-
- EXPECT_EQ(SentinelValue, 0U);
-
- std::future<void> ShutdownResult;
- SNMM->onShutdown(waitFor(ShutdownResult));
- ShutdownResult.get();
- SNMM.reset();
-
- EXPECT_EQ(SentinelValue, 42);
-}
-
-TEST_F(SimpleNativeMemoryMapSPSCITest, ReserveInitializeDetachShutdown) {
- std::future<Expected<Expected<void *>>> ReserveAddr;
- spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
- void *Addr = cantFail(cantFail(ReserveAddr.get()));
-
- std::future<Expected<Expected<void *>>> InitializeKey;
- TestSNMMInitializeRequest IR;
- char *InitializeBase = reinterpret_cast<char *>(Addr) + 64 * 1024;
- uint64_t SentinelValue = 0;
-
- IR.Segments.push_back(
- {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024});
-
- IR.AAPs.push_back(
- {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
- write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
- uint64_t(42)),
- *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
- read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
- ExecutorAddr::fromPtr(InitializeBase))});
- spsInitialize(waitFor(InitializeKey), std::move(IR));
- cantFail(cantFail(InitializeKey.get()));
-
- EXPECT_EQ(SentinelValue, 0U);
-
- std::future<void> DetachResult;
- SNMM->onDetach(waitFor(DetachResult), /* ShutdownRequested */ false);
- DetachResult.get();
-
- EXPECT_EQ(SentinelValue, 0);
-
- std::future<void> ShutdownResult;
- SNMM->onShutdown(waitFor(ShutdownResult));
- ShutdownResult.get();
- SNMM.reset();
-
- EXPECT_EQ(SentinelValue, 42);
-}
+//===- SimpleNativeMemoryMapSPSControllerInterfaceTest.cpp ----------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for SimpleNativeMemoryMap's SPS Controller Interface.
+//
+//===----------------------------------------------------------------------===//
+#ifndef _WIN32
+#include "orc-rt/bedrock/sps/SimpleNativeMemoryMapSPSCI.h"
+#include "orc-rt/bedrock/Session.h"
+#include "orc-rt/bedrock/SimpleNativeMemoryMap.h"
+#include "orc-rt/support/sps/SPSAllocAction.h"
+#include "orc-rt/support/sps/SPSMemoryFlags.h"
+#include "orc-rt/support/sps/SPSWrapperFunction.h"
+
+#include "AllocActionTestUtils.h"
+#include "BedrockTestUtils.h"
+#include "CommonTestUtils.h"
+#include "DirectCaller.h"
+#include "gtest/gtest.h"
+
+using namespace orc_rt;
+
+namespace orc_rt {
+
+struct SPSSimpleNativeMemoryMapSegment;
+struct SPSSimpleNativeMemoryMapInitializeRequest;
+
+/// A SimpleNativeMemoryMap::InitializeRequest::Segment plus segment content (if
+/// segment content type is regular).
+struct TestSNMMSegment
+ : public SimpleNativeMemoryMap::InitializeRequest::Segment {
+
+ TestSNMMSegment(AllocGroup AG, char *Address, size_t Size,
+ std::vector<char> C = {})
+ : SimpleNativeMemoryMap::InitializeRequest::Segment(
+ {AG, Address, Size, {}}),
+ OwnedContent(std::move(C)) {
+ this->Content = {OwnedContent.data(), OwnedContent.size()};
+ }
+
+ std::vector<char> OwnedContent;
+};
+
+template <>
+class SPSSerializationTraits<SPSSimpleNativeMemoryMapSegment, TestSNMMSegment> {
+ using SPSType =
+ SPSTuple<SPSAllocGroup, SPSExecutorAddr, uint64_t, SPSSequence<char>>;
+
+public:
+ static size_t size(const TestSNMMSegment &S) {
+ return SPSType::AsArgList::size(S.AG, ExecutorAddr::fromPtr(S.Address),
+ static_cast<uint64_t>(S.Size), S.Content);
+ }
+
+ static bool serialize(SPSOutputBuffer &OB, const TestSNMMSegment &S) {
+ return SPSType::AsArgList::serialize(
+ OB, S.AG, ExecutorAddr::fromPtr(S.Address),
+ static_cast<uint64_t>(S.Size), S.Content);
+ }
+};
+
+struct TestSNMMInitializeRequest {
+ std::vector<TestSNMMSegment> Segments;
+ std::vector<AllocActionPair> AAPs;
+};
+
+template <>
+class SPSSerializationTraits<SPSSimpleNativeMemoryMapInitializeRequest,
+ TestSNMMInitializeRequest> {
+ using SPSType = SPSTuple<SPSSequence<SPSSimpleNativeMemoryMapSegment>,
+ SPSSequence<SPSAllocActionPair>>;
+
+public:
+ static size_t size(const TestSNMMInitializeRequest &IR) {
+ return SPSType::AsArgList::size(IR.Segments, IR.AAPs);
+ }
+ static bool serialize(SPSOutputBuffer &OB,
+ const TestSNMMInitializeRequest &IR) {
+ return SPSType::AsArgList::serialize(OB, IR.Segments, IR.AAPs);
+ }
+};
+
+} // namespace orc_rt
+
+// Write the given value to the address pointed to by P.
+static orc_rt_WrapperFunctionBuffer
+write_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
+ return SPSAllocActionFunction<SPSExecutorAddr, uint64_t>::handle(
+ ArgData, ArgSize,
+ [](ExecutorAddr P, uint64_t Val) {
+ *P.toPtr<uint64_t *>() = Val;
+ return WrapperFunctionBuffer();
+ })
+ .release();
+}
+
+// Read the uint64_t value at Src and write it to Dst.
+static orc_rt_WrapperFunctionBuffer
+read_value_sps_allocaction(const char *ArgData, size_t ArgSize) {
+ return SPSAllocActionFunction<SPSExecutorAddr, SPSExecutorAddr>::handle(
+ ArgData, ArgSize,
+ [](ExecutorAddr Dst, ExecutorAddr Src) {
+ *Dst.toPtr<uint64_t *>() = *Src.toPtr<uint64_t *>();
+ return WrapperFunctionBuffer();
+ })
+ .release();
+}
+
+DirectCaller caller(orc_rt_WrapperFunction Fn) { return {nullptr, Fn}; }
+
+class SimpleNativeMemoryMapSPSCITest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ S = std::make_unique<Session>(mockExecutorProcessInfo(), noDispatch,
+ noErrors);
+ SNMM = cantFail(SimpleNativeMemoryMap::Create(*S, CI));
+ }
+
+ void TearDown() override {
+ if (SNMM) {
+ std::future<void> F;
+ SNMM->onShutdown(waitFor(F));
+ F.get();
+ }
+ }
+
+ template <typename OnCompleteFn>
+ void spsReserve(OnCompleteFn &&OnComplete, size_t Size) {
+ using SPSSig = SPSExpected<SPSExecutorAddr>(SPSExecutorAddr, SPSSize);
+ SPSWrapperFunction<SPSSig>::call(
+ caller(orc_rt_ci_sps_SimpleNativeMemoryMap_reserve),
+ std::forward<OnCompleteFn>(OnComplete), SNMM.get(), Size);
+ }
+
+ template <typename OnCompleteFn>
+ void spsReleaseMultiple(OnCompleteFn &&OnComplete, span<void *> Addrs) {
+ using SPSSig = SPSError(SPSExecutorAddr, SPSSequence<SPSExecutorAddr>);
+ SPSWrapperFunction<SPSSig>::call(
+ caller(orc_rt_ci_sps_SimpleNativeMemoryMap_releaseMultiple),
+ std::forward<OnCompleteFn>(OnComplete), SNMM.get(), Addrs);
+ }
+
+ template <typename OnCompleteFn>
+ void spsInitialize(OnCompleteFn &&OnComplete, TestSNMMInitializeRequest IR) {
+ using SPSSig = SPSExpected<SPSExecutorAddr>(
+ SPSExecutorAddr, SPSSimpleNativeMemoryMapInitializeRequest);
+ SPSWrapperFunction<SPSSig>::call(
+ caller(orc_rt_ci_sps_SimpleNativeMemoryMap_initialize),
+ std::forward<OnCompleteFn>(OnComplete), SNMM.get(), std::move(IR));
+ }
+
+ template <typename OnCompleteFn>
+ void spsDeinitializeMultiple(OnCompleteFn &&OnComplete, span<void *> Bases) {
+ using SPSSig = SPSError(SPSExecutorAddr, SPSSequence<SPSExecutorAddr>);
+ SPSWrapperFunction<SPSSig>::call(
+ caller(orc_rt_ci_sps_SimpleNativeMemoryMap_deinitializeMultiple),
+ std::forward<OnCompleteFn>(OnComplete), SNMM.get(), Bases);
+ }
+
+ SimpleSymbolTable CI;
+ std::unique_ptr<Session> S;
+ std::unique_ptr<SimpleNativeMemoryMap> SNMM;
+};
+
+TEST_F(SimpleNativeMemoryMapSPSCITest, Registration) {
+
+ EXPECT_TRUE(CI.count(
+ SymbolNameSpec::c("orc_rt_ci_sps_SimpleNativeMemoryMap_reserve")));
+ EXPECT_TRUE(CI.count(SymbolNameSpec::c(
+ "orc_rt_ci_sps_SimpleNativeMemoryMap_releaseMultiple")));
+ EXPECT_TRUE(CI.count(
+ SymbolNameSpec::c("orc_rt_ci_sps_SimpleNativeMemoryMap_initialize")));
+ EXPECT_TRUE(CI.count(SymbolNameSpec::c(
+ "orc_rt_ci_sps_SimpleNativeMemoryMap_deinitializeMultiple")));
+}
+
+TEST_F(SimpleNativeMemoryMapSPSCITest, ReserveAndRelease) {
+ std::future<Expected<Expected<void *>>> ReserveAddr;
+ spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
+ auto *Addr = cantFail(cantFail(ReserveAddr.get()));
+
+ std::future<Expected<Error>> ReleaseResult;
+ spsReleaseMultiple(waitFor(ReleaseResult), {&Addr, 1});
+ cantFail(cantFail(ReleaseResult.get()));
+}
+
+TEST_F(SimpleNativeMemoryMapSPSCITest, FullPipelineForOneRWSegment) {
+ std::future<Expected<Expected<void *>>> ReserveAddr;
+ spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
+ void *Addr = cantFail(cantFail(ReserveAddr.get()));
+
+ std::future<Expected<Expected<void *>>> InitializeKey;
+ TestSNMMInitializeRequest IR;
+ char *InitializeBase = reinterpret_cast<char *>(Addr) + 64 * 1024;
+ uint64_t SentinelValue1 = 0;
+ uint64_t SentinelValue2 = 0;
+ uint64_t SentinelValue3 = 42;
+
+ std::vector<char> Content;
+ Content.resize(sizeof(uint64_t) * 2);
+ memcpy(Content.data(), &SentinelValue3, sizeof(uint64_t));
+ memcpy(Content.data() + sizeof(uint64_t), &SentinelValue1, sizeof(uint64_t));
+
+ IR.Segments.push_back({MemProt::Read | MemProt::Write, InitializeBase,
+ 64 * 1024, std::move(Content)});
+
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue1),
+ ExecutorAddr::fromPtr(InitializeBase)),
+ {}});
+
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
+ write_value_sps_allocaction,
+ ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t),
+ uint64_t(42)),
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue2),
+ ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t))});
+
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue3),
+ ExecutorAddr::fromPtr(InitializeBase) + sizeof(uint64_t) * 2),
+ {}});
+
+ spsInitialize(waitFor(InitializeKey), std::move(IR));
+ void *InitializeKeyAddr = cantFail(cantFail(InitializeKey.get()));
+
+ EXPECT_EQ(SentinelValue1, 42U);
+ EXPECT_EQ(SentinelValue2, 0U);
+ EXPECT_EQ(SentinelValue3, 0U);
+
+ std::future<Expected<Error>> DeallocResult;
+ spsDeinitializeMultiple(waitFor(DeallocResult), {&InitializeKeyAddr, 1});
+ cantFail(cantFail(DeallocResult.get()));
+
+ EXPECT_EQ(SentinelValue1, 42U);
+ EXPECT_EQ(SentinelValue2, 42U);
+ EXPECT_EQ(SentinelValue3, 0U);
+
+ std::future<Expected<Error>> ReleaseResult;
+ spsReleaseMultiple(waitFor(ReleaseResult), {&Addr, 1});
+ cantFail(cantFail(ReleaseResult.get()));
+}
+
+TEST_F(SimpleNativeMemoryMapSPSCITest, ReserveInitializeShutdown) {
+ std::future<Expected<Expected<void *>>> ReserveAddr;
+ spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
+ void *Addr = cantFail(cantFail(ReserveAddr.get()));
+
+ std::future<Expected<Expected<void *>>> InitializeKey;
+ TestSNMMInitializeRequest IR;
+ char *InitializeBase = reinterpret_cast<char *>(Addr) + 64 * 1024;
+ uint64_t SentinelValue = 0;
+
+ IR.Segments.push_back(
+ {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024});
+
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
+ write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
+ uint64_t(42)),
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
+ ExecutorAddr::fromPtr(InitializeBase))});
+ spsInitialize(waitFor(InitializeKey), std::move(IR));
+ cantFail(cantFail(InitializeKey.get()));
+
+ EXPECT_EQ(SentinelValue, 0U);
+
+ std::future<void> ShutdownResult;
+ SNMM->onShutdown(waitFor(ShutdownResult));
+ ShutdownResult.get();
+ SNMM.reset();
+
+ EXPECT_EQ(SentinelValue, 42);
+}
+
+TEST_F(SimpleNativeMemoryMapSPSCITest, ReserveInitializeDetachShutdown) {
+ std::future<Expected<Expected<void *>>> ReserveAddr;
+ spsReserve(waitFor(ReserveAddr), 1024 * 1024 * 1024);
+ void *Addr = cantFail(cantFail(ReserveAddr.get()));
+
+ std::future<Expected<Expected<void *>>> InitializeKey;
+ TestSNMMInitializeRequest IR;
+ char *InitializeBase = reinterpret_cast<char *>(Addr) + 64 * 1024;
+ uint64_t SentinelValue = 0;
+
+ IR.Segments.push_back(
+ {MemProt::Read | MemProt::Write, InitializeBase, 64 * 1024});
+
+ IR.AAPs.push_back(
+ {*MakeAllocAction<SPSExecutorAddr, uint64_t>::from(
+ write_value_sps_allocaction, ExecutorAddr::fromPtr(InitializeBase),
+ uint64_t(42)),
+ *MakeAllocAction<SPSExecutorAddr, SPSExecutorAddr>::from(
+ read_value_sps_allocaction, ExecutorAddr::fromPtr(&SentinelValue),
+ ExecutorAddr::fromPtr(InitializeBase))});
+ spsInitialize(waitFor(InitializeKey), std::move(IR));
+ cantFail(cantFail(InitializeKey.get()));
+
+ EXPECT_EQ(SentinelValue, 0U);
+
+ std::future<void> DetachResult;
+ SNMM->onDetach(waitFor(DetachResult), /* ShutdownRequested */ false);
+ DetachResult.get();
+
+ EXPECT_EQ(SentinelValue, 0);
+
+ std::future<void> ShutdownResult;
+ SNMM->onShutdown(waitFor(ShutdownResult));
+ ShutdownResult.get();
+ SNMM.reset();
+
+ EXPECT_EQ(SentinelValue, 42);
+}
+#endif
diff --git a/orc-rt/test/unit/bedrock/sps/SimpleRemoteCATest.cpp b/orc-rt/test/unit/bedrock/sps/SimpleRemoteCATest.cpp
index 879f415c5b433..8d248179e8791 100644
--- a/orc-rt/test/unit/bedrock/sps/SimpleRemoteCATest.cpp
+++ b/orc-rt/test/unit/bedrock/sps/SimpleRemoteCATest.cpp
@@ -1,286 +1,287 @@
-//===- SimpleRemoteCATest.cpp ---------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for the transport-independent half of the SimpleRemote protocol.
-//
-// These cover the payload encodings and the pending-call table on their own.
-// When a call may be registered, what ends a session, and who notifies the
-// Session are all the transport's to decide, and are tested with it.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/bedrock/sps/SimpleRemoteCA.h"
-
-#include "gtest/gtest.h"
-
-#include "BedrockTestUtils.h"
-#include "CommonTestUtils.h"
-
-#include "orc-rt/support/sps/SimplePackedSerialization.h"
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-using namespace orc_rt;
-
-namespace {
-
-/// Exposes the protected utilities, and captures the handler that
-/// Session::callController hands over so tests have a real one to register.
-class TestCA : public SimpleRemoteCA {
-public:
- using ControllerAccess::failPendingControllerCall;
- using ControllerAccess::OnControllerCallReturn;
- using SimpleRemoteCA::decodeHangup;
- using SimpleRemoteCA::decodeResult;
- using SimpleRemoteCA::encodeHangup;
- using SimpleRemoteCA::encodeResult;
- using SimpleRemoteCA::encodeSetup;
- using SimpleRemoteCA::handleMessage;
- using SimpleRemoteCA::Opcode;
- using SimpleRemoteCA::PendingCallsMap;
- using SimpleRemoteCA::registerCall;
- using SimpleRemoteCA::ResultKind;
- using SimpleRemoteCA::takeAllCalls;
- using SimpleRemoteCA::takeCall;
-
- TestCA(Session &S, TestCA **Self = nullptr) : SimpleRemoteCA(S) {
- if (Self)
- *Self = this;
- }
-
- void connect(BootstrapInfo BI) override {}
-
- void disconnect() override {
- // What a transport owes on the way out: fail what is pending, then notify.
- for (auto &[SeqNo, OnComplete] : takeAllCalls())
- failPendingControllerCall(std::move(OnComplete));
- notifyDisconnected(Error::success());
- }
-
- void callController(OnControllerCallReturn OnComplete,
- orc_rt_ControllerHandlerTag T,
- WrapperFunctionBuffer ArgBytes) override {
- Captured = std::move(OnComplete);
- }
-
- void sendWrapperResult(WrapperFunctionBuffer ResultBytes,
- uint64_t CallId) override {}
-
- /// Single-threaded here, so no lock: a real transport takes its own.
- OnControllerCallReturn takePendingCall(uint64_t SeqNo) override {
- return takeCall(SeqNo);
- }
-
- /// A handler taken from the Session, for registering.
- OnControllerCallReturn Captured;
-};
-
-/// Drives Session::callController once and returns the handler it produced.
-TestCA::OnControllerCallReturn borrowHandler(Session &S, TestCA &CA) {
- S.callController([](WrapperFunctionBuffer) {}, nullptr,
- WrapperFunctionBuffer());
- return std::move(CA.Captured);
-}
-
-} // namespace
-
-TEST(SimpleRemoteCATest, SetupMessageRoundTrips) {
- // The setup payload's wire format is shared with the controller (it matches
- // LLVM's SPSSimpleRemoteEPCExecutorInfo), so pin the field order and types by
- // decoding a payload the encoder produced.
- using SPSSetup = SPSTuple<SPSString, uint64_t,
- SPSSequence<SPSTuple<SPSString, SPSSequence<char>>>,
- SPSSequence<SPSTuple<SPSString, SPSExecutorAddr>>>;
-
- Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
-
- int SomeSymbol = 0;
- SimpleSymbolTable Symbols;
- std::vector<std::pair<SymbolNameSpec, const void *>> SymbolDefs = {
- {SymbolNameSpec::linker("foo"), &SomeSymbol}};
- cantFail(Symbols.addUnique(SymbolDefs));
-
- BootstrapInfo BI(S, std::move(Symbols),
- BootstrapInfo::ValueMap{{"key", "value"}});
- auto Payload = TestCA::encodeSetup(BI);
-
- std::string Triple;
- uint64_t PageSize = 0;
- std::unordered_map<std::string, std::string> Values;
- std::unordered_map<std::string, ExecutorAddr> DecodedSymbols;
- SPSInputBuffer IB(Payload.data(), Payload.size());
- ASSERT_TRUE(SPSSetup::AsArgList::deserialize(IB, Triple, PageSize, Values,
- DecodedSymbols));
-
- EXPECT_EQ(Triple, S.processInfo().targetTriple());
- EXPECT_EQ(PageSize, S.processInfo().pageSize());
- EXPECT_EQ(Values,
- (std::unordered_map<std::string, std::string>{{"key", "value"}}));
- EXPECT_EQ(DecodedSymbols, (std::unordered_map<std::string, ExecutorAddr>{
- {"foo", ExecutorAddr::fromPtr(&SomeSymbol)}}));
-
- // The payload holds exactly the setup fields: no padding, and nothing the
- // controller would be left to interpret.
- EXPECT_EQ(static_cast<size_t>(IB.data() - Payload.data()), Payload.size());
-
- S.detach([] {});
-}
-
-TEST(SimpleRemoteCATest, OrderlyHangupRoundTrips) {
- // Both ends encode and decode hang-ups through these, so a success value must
- // survive the trip as a success.
- auto Err = TestCA::decodeHangup(TestCA::encodeHangup(Error::success()));
- EXPECT_FALSE(!!Err) << "an orderly hang-up is not an error";
-}
-
-TEST(SimpleRemoteCATest, HangupReasonRoundTrips) {
- auto Err = TestCA::decodeHangup(
- TestCA::encodeHangup(make_error<StringError>("controller ran out of x")));
- ASSERT_TRUE(!!Err);
- EXPECT_EQ(toString(std::move(Err)), "controller ran out of x");
-}
-
-TEST(SimpleRemoteCATest, DecodeHangupRejectsAnEmptyPayload) {
- // Never valid: the two ends are rev-locked, so this is a bug in the peer
- // rather than version skew. It comes back as an error like any other reason,
- // since both outcomes end the session.
- auto Err = TestCA::decodeHangup(WrapperFunctionBuffer());
- ASSERT_TRUE(!!Err);
- EXPECT_EQ(toString(std::move(Err)),
- "Malformed hang-up message: could not deserialize reason");
-}
-
-TEST(SimpleRemoteCATest, ResultValueRoundTrips) {
- constexpr std::string_view Content = "result bytes";
- auto [Kind, Payload] = TestCA::encodeResult(
- WrapperFunctionBuffer::copyFrom(Content.data(), Content.size()));
- EXPECT_EQ(Kind, TestCA::ResultKind::Value);
-
- auto R = TestCA::decodeResult(Kind, std::move(Payload));
- EXPECT_EQ(R.getOutOfBandError(), nullptr);
- EXPECT_EQ(std::string_view(R.data(), R.size()), Content);
-}
-
-TEST(SimpleRemoteCATest, EmptyResultRoundTrips) {
- // What a void-returning wrapper produces. An empty buffer shares 'no size'
- // with an out-of-band error, so check it is not mistaken for one.
- auto [Kind, Payload] = TestCA::encodeResult(WrapperFunctionBuffer());
- EXPECT_EQ(Kind, TestCA::ResultKind::Value);
-
- auto R = TestCA::decodeResult(Kind, std::move(Payload));
- EXPECT_TRUE(R.empty());
-}
-
-TEST(SimpleRemoteCATest, OutOfBandErrorResultRoundTrips) {
- // An out-of-band error is a pointer to a message rather than a serialized
- // value, so it cannot travel as an ordinary payload. It goes out under its
- // own result kind, and must arrive as an out-of-band error again -- otherwise
- // the caller is told its call succeeded with no result.
- constexpr const char *Msg = "Could not deserialize wrapper function arg data";
- auto [Kind, Payload] =
- TestCA::encodeResult(WrapperFunctionBuffer::createOutOfBandError(Msg));
- EXPECT_EQ(Kind, TestCA::ResultKind::OutOfBandError);
-
- auto R = TestCA::decodeResult(Kind, std::move(Payload));
- ASSERT_NE(R.getOutOfBandError(), nullptr);
- EXPECT_STREQ(R.getOutOfBandError(), Msg);
-}
-
-TEST(SimpleRemoteCATest, ResultWithAnUnknownKindIsRejected) {
- // An unrecognized kind means the controller is speaking a dialect this build
- // does not know, so the payload cannot be interpreted: terminal, as an
- // unrecognized opcode is. Rejected where the tag is read, so that
- // decodeResult only ever sees a kind it can interpret.
- TestCA *CA = nullptr;
- Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
- S.attach<TestCA>(BootstrapInfo(S), &CA);
- ASSERT_TRUE(CA);
-
- ExecutorAddr UnknownKind(
- static_cast<uint64_t>(TestCA::ResultKind::LastResultKind) + 1);
- auto A = CA->handleMessage(static_cast<uint64_t>(TestCA::Opcode::Result),
- /*SeqNo=*/1, UnknownKind, WrapperFunctionBuffer());
- ASSERT_FALSE(!!A);
- EXPECT_EQ(toString(A.takeError()),
- "Malformed result message: invalid kind 2");
-
- S.detach([] {});
-}
-
-TEST(SimpleRemoteCATest, DecodeResultOfMalformedOutOfBandErrorIsNotTerminal) {
- // The call waiting on this result has to be completed either way, so a
- // payload that will not decode becomes an out-of-band error about itself
- // rather than ending the session.
- auto R = TestCA::decodeResult(TestCA::ResultKind::OutOfBandError,
- WrapperFunctionBuffer::allocate(4));
- ASSERT_NE(R.getOutOfBandError(), nullptr);
- EXPECT_STREQ(
- R.getOutOfBandError(),
- "Malformed result message: could not deserialize out-of-band error");
-}
-
-TEST(SimpleRemoteCATest, RegisterCallReturnsDistinctNonZeroSequenceNumbers) {
- // Zero is reserved for messages with no result to await, so a registered call
- // must never get it.
- TestCA *CA = nullptr;
- Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
- S.attach<TestCA>(BootstrapInfo(S), &CA);
- ASSERT_TRUE(CA);
-
- uint64_t First = CA->registerCall(borrowHandler(S, *CA));
- uint64_t Second = CA->registerCall(borrowHandler(S, *CA));
- EXPECT_NE(First, 0u);
- EXPECT_NE(Second, 0u);
- EXPECT_NE(First, Second);
-
- S.detach([] {});
-}
-
-TEST(SimpleRemoteCATest, TakeCallYieldsTheHandlerExactlyOnce) {
- TestCA *CA = nullptr;
- Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
- S.attach<TestCA>(BootstrapInfo(S), &CA);
- ASSERT_TRUE(CA);
-
- uint64_t SeqNo = CA->registerCall(borrowHandler(S, *CA));
- auto Taken = CA->takeCall(SeqNo);
- EXPECT_TRUE(!!Taken) << "the registered handler should come back";
-
- // A second take finds nothing: a result for a call that was never made, or
- // answered twice, which the transport reports as terminal.
- EXPECT_FALSE(!!CA->takeCall(SeqNo));
- EXPECT_FALSE(!!CA->takeCall(/*SeqNo=*/9999)) << "never registered";
-
- CA->failPendingControllerCall(std::move(Taken));
- S.detach([] {});
-}
-
-TEST(SimpleRemoteCATest, TakeAllCallsEmptiesTheTable) {
- TestCA *CA = nullptr;
- Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
- S.attach<TestCA>(BootstrapInfo(S), &CA);
- ASSERT_TRUE(CA);
-
- uint64_t First = CA->registerCall(borrowHandler(S, *CA));
- uint64_t Second = CA->registerCall(borrowHandler(S, *CA));
-
- auto All = CA->takeAllCalls();
- EXPECT_EQ(All.size(), 2u);
- EXPECT_EQ(All.count(First), 1u);
- EXPECT_EQ(All.count(Second), 1u);
-
- // Emptied, so a second drain finds nothing and a late result finds no call.
- EXPECT_TRUE(CA->takeAllCalls().empty());
- EXPECT_FALSE(!!CA->takeCall(First));
-
- for (auto &[SeqNo, OnComplete] : All)
- CA->failPendingControllerCall(std::move(OnComplete));
- S.detach([] {});
-}
+//===- SimpleRemoteCATest.cpp ---------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for the transport-independent half of the SimpleRemote protocol.
+//
+// These cover the payload encodings and the pending-call table on their own.
+// When a call may be registered, what ends a session, and who notifies the
+// Session are all the transport's to decide, and are tested with it.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/bedrock/sps/SimpleRemoteCA.h"
+
+#include "gtest/gtest.h"
+
+#include "BedrockTestUtils.h"
+#include "CommonTestUtils.h"
+
+#include "orc-rt/support/sps/SimplePackedSerialization.h"
+
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+using namespace orc_rt;
+
+namespace {
+
+/// Exposes the protected utilities, and captures the handler that
+/// Session::callController hands over so tests have a real one to register.
+class TestCA : public SimpleRemoteCA {
+public:
+ using ControllerAccess::failPendingControllerCall;
+ using ControllerAccess::OnControllerCallReturn;
+ using SimpleRemoteCA::decodeHangup;
+ using SimpleRemoteCA::decodeResult;
+ using SimpleRemoteCA::encodeHangup;
+ using SimpleRemoteCA::encodeResult;
+ using SimpleRemoteCA::encodeSetup;
+ using SimpleRemoteCA::handleMessage;
+ using SimpleRemoteCA::PendingCallsMap;
+ using SimpleRemoteCA::registerCall;
+ using SimpleRemoteCA::takeAllCalls;
+ using SimpleRemoteCA::takeCall;
+
+ using Opcode = SimpleRemoteCA::Opcode;
+ using ResultKind = SimpleRemoteCA::ResultKind;
+
+ TestCA(Session &S, TestCA **Self = nullptr) : SimpleRemoteCA(S) {
+ if (Self)
+ *Self = this;
+ }
+
+ void connect(BootstrapInfo BI) override {}
+
+ void disconnect() override {
+ // What a transport owes on the way out: fail what is pending, then notify.
+ for (auto &[SeqNo, OnComplete] : takeAllCalls())
+ failPendingControllerCall(std::move(OnComplete));
+ notifyDisconnected(Error::success());
+ }
+
+ void callController(OnControllerCallReturn OnComplete,
+ orc_rt_ControllerHandlerTag T,
+ WrapperFunctionBuffer ArgBytes) override {
+ Captured = std::move(OnComplete);
+ }
+
+ void sendWrapperResult(WrapperFunctionBuffer ResultBytes,
+ uint64_t CallId) override {}
+
+ /// Single-threaded here, so no lock: a real transport takes its own.
+ OnControllerCallReturn takePendingCall(uint64_t SeqNo) override {
+ return takeCall(SeqNo);
+ }
+
+ /// A handler taken from the Session, for registering.
+ OnControllerCallReturn Captured;
+};
+
+/// Drives Session::callController once and returns the handler it produced.
+TestCA::OnControllerCallReturn borrowHandler(Session &S, TestCA &CA) {
+ S.callController([](WrapperFunctionBuffer) {}, nullptr,
+ WrapperFunctionBuffer());
+ return std::move(CA.Captured);
+}
+
+} // namespace
+
+TEST(SimpleRemoteCATest, SetupMessageRoundTrips) {
+ // The setup payload's wire format is shared with the controller (it matches
+ // LLVM's SPSSimpleRemoteEPCExecutorInfo), so pin the field order and types by
+ // decoding a payload the encoder produced.
+ using SPSSetup = SPSTuple<SPSString, uint64_t,
+ SPSSequence<SPSTuple<SPSString, SPSSequence<char>>>,
+ SPSSequence<SPSTuple<SPSString, SPSExecutorAddr>>>;
+
+ Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
+
+ int SomeSymbol = 0;
+ SimpleSymbolTable Symbols;
+ std::vector<std::pair<SymbolNameSpec, const void *>> SymbolDefs = {
+ {SymbolNameSpec::linker("foo"), &SomeSymbol}};
+ cantFail(Symbols.addUnique(SymbolDefs));
+
+ BootstrapInfo BI(S, std::move(Symbols),
+ BootstrapInfo::ValueMap{{"key", "value"}});
+ auto Payload = TestCA::encodeSetup(BI);
+
+ std::string Triple;
+ uint64_t PageSize = 0;
+ std::unordered_map<std::string, std::string> Values;
+ std::unordered_map<std::string, ExecutorAddr> DecodedSymbols;
+ SPSInputBuffer IB(Payload.data(), Payload.size());
+ ASSERT_TRUE(SPSSetup::AsArgList::deserialize(IB, Triple, PageSize, Values,
+ DecodedSymbols));
+
+ EXPECT_EQ(Triple, S.processInfo().targetTriple());
+ EXPECT_EQ(PageSize, S.processInfo().pageSize());
+ EXPECT_EQ(Values,
+ (std::unordered_map<std::string, std::string>{{"key", "value"}}));
+ EXPECT_EQ(DecodedSymbols, (std::unordered_map<std::string, ExecutorAddr>{
+ {"foo", ExecutorAddr::fromPtr(&SomeSymbol)}}));
+
+ // The payload holds exactly the setup fields: no padding, and nothing the
+ // controller would be left to interpret.
+ EXPECT_EQ(static_cast<size_t>(IB.data() - Payload.data()), Payload.size());
+
+ S.detach([] {});
+}
+
+TEST(SimpleRemoteCATest, OrderlyHangupRoundTrips) {
+ // Both ends encode and decode hang-ups through these, so a success value must
+ // survive the trip as a success.
+ auto Err = TestCA::decodeHangup(TestCA::encodeHangup(Error::success()));
+ EXPECT_FALSE(!!Err) << "an orderly hang-up is not an error";
+}
+
+TEST(SimpleRemoteCATest, HangupReasonRoundTrips) {
+ auto Err = TestCA::decodeHangup(
+ TestCA::encodeHangup(make_error<StringError>("controller ran out of x")));
+ ASSERT_TRUE(!!Err);
+ EXPECT_EQ(toString(std::move(Err)), "controller ran out of x");
+}
+
+TEST(SimpleRemoteCATest, DecodeHangupRejectsAnEmptyPayload) {
+ // Never valid: the two ends are rev-locked, so this is a bug in the peer
+ // rather than version skew. It comes back as an error like any other reason,
+ // since both outcomes end the session.
+ auto Err = TestCA::decodeHangup(WrapperFunctionBuffer());
+ ASSERT_TRUE(!!Err);
+ EXPECT_EQ(toString(std::move(Err)),
+ "Malformed hang-up message: could not deserialize reason");
+}
+
+TEST(SimpleRemoteCATest, ResultValueRoundTrips) {
+ constexpr std::string_view Content = "result bytes";
+ auto [Kind, Payload] = TestCA::encodeResult(
+ WrapperFunctionBuffer::copyFrom(Content.data(), Content.size()));
+ EXPECT_EQ(Kind, TestCA::ResultKind::Value);
+
+ auto R = TestCA::decodeResult(Kind, std::move(Payload));
+ EXPECT_EQ(R.getOutOfBandError(), nullptr);
+ EXPECT_EQ(std::string_view(R.data(), R.size()), Content);
+}
+
+TEST(SimpleRemoteCATest, EmptyResultRoundTrips) {
+ // What a void-returning wrapper produces. An empty buffer shares 'no size'
+ // with an out-of-band error, so check it is not mistaken for one.
+ auto [Kind, Payload] = TestCA::encodeResult(WrapperFunctionBuffer());
+ EXPECT_EQ(Kind, TestCA::ResultKind::Value);
+
+ auto R = TestCA::decodeResult(Kind, std::move(Payload));
+ EXPECT_TRUE(R.empty());
+}
+
+TEST(SimpleRemoteCATest, OutOfBandErrorResultRoundTrips) {
+ // An out-of-band error is a pointer to a message rather than a serialized
+ // value, so it cannot travel as an ordinary payload. It goes out under its
+ // own result kind, and must arrive as an out-of-band error again -- otherwise
+ // the caller is told its call succeeded with no result.
+ constexpr const char *Msg = "Could not deserialize wrapper function arg data";
+ auto [Kind, Payload] =
+ TestCA::encodeResult(WrapperFunctionBuffer::createOutOfBandError(Msg));
+ EXPECT_EQ(Kind, TestCA::ResultKind::OutOfBandError);
+
+ auto R = TestCA::decodeResult(Kind, std::move(Payload));
+ ASSERT_NE(R.getOutOfBandError(), nullptr);
+ EXPECT_STREQ(R.getOutOfBandError(), Msg);
+}
+
+TEST(SimpleRemoteCATest, ResultWithAnUnknownKindIsRejected) {
+ // An unrecognized kind means the controller is speaking a dialect this build
+ // does not know, so the payload cannot be interpreted: terminal, as an
+ // unrecognized opcode is. Rejected where the tag is read, so that
+ // decodeResult only ever sees a kind it can interpret.
+ TestCA *CA = nullptr;
+ Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
+ S.attach<TestCA>(BootstrapInfo(S), &CA);
+ ASSERT_TRUE(CA);
+
+ ExecutorAddr UnknownKind(
+ static_cast<uint64_t>(TestCA::ResultKind::LastResultKind) + 1);
+ auto A = CA->handleMessage(static_cast<uint64_t>(TestCA::Opcode::Result),
+ /*SeqNo=*/1, UnknownKind, WrapperFunctionBuffer());
+ ASSERT_FALSE(!!A);
+ EXPECT_EQ(toString(A.takeError()),
+ "Malformed result message: invalid kind 2");
+
+ S.detach([] {});
+}
+
+TEST(SimpleRemoteCATest, DecodeResultOfMalformedOutOfBandErrorIsNotTerminal) {
+ // The call waiting on this result has to be completed either way, so a
+ // payload that will not decode becomes an out-of-band error about itself
+ // rather than ending the session.
+ auto R = TestCA::decodeResult(TestCA::ResultKind::OutOfBandError,
+ WrapperFunctionBuffer::allocate(4));
+ ASSERT_NE(R.getOutOfBandError(), nullptr);
+ EXPECT_STREQ(
+ R.getOutOfBandError(),
+ "Malformed result message: could not deserialize out-of-band error");
+}
+
+TEST(SimpleRemoteCATest, RegisterCallReturnsDistinctNonZeroSequenceNumbers) {
+ // Zero is reserved for messages with no result to await, so a registered call
+ // must never get it.
+ TestCA *CA = nullptr;
+ Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
+ S.attach<TestCA>(BootstrapInfo(S), &CA);
+ ASSERT_TRUE(CA);
+
+ uint64_t First = CA->registerCall(borrowHandler(S, *CA));
+ uint64_t Second = CA->registerCall(borrowHandler(S, *CA));
+ EXPECT_NE(First, 0u);
+ EXPECT_NE(Second, 0u);
+ EXPECT_NE(First, Second);
+
+ S.detach([] {});
+}
+
+TEST(SimpleRemoteCATest, TakeCallYieldsTheHandlerExactlyOnce) {
+ TestCA *CA = nullptr;
+ Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
+ S.attach<TestCA>(BootstrapInfo(S), &CA);
+ ASSERT_TRUE(CA);
+
+ uint64_t SeqNo = CA->registerCall(borrowHandler(S, *CA));
+ auto Taken = CA->takeCall(SeqNo);
+ EXPECT_TRUE(!!Taken) << "the registered handler should come back";
+
+ // A second take finds nothing: a result for a call that was never made, or
+ // answered twice, which the transport reports as terminal.
+ EXPECT_FALSE(!!CA->takeCall(SeqNo));
+ EXPECT_FALSE(!!CA->takeCall(/*SeqNo=*/9999)) << "never registered";
+
+ CA->failPendingControllerCall(std::move(Taken));
+ S.detach([] {});
+}
+
+TEST(SimpleRemoteCATest, TakeAllCallsEmptiesTheTable) {
+ TestCA *CA = nullptr;
+ Session S(mockExecutorProcessInfo(), inlineDispatch, noErrors);
+ S.attach<TestCA>(BootstrapInfo(S), &CA);
+ ASSERT_TRUE(CA);
+
+ uint64_t First = CA->registerCall(borrowHandler(S, *CA));
+ uint64_t Second = CA->registerCall(borrowHandler(S, *CA));
+
+ auto All = CA->takeAllCalls();
+ EXPECT_EQ(All.size(), 2u);
+ EXPECT_EQ(All.count(First), 1u);
+ EXPECT_EQ(All.count(Second), 1u);
+
+ // Emptied, so a second drain finds nothing and a late result finds no call.
+ EXPECT_TRUE(CA->takeAllCalls().empty());
+ EXPECT_FALSE(!!CA->takeCall(First));
+
+ for (auto &[SeqNo, OnComplete] : All)
+ CA->failPendingControllerCall(std::move(OnComplete));
+ S.detach([] {});
+}
diff --git a/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp b/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp
index 1a03de3870edf..647518dfb0a44 100644
--- a/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp
+++ b/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp
@@ -1,58 +1,58 @@
-//===- TargetTripleTest.cpp -----------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for orc-rt's bedrock/sys/TargetTriple.h APIs.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt-internal/bedrock/sys/TargetTriple.h"
-#include "gtest/gtest.h"
-
-#include <algorithm>
-
-using namespace orc_rt;
-
-TEST(TargetTripleTest, NotEmpty) {
- EXPECT_FALSE(sys::detectTargetTriple().empty());
-}
-
-TEST(TargetTripleTest, HasValidStructure) {
- auto Triple = sys::detectTargetTriple();
- // A valid triple has 2 hyphens (arch-vendor-os) or 3 (arch-vendor-os-env).
- auto NumHyphens = std::count(Triple.begin(), Triple.end(), '-');
- EXPECT_GE(NumHyphens, 2);
- EXPECT_LE(NumHyphens, 3);
-}
-
-TEST(TargetTripleTest, ArchMatchesCompileTarget) {
- auto Triple = sys::detectTargetTriple();
-#if defined(__arm64e__)
- EXPECT_EQ(Triple.substr(0, 7), "arm64e-");
-#elif defined(__APPLE__) && (defined(__arm64__) || defined(__aarch64__))
- EXPECT_EQ(Triple.substr(0, 6), "arm64-");
-#elif defined(__aarch64__) || defined(_M_ARM64)
- EXPECT_EQ(Triple.substr(0, 8), "aarch64-");
-#elif defined(__x86_64h__)
- EXPECT_EQ(Triple.substr(0, 8), "x86_64h-");
-#elif defined(__x86_64__) || defined(_M_X64)
- EXPECT_EQ(Triple.substr(0, 7), "x86_64-");
-#endif
-}
-
-TEST(TargetTripleTest, OSMatchesCompileTarget) {
- auto Triple = sys::detectTargetTriple();
-#if defined(__APPLE__)
- EXPECT_NE(Triple.find("-apple-"), std::string::npos);
-#elif defined(__linux__)
- EXPECT_NE(Triple.find("-linux-"), std::string::npos);
-#endif
-}
-
-TEST(TargetTripleTest, CachedResultIsIdempotent) {
- EXPECT_EQ(sys::detectTargetTriple(), sys::detectTargetTriple());
-}
+//===- TargetTripleTest.cpp -----------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for orc-rt's bedrock/sys/TargetTriple.h APIs.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt-internal/bedrock/sys/TargetTriple.h"
+#include "gtest/gtest.h"
+
+#include <algorithm>
+
+using namespace orc_rt;
+#ifndef _WIN32
+TEST(TargetTripleTest, NotEmpty) {
+ EXPECT_FALSE(sys::detectTargetTriple().empty());
+}
+
+TEST(TargetTripleTest, HasValidStructure) {
+ auto Triple = sys::detectTargetTriple();
+ // A valid triple has 2 hyphens (arch-vendor-os) or 3 (arch-vendor-os-env).
+ auto NumHyphens = std::count(Triple.begin(), Triple.end(), '-');
+ EXPECT_GE(NumHyphens, 2);
+ EXPECT_LE(NumHyphens, 3);
+}
+
+TEST(TargetTripleTest, ArchMatchesCompileTarget) {
+ auto Triple = sys::detectTargetTriple();
+#if defined(__arm64e__)
+ EXPECT_EQ(Triple.substr(0, 7), "arm64e-");
+#elif defined(__APPLE__) && (defined(__arm64__) || defined(__aarch64__))
+ EXPECT_EQ(Triple.substr(0, 6), "arm64-");
+#elif defined(__aarch64__) || defined(_M_ARM64)
+ EXPECT_EQ(Triple.substr(0, 8), "aarch64-");
+#elif defined(__x86_64h__)
+ EXPECT_EQ(Triple.substr(0, 8), "x86_64h-");
+#elif defined(__x86_64__) || defined(_M_X64)
+ EXPECT_EQ(Triple.substr(0, 7), "x86_64-");
+#endif
+}
+
+TEST(TargetTripleTest, OSMatchesCompileTarget) {
+ auto Triple = sys::detectTargetTriple();
+#if defined(__APPLE__)
+ EXPECT_NE(Triple.find("-apple-"), std::string::npos);
+#elif defined(__linux__)
+ EXPECT_NE(Triple.find("-linux-"), std::string::npos);
+#endif
+}
+#endif
+TEST(TargetTripleTest, CachedResultIsIdempotent) {
+ EXPECT_EQ(sys::detectTargetTriple(), sys::detectTargetTriple());
+}
diff --git a/orc-rt/test/unit/support/BitmaskEnumTest.cpp b/orc-rt/test/unit/support/BitmaskEnumTest.cpp
index 54fd14f9345eb..f6b44508ec7e4 100644
--- a/orc-rt/test/unit/support/BitmaskEnumTest.cpp
+++ b/orc-rt/test/unit/support/BitmaskEnumTest.cpp
@@ -1,158 +1,158 @@
-//===- BitmaskEnumTest.cpp ------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Test bitmask-enum support APIs.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/support/BitmaskEnum.h"
-#include "gtest/gtest.h"
-
-#include <string>
-
-using namespace orc_rt;
-
-namespace {
-
-enum Flags : unsigned { F0 = 0, F1 = 1, F2 = 2, F3 = 4, F4 = 8 };
-
-} // namespace
-
-namespace orc_rt {
-ORC_RT_DECLARE_ENUM_AS_BITMASK(Flags, F4);
-} // namespace orc_rt
-
-static_assert(is_bitmask_enum<Flags>::value != 0);
-static_assert(largest_bitmask_enum_bit<Flags>::value == Flags::F4);
-
-namespace {
-
-static_assert(is_bitmask_enum<Flags>::value != 0);
-static_assert(largest_bitmask_enum_bit<Flags>::value == Flags::F4);
-
-TEST(BitmaskEnumTest, BitwiseOr) {
- Flags f = F1 | F2;
- EXPECT_EQ(3, f);
-
- f = f | F3;
- EXPECT_EQ(7, f);
-}
-
-TEST(BitmaskEnumTest, BitwiseOrEquals) {
- Flags f = F1;
- f |= F3;
- EXPECT_EQ(5, f);
-
- // |= should return a reference to the LHS.
- f = F2;
- (f |= F3) = F1;
- EXPECT_EQ(F1, f);
-}
-
-TEST(BitmaskEnumTest, BitwiseAnd) {
- Flags f = static_cast<Flags>(3) & F2;
- EXPECT_EQ(F2, f);
-
- f = (f | F3) & (F1 | F2 | F3);
- EXPECT_EQ(6, f);
-}
-
-TEST(BitmaskEnumTest, BitwiseAndEquals) {
- Flags f = F1 | F2 | F3;
- f &= F1 | F2;
- EXPECT_EQ(3, f);
-
- // &= should return a reference to the LHS.
- (f &= F1) = F3;
- EXPECT_EQ(F3, f);
-}
-
-TEST(BitmaskEnumTest, BitwiseXor) {
- Flags f = (F1 | F2) ^ (F2 | F3);
- EXPECT_EQ(5, f);
-
- f = f ^ F1;
- EXPECT_EQ(4, f);
-}
-
-TEST(BitmaskEnumTest, BitwiseXorEquals) {
- Flags f = (F1 | F2);
- f ^= (F2 | F4);
- EXPECT_EQ(9, f);
-
- // ^= should return a reference to the LHS.
- (f ^= F4) = F3;
- EXPECT_EQ(F3, f);
-}
-
-TEST(BitmaskEnumTest, ConstantExpression) {
- constexpr Flags f1 = ~F1;
- constexpr Flags f2 = F1 | F2;
- constexpr Flags f3 = F1 & F2;
- constexpr Flags f4 = F1 ^ F2;
- EXPECT_EQ(f1, ~F1);
- EXPECT_EQ(f2, F1 | F2);
- EXPECT_EQ(f3, F1 & F2);
- EXPECT_EQ(f4, F1 ^ F2);
-}
-
-TEST(BitmaskEnumTest, BitwiseNot) {
- Flags f = ~F1;
- EXPECT_EQ(14, f); // Largest value for f is 15.
- EXPECT_EQ(15, ~F0);
-}
-
-enum class FlagsClass : unsigned {
- F0 = 0,
- F1 = 1,
- F2 = 2,
- F3 = 4,
- ORC_RT_MARK_AS_BITMASK_ENUM(F3)
-};
-
-TEST(BitmaskEnumTest, ScopedEnum) {
- FlagsClass f = (FlagsClass::F1 & ~FlagsClass::F0) | FlagsClass::F2;
- f |= FlagsClass::F3;
- EXPECT_EQ(7, static_cast<int>(f));
-}
-
-struct Container {
- enum Flags : unsigned {
- F0 = 0,
- F1 = 1,
- F2 = 2,
- F3 = 4,
- ORC_RT_MARK_AS_BITMASK_ENUM(F3)
- };
-
- static Flags getFlags() {
- Flags f = F0 | F1;
- f |= F2;
- return f;
- }
-};
-
-TEST(BitmaskEnumTest, EnumInStruct) { EXPECT_EQ(3, Container::getFlags()); }
-
-// A largest bit in the top position of the underlying type: the mask is every
-// bit, and computing it must not shift by the full width of the type.
-enum class TopBitFlags : uint32_t {
- Low = 1,
- High = 0x80000000,
- ORC_RT_MARK_AS_BITMASK_ENUM(High)
-};
-
-TEST(BitmaskEnumTest, LargestBitInTopPosition) {
- EXPECT_EQ(0xffffffffU, bitmask_enum_mask<TopBitFlags>());
- EXPECT_EQ(32, bitmask_enum_num_bits_v<TopBitFlags>);
- EXPECT_EQ(0x80000001U,
- static_cast<uint32_t>(TopBitFlags::Low | TopBitFlags::High));
- EXPECT_EQ(0xfffffffeU, static_cast<uint32_t>(~TopBitFlags::Low));
-}
-
-} // namespace
+//===- BitmaskEnumTest.cpp ------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Test bitmask-enum support APIs.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/support/BitmaskEnum.h"
+#include "gtest/gtest.h"
+
+#include <string>
+
+using namespace orc_rt;
+
+namespace {
+
+enum Flags : unsigned { F0 = 0, F1 = 1, F2 = 2, F3 = 4, F4 = 8 };
+
+} // namespace
+
+namespace orc_rt {
+ORC_RT_DECLARE_ENUM_AS_BITMASK(Flags, F4);
+} // namespace orc_rt
+
+static_assert(is_bitmask_enum<Flags>::value != 0);
+static_assert(largest_bitmask_enum_bit<Flags>::value == Flags::F4);
+
+namespace {
+
+static_assert(is_bitmask_enum<Flags>::value != 0);
+static_assert(largest_bitmask_enum_bit<Flags>::value == Flags::F4);
+
+TEST(BitmaskEnumTest, BitwiseOr) {
+ Flags f = F1 | F2;
+ EXPECT_EQ(3, f);
+
+ f = f | F3;
+ EXPECT_EQ(7, f);
+}
+
+TEST(BitmaskEnumTest, BitwiseOrEquals) {
+ Flags f = F1;
+ f |= F3;
+ EXPECT_EQ(5, f);
+
+ // |= should return a reference to the LHS.
+ f = F2;
+ (f |= F3) = F1;
+ EXPECT_EQ(F1, f);
+}
+
+TEST(BitmaskEnumTest, BitwiseAnd) {
+ Flags f = static_cast<Flags>(3) & F2;
+ EXPECT_EQ(F2, f);
+
+ f = (f | F3) & (F1 | F2 | F3);
+ EXPECT_EQ(6, f);
+}
+
+TEST(BitmaskEnumTest, BitwiseAndEquals) {
+ Flags f = F1 | F2 | F3;
+ f &= F1 | F2;
+ EXPECT_EQ(3, f);
+
+ // &= should return a reference to the LHS.
+ (f &= F1) = F3;
+ EXPECT_EQ(F3, f);
+}
+
+TEST(BitmaskEnumTest, BitwiseXor) {
+ Flags f = (F1 | F2) ^ (F2 | F3);
+ EXPECT_EQ(5, f);
+
+ f = f ^ F1;
+ EXPECT_EQ(4, f);
+}
+
+TEST(BitmaskEnumTest, BitwiseXorEquals) {
+ Flags f = (F1 | F2);
+ f ^= (F2 | F4);
+ EXPECT_EQ(9, f);
+
+ // ^= should return a reference to the LHS.
+ (f ^= F4) = F3;
+ EXPECT_EQ(F3, f);
+}
+
+TEST(BitmaskEnumTest, ConstantExpression) {
+ constexpr Flags f1 = ~F1;
+ constexpr Flags f2 = F1 | F2;
+ constexpr Flags f3 = F1 & F2;
+ constexpr Flags f4 = F1 ^ F2;
+ EXPECT_EQ(f1, ~F1);
+ EXPECT_EQ(f2, F1 | F2);
+ EXPECT_EQ(f3, F1 & F2);
+ EXPECT_EQ(f4, F1 ^ F2);
+}
+
+TEST(BitmaskEnumTest, BitwiseNot) {
+ Flags f = ~F1;
+ EXPECT_EQ(14, f); // Largest value for f is 15.
+ EXPECT_EQ(15, ~F0);
+}
+
+enum class FlagsClass : unsigned {
+ F0 = 0,
+ F1 = 1,
+ F2 = 2,
+ F3 = 4,
+ ORC_RT_MARK_AS_BITMASK_ENUM(F3)
+};
+
+TEST(BitmaskEnumTest, ScopedEnum) {
+ FlagsClass f = (FlagsClass::F1 & ~FlagsClass::F0) | FlagsClass::F2;
+ f |= FlagsClass::F3;
+ EXPECT_EQ(7, static_cast<int>(f));
+}
+
+struct Container {
+ enum Flags : unsigned {
+ F0 = 0,
+ F1 = 1,
+ F2 = 2,
+ F3 = 4,
+ ORC_RT_MARK_AS_BITMASK_ENUM(F3)
+ };
+
+ static Flags getFlags() {
+ Flags f = F0 | F1;
+ f |= F2;
+ return f;
+ }
+};
+
+TEST(BitmaskEnumTest, EnumInStruct) { EXPECT_EQ(3, Container::getFlags()); }
+
+// A largest bit in the top position of the underlying type: the mask is every
+// bit, and computing it must not shift by the full width of the type.
+enum class TopBitFlags : uint32_t {
+ Low = 1,
+ High = 0x80000000,
+ ORC_RT_MARK_AS_BITMASK_ENUM(High)
+};
+
+TEST(BitmaskEnumTest, LargestBitInTopPosition) {
+ EXPECT_EQ(0xffffffffU, bitmask_enum_mask<TopBitFlags>());
+ EXPECT_EQ(32, bitmask_enum_num_bits_v<TopBitFlags>);
+ EXPECT_EQ(0x80000001U,
+ static_cast<uint32_t>(TopBitFlags::Low | TopBitFlags::High));
+ EXPECT_EQ(0xfffffffeU, static_cast<uint32_t>(~TopBitFlags::Low));
+}
+
+} // namespace
diff --git a/orc-rt/test/unit/support/CallableTraitsHelperTest.cpp b/orc-rt/test/unit/support/CallableTraitsHelperTest.cpp
index e04f10328b1c3..50e0e0d5c4dc3 100644
--- a/orc-rt/test/unit/support/CallableTraitsHelperTest.cpp
+++ b/orc-rt/test/unit/support/CallableTraitsHelperTest.cpp
@@ -1,206 +1,204 @@
-//===- CallableTraitsHelperTest.cpp ---------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for orc-rt's CallableTraitsHelper.h APIs.
-//
-// NOTE: All tests in this file are testing compile-time functionality, so the
-// tests at runtime all end up being noops. That's fine -- those are
-// cheap.
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/support/CallableTraitsHelper.h"
-#include "gtest/gtest.h"
-
-using namespace orc_rt;
-
-static void freeVoidVoid() {}
-
-TEST(CallableTraitsHelperTest, FreeVoidVoid) {
- (void)freeVoidVoid;
- typedef CallableArgInfo<decltype(freeVoidVoid)> CAI;
- static_assert(std::is_void_v<CAI::return_type>);
- static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<>>);
-}
-
-static int freeBinaryOp(int, float) { return 0; }
-
-TEST(CallableTraitsHelperTest, FreeBinaryOp) {
- (void)freeBinaryOp;
- typedef CallableArgInfo<decltype(freeBinaryOp)> CAI;
- static_assert(std::is_same_v<CAI::return_type, int>);
- static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int, float>>);
-}
-
-TEST(CallableTraitsHelperTest, VoidVoidObj) {
- auto VoidVoid = []() {};
- typedef CallableArgInfo<decltype(VoidVoid)> CAI;
- static_assert(std::is_void_v<CAI::return_type>);
- static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<>>);
-}
-
-TEST(CallableTraitsHelperTest, BinaryOpObj) {
- auto BinaryOp = [](int X, float Y) -> int { return X + Y; };
- typedef CallableArgInfo<decltype(BinaryOp)> CAI;
- static_assert(std::is_same_v<CAI::return_type, int>);
- static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int, float>>);
-}
-
-TEST(CallableTraitsHelperTest, PreservesLValueRef) {
- auto RefOp = [](int &) {};
- typedef CallableArgInfo<decltype(RefOp)> CAI;
- static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int &>>);
-}
-
-TEST(CallableTraitsHelperTest, PreservesLValueRefConstness) {
- auto RefOp = [](const int &) {};
- typedef CallableArgInfo<decltype(RefOp)> CAI;
- static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<const int &>>);
-}
-
-TEST(CallableTraitsHelperTest, PreservesRValueRef) {
- auto RefOp = [](int &&) {};
- typedef CallableArgInfo<decltype(RefOp)> CAI;
- static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int &&>>);
-}
-
-// Free functions cannot be const-qualified.
-TEST(CallableTraitsHelperTest, FreeFunctionIsNonConst) {
- static_assert(!CallableArgInfo<decltype(freeVoidVoid)>::is_const);
- static_assert(!CallableArgInfo<decltype(freeBinaryOp)>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, FunctionPointerIsNonConst) {
- static_assert(!CallableArgInfo<int (*)(int, float)>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, FunctionReferenceIsNonConst) {
- static_assert(!CallableArgInfo<int (&)(int, float)>::is_const);
-}
-
-// A non-mutable lambda's call operator is const-qualified.
-TEST(CallableTraitsHelperTest, NonMutableLambdaIsConst) {
- auto L = []() {};
- static_assert(CallableArgInfo<decltype(L)>::is_const);
-}
-
-// A mutable lambda's call operator is not const-qualified.
-TEST(CallableTraitsHelperTest, MutableLambdaIsNonConst) {
- auto L = []() mutable {};
- static_assert(!CallableArgInfo<decltype(L)>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, ConstFunctorIsConst) {
- struct F {
- void operator()() const {}
- };
- static_assert(CallableArgInfo<F>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, NonConstFunctorIsNonConst) {
- struct F {
- void operator()() {}
- };
- static_assert(!CallableArgInfo<F>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, NonConstMemberFnPtrIsNonConst) {
- struct C {
- void m(int) {}
- };
- static_assert(!CallableArgInfo<decltype(&C::m)>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, ConstMemberFnPtrIsConst) {
- struct C {
- void m(int) const {}
- };
- static_assert(CallableArgInfo<decltype(&C::m)>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, FunctionTypeIsNonConst) {
- static_assert(!CallableArgInfo<int(int, float)>::is_const);
-}
-
-// Abominable function type: const cv-qualifier on the function type itself.
-TEST(CallableTraitsHelperTest, AbominableFunctionTypeIsConst) {
- static_assert(CallableArgInfo<int(int, float) const>::is_const);
-}
-
-// noexcept coverage — mirrors the const-qualifier tests above.
-
-static void freeVoidVoidNoexcept() noexcept {}
-
-TEST(CallableTraitsHelperTest, FreeFunctionNoexcept) {
- (void)freeVoidVoidNoexcept;
- static_assert(!CallableArgInfo<decltype(freeVoidVoid)>::is_noexcept);
- static_assert(CallableArgInfo<decltype(freeVoidVoidNoexcept)>::is_noexcept);
-}
-
-TEST(CallableTraitsHelperTest, FunctionPointerNoexcept) {
- static_assert(!CallableArgInfo<int (*)(int, float)>::is_noexcept);
- static_assert(CallableArgInfo<int (*)(int, float) noexcept>::is_noexcept);
-}
-
-TEST(CallableTraitsHelperTest, FunctionReferenceNoexcept) {
- static_assert(!CallableArgInfo<int (&)(int, float)>::is_noexcept);
- static_assert(CallableArgInfo<int (&)(int, float) noexcept>::is_noexcept);
-}
-
-TEST(CallableTraitsHelperTest, NonNoexceptLambdaIsNotNoexcept) {
- auto L = []() {};
- static_assert(!CallableArgInfo<decltype(L)>::is_noexcept);
-}
-
-TEST(CallableTraitsHelperTest, NoexceptLambdaIsNoexcept) {
- auto L = []() noexcept {};
- static_assert(CallableArgInfo<decltype(L)>::is_noexcept);
-}
-
-TEST(CallableTraitsHelperTest, NoexceptFunctor) {
- struct F {
- void operator()() const noexcept {}
- };
- static_assert(CallableArgInfo<F>::is_noexcept);
- static_assert(CallableArgInfo<F>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, NonNoexceptFunctor) {
- struct F {
- void operator()() const {}
- };
- static_assert(!CallableArgInfo<F>::is_noexcept);
-}
-
-TEST(CallableTraitsHelperTest, NoexceptMemberFnPtr) {
- struct C {
- void m(int) noexcept {}
- void mConstNoexcept(int) const noexcept {}
- void mConst(int) const {}
- void mPlain(int) {}
- };
- static_assert(CallableArgInfo<decltype(&C::m)>::is_noexcept);
- static_assert(!CallableArgInfo<decltype(&C::m)>::is_const);
- static_assert(CallableArgInfo<decltype(&C::mConstNoexcept)>::is_noexcept);
- static_assert(CallableArgInfo<decltype(&C::mConstNoexcept)>::is_const);
- static_assert(!CallableArgInfo<decltype(&C::mConst)>::is_noexcept);
- static_assert(CallableArgInfo<decltype(&C::mConst)>::is_const);
- static_assert(!CallableArgInfo<decltype(&C::mPlain)>::is_noexcept);
- static_assert(!CallableArgInfo<decltype(&C::mPlain)>::is_const);
-}
-
-TEST(CallableTraitsHelperTest, FunctionTypeNoexcept) {
- static_assert(!CallableArgInfo<int(int, float)>::is_noexcept);
- static_assert(CallableArgInfo<int(int, float) noexcept>::is_noexcept);
-}
-
-// Abominable function type with both const and noexcept cv-qualifiers.
-TEST(CallableTraitsHelperTest, AbominableFunctionTypeConstNoexcept) {
- using F = int(int, float) const noexcept;
- static_assert(CallableArgInfo<F>::is_const);
- static_assert(CallableArgInfo<F>::is_noexcept);
-}
+//===- CallableTraitsHelperTest.cpp ---------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for orc-rt's CallableTraitsHelper.h APIs.
+//
+// NOTE: All tests in this file are testing compile-time functionality, so the
+// tests at runtime all end up being noops. That's fine -- those are
+// cheap.
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/support/CallableTraitsHelper.h"
+#include "gtest/gtest.h"
+
+using namespace orc_rt;
+
+static void freeVoidVoid() {}
+
+TEST(CallableTraitsHelperTest, FreeVoidVoid) {
+ using CAI = CallableArgInfo<decltype(freeVoidVoid)>;
+ static_assert(std::is_void_v<CAI::return_type>);
+ static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<>>);
+}
+
+static int freeBinaryOp(int, float) { return 0; }
+
+TEST(CallableTraitsHelperTest, FreeBinaryOp) {
+ using CAI = CallableArgInfo<decltype(freeBinaryOp)>;
+ static_assert(std::is_same_v<CAI::return_type, int>);
+ static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int, float>>);
+}
+
+TEST(CallableTraitsHelperTest, VoidVoidObj) {
+ auto VoidVoid = []() {};
+ using CAI = CallableArgInfo<decltype(VoidVoid)>;
+ static_assert(std::is_void_v<CAI::return_type>);
+ static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<>>);
+}
+
+TEST(CallableTraitsHelperTest, BinaryOpObj) {
+ auto BinaryOp = [](int X, float Y) -> int { return X + Y; };
+ using CAI = CallableArgInfo<decltype(BinaryOp)>;
+ static_assert(std::is_same_v<CAI::return_type, int>);
+ static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int, float>>);
+}
+
+TEST(CallableTraitsHelperTest, PreservesLValueRef) {
+ auto RefOp = [](int &) {};
+ using CAI = CallableArgInfo<decltype(RefOp)>;
+ static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int &>>);
+}
+
+TEST(CallableTraitsHelperTest, PreservesLValueRefConstness) {
+ auto RefOp = [](const int &) {};
+ using CAI = CallableArgInfo<decltype(RefOp)>;
+ static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<const int &>>);
+}
+
+TEST(CallableTraitsHelperTest, PreservesRValueRef) {
+ auto RefOp = [](int &&) {};
+ using CAI = CallableArgInfo<decltype(RefOp)>;
+ static_assert(std::is_same_v<CAI::args_tuple_type, std::tuple<int &&>>);
+}
+
+// Free functions cannot be const-qualified.
+TEST(CallableTraitsHelperTest, FreeFunctionIsNonConst) {
+ static_assert(!CallableArgInfo<decltype(freeVoidVoid)>::is_const);
+ static_assert(!CallableArgInfo<decltype(freeBinaryOp)>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, FunctionPointerIsNonConst) {
+ static_assert(!CallableArgInfo<int (*)(int, float)>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, FunctionReferenceIsNonConst) {
+ static_assert(!CallableArgInfo<int (&)(int, float)>::is_const);
+}
+
+// A non-mutable lambda's call operator is const-qualified.
+TEST(CallableTraitsHelperTest, NonMutableLambdaIsConst) {
+ auto L = []() {};
+ static_assert(CallableArgInfo<decltype(L)>::is_const);
+}
+
+// A mutable lambda's call operator is not const-qualified.
+TEST(CallableTraitsHelperTest, MutableLambdaIsNonConst) {
+ auto L = []() mutable {};
+ static_assert(!CallableArgInfo<decltype(L)>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, ConstFunctorIsConst) {
+ struct F {
+ void operator()() const {}
+ };
+ static_assert(CallableArgInfo<F>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, NonConstFunctorIsNonConst) {
+ struct F {
+ void operator()() {}
+ };
+ static_assert(!CallableArgInfo<F>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, NonConstMemberFnPtrIsNonConst) {
+ struct C {
+ void m(int) {}
+ };
+ static_assert(!CallableArgInfo<decltype(&C::m)>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, ConstMemberFnPtrIsConst) {
+ struct C {
+ void m(int) const {}
+ };
+ static_assert(CallableArgInfo<decltype(&C::m)>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, FunctionTypeIsNonConst) {
+ static_assert(!CallableArgInfo<int(int, float)>::is_const);
+}
+
+// Abominable function type: const cv-qualifier on the function type itself.
+TEST(CallableTraitsHelperTest, AbominableFunctionTypeIsConst) {
+ static_assert(CallableArgInfo<int(int, float) const>::is_const);
+}
+
+// noexcept coverage — mirrors the const-qualifier tests above.
+
+static void freeVoidVoidNoexcept() noexcept {}
+
+TEST(CallableTraitsHelperTest, FreeFunctionNoexcept) {
+ (void)freeVoidVoidNoexcept();
+ static_assert(!CallableArgInfo<decltype(freeVoidVoid)>::is_noexcept);
+ static_assert(CallableArgInfo<decltype(freeVoidVoidNoexcept)>::is_noexcept);
+}
+
+TEST(CallableTraitsHelperTest, FunctionPointerNoexcept) {
+ static_assert(!CallableArgInfo<int (*)(int, float)>::is_noexcept);
+ static_assert(CallableArgInfo<int (*)(int, float) noexcept>::is_noexcept);
+}
+
+TEST(CallableTraitsHelperTest, FunctionReferenceNoexcept) {
+ static_assert(!CallableArgInfo<int (&)(int, float)>::is_noexcept);
+ static_assert(CallableArgInfo<int (&)(int, float) noexcept>::is_noexcept);
+}
+
+TEST(CallableTraitsHelperTest, NonNoexceptLambdaIsNotNoexcept) {
+ auto L = []() {};
+ static_assert(!CallableArgInfo<decltype(L)>::is_noexcept);
+}
+
+TEST(CallableTraitsHelperTest, NoexceptLambdaIsNoexcept) {
+ auto L = []() noexcept {};
+ static_assert(CallableArgInfo<decltype(L)>::is_noexcept);
+}
+
+TEST(CallableTraitsHelperTest, NoexceptFunctor) {
+ struct F {
+ void operator()() const noexcept {}
+ };
+ static_assert(CallableArgInfo<F>::is_noexcept);
+ static_assert(CallableArgInfo<F>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, NonNoexceptFunctor) {
+ struct F {
+ void operator()() const {}
+ };
+ static_assert(!CallableArgInfo<F>::is_noexcept);
+}
+
+TEST(CallableTraitsHelperTest, NoexceptMemberFnPtr) {
+ struct C {
+ void m(int) noexcept {}
+ void mConstNoexcept(int) const noexcept {}
+ void mConst(int) const {}
+ void mPlain(int) {}
+ };
+ static_assert(CallableArgInfo<decltype(&C::m)>::is_noexcept);
+ static_assert(!CallableArgInfo<decltype(&C::m)>::is_const);
+ static_assert(CallableArgInfo<decltype(&C::mConstNoexcept)>::is_noexcept);
+ static_assert(CallableArgInfo<decltype(&C::mConstNoexcept)>::is_const);
+ static_assert(!CallableArgInfo<decltype(&C::mConst)>::is_noexcept);
+ static_assert(CallableArgInfo<decltype(&C::mConst)>::is_const);
+ static_assert(!CallableArgInfo<decltype(&C::mPlain)>::is_noexcept);
+ static_assert(!CallableArgInfo<decltype(&C::mPlain)>::is_const);
+}
+
+TEST(CallableTraitsHelperTest, FunctionTypeNoexcept) {
+ static_assert(!CallableArgInfo<int(int, float)>::is_noexcept);
+ static_assert(CallableArgInfo<int(int, float) noexcept>::is_noexcept);
+}
+
+// Abominable function type with both const and noexcept cv-qualifiers.
+TEST(CallableTraitsHelperTest, AbominableFunctionTypeConstNoexcept) {
+ using F = int(int, float) const noexcept;
+ static_assert(CallableArgInfo<F>::is_const);
+ static_assert(CallableArgInfo<F>::is_noexcept);
+}
diff --git a/orc-rt/test/unit/support/bit-test.cpp b/orc-rt/test/unit/support/bit-test.cpp
index f2ca32b89edc9..b9fca5b26a107 100644
--- a/orc-rt/test/unit/support/bit-test.cpp
+++ b/orc-rt/test/unit/support/bit-test.cpp
@@ -1,235 +1,240 @@
-//===- bit-test.cpp -------------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for orc-rt's bit.h APIs.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt/support/bit.h"
-#include "gtest/gtest.h"
-
-#include <cstdint>
-
-#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
-#define IS_BIG_ENDIAN
-#elif defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && \
- BYTE_ORDER == LITTLE_ENDIAN
-#define IS_LITTLE_ENDIAN
-#endif
-
-using namespace orc_rt;
-
-TEST(BitTest, endian) {
-#if defined(IS_BIG_ENDIAN)
- EXPECT_EQ(endian::native, endian::big);
-#elif defined(IS_LITTLE_ENDIAN)
- EXPECT_EQ(endian::native, endian::little);
-#else
- ADD_FAILURE() << "BYTE_ORDER is neither BIG_ENDIAN nor LITTLE_ENDIAN.";
-#endif
-}
-
-TEST(BitTest, byte_swap_32) {
- unsigned char Seq[] = {0x01, 0x23, 0x45, 0x67};
- uint32_t X = 0;
- memcpy(&X, Seq, sizeof(X));
- auto Y = byteswap(X);
-
- static_assert(sizeof(Seq) == sizeof(X),
- "sizeof(char[4]) != sizeof(uint32_t) ?");
- static_assert(std::is_same_v<decltype(X), decltype(Y)>,
- "byte_swap return type doesn't match input");
-
-#if defined(IS_BIG_ENDIAN)
- EXPECT_EQ(X, uint32_t(0x01234567));
- EXPECT_EQ(Y, uint32_t(0x67452301));
-#elif defined(IS_LITTLE_ENDIAN)
- EXPECT_EQ(X, uint32_t(0x67452301));
- EXPECT_EQ(Y, uint32_t(0x01234567));
-#else
- ADD_FAILURE() << "BYTE_ORDER is neither BIG_ENDIAN nor LITTLE_ENDIAN.";
-#endif
-}
-
-TEST(BitTest, byte_swap_64) {
- unsigned char Seq[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF};
- uint64_t X = 0;
- memcpy(&X, Seq, sizeof(X));
- auto Y = byteswap(X);
-
- static_assert(sizeof(Seq) == sizeof(X),
- "sizeof(char[8]) != sizeof(uint64_t) ?");
- static_assert(std::is_same_v<decltype(X), decltype(Y)>,
- "byte_swap return type doesn't match input");
-
-#if defined(IS_BIG_ENDIAN)
- EXPECT_EQ(X, uint64_t(0x0123456789ABCDEF));
- EXPECT_EQ(Y, uint64_t(0xEFCDAB8967452301));
-#elif defined(IS_LITTLE_ENDIAN)
- EXPECT_EQ(X, uint64_t(0xEFCDAB8967452301));
- EXPECT_EQ(Y, uint64_t(0x0123456789ABCDEF));
-#else
- ADD_FAILURE() << "BYTE_ORDER is neither BIG_ENDIAN nor LITTLE_ENDIAN.";
-#endif
-}
-
-TEST(BitTest, CountlZero) {
- uint8_t Z8 = 0;
- uint16_t Z16 = 0;
- uint32_t Z32 = 0;
- uint64_t Z64 = 0;
- EXPECT_EQ(8, orc_rt::countl_zero(Z8));
- EXPECT_EQ(16, orc_rt::countl_zero(Z16));
- EXPECT_EQ(32, orc_rt::countl_zero(Z32));
- EXPECT_EQ(64, orc_rt::countl_zero(Z64));
-
- uint8_t NZ8 = 42;
- uint16_t NZ16 = 42;
- uint32_t NZ32 = 42;
- uint64_t NZ64 = 42;
- EXPECT_EQ(2, orc_rt::countl_zero(NZ8));
- EXPECT_EQ(10, orc_rt::countl_zero(NZ16));
- EXPECT_EQ(26, orc_rt::countl_zero(NZ32));
- EXPECT_EQ(58, orc_rt::countl_zero(NZ64));
-
- EXPECT_EQ(8, orc_rt::countl_zero(0x00F000FFu));
- EXPECT_EQ(8, orc_rt::countl_zero(0x00F12345u));
- for (unsigned i = 0; i <= 30; ++i) {
- EXPECT_EQ(int(31 - i), orc_rt::countl_zero(1u << i));
- }
-
- EXPECT_EQ(8, orc_rt::countl_zero(0x00F1234500F12345ULL));
- EXPECT_EQ(1, orc_rt::countl_zero(1ULL << 62));
- for (unsigned i = 0; i <= 62; ++i) {
- EXPECT_EQ(int(63 - i), orc_rt::countl_zero(1ULL << i));
- }
-}
-
-TEST(BitTest, BitWidth) {
- EXPECT_EQ(0, orc_rt::bit_width(uint8_t(0)));
- EXPECT_EQ(0, orc_rt::bit_width(uint16_t(0)));
- EXPECT_EQ(0, orc_rt::bit_width(uint32_t(0)));
- EXPECT_EQ(0, orc_rt::bit_width(uint64_t(0)));
-
- EXPECT_EQ(1, orc_rt::bit_width(uint8_t(1)));
- EXPECT_EQ(1, orc_rt::bit_width(uint16_t(1)));
- EXPECT_EQ(1, orc_rt::bit_width(uint32_t(1)));
- EXPECT_EQ(1, orc_rt::bit_width(uint64_t(1)));
-
- EXPECT_EQ(2, orc_rt::bit_width(uint8_t(2)));
- EXPECT_EQ(2, orc_rt::bit_width(uint16_t(2)));
- EXPECT_EQ(2, orc_rt::bit_width(uint32_t(2)));
- EXPECT_EQ(2, orc_rt::bit_width(uint64_t(2)));
-
- EXPECT_EQ(2, orc_rt::bit_width(uint8_t(3)));
- EXPECT_EQ(2, orc_rt::bit_width(uint16_t(3)));
- EXPECT_EQ(2, orc_rt::bit_width(uint32_t(3)));
- EXPECT_EQ(2, orc_rt::bit_width(uint64_t(3)));
-
- EXPECT_EQ(3, orc_rt::bit_width(uint8_t(4)));
- EXPECT_EQ(3, orc_rt::bit_width(uint16_t(4)));
- EXPECT_EQ(3, orc_rt::bit_width(uint32_t(4)));
- EXPECT_EQ(3, orc_rt::bit_width(uint64_t(4)));
-
- EXPECT_EQ(7, orc_rt::bit_width(uint8_t(0x7f)));
- EXPECT_EQ(15, orc_rt::bit_width(uint16_t(0x7fff)));
- EXPECT_EQ(31, orc_rt::bit_width(uint32_t(0x7fffffffu)));
- EXPECT_EQ(63, orc_rt::bit_width(uint64_t(0x7fffffffffffffffull)));
-
- EXPECT_EQ(8, orc_rt::bit_width(uint8_t(0x80)));
- EXPECT_EQ(16, orc_rt::bit_width(uint16_t(0x8000)));
- EXPECT_EQ(32, orc_rt::bit_width(uint32_t(0x80000000u)));
- EXPECT_EQ(64, orc_rt::bit_width(uint64_t(0x8000000000000000ull)));
-
- EXPECT_EQ(8, orc_rt::bit_width(uint8_t(0xff)));
- EXPECT_EQ(16, orc_rt::bit_width(uint16_t(0xffff)));
- EXPECT_EQ(32, orc_rt::bit_width(uint32_t(0xffffffffu)));
- EXPECT_EQ(64, orc_rt::bit_width(uint64_t(0xffffffffffffffffull)));
-}
-
-TEST(BitTest, HasSingleBit) {
- EXPECT_FALSE(orc_rt::has_single_bit(0U));
- EXPECT_FALSE(orc_rt::has_single_bit(0ULL));
-
- EXPECT_FALSE(orc_rt::has_single_bit(~0U));
- EXPECT_FALSE(orc_rt::has_single_bit(~0ULL));
-
- EXPECT_TRUE(orc_rt::has_single_bit(1U));
- EXPECT_TRUE(orc_rt::has_single_bit(1ULL));
-
- static const int8_t kValueS8 = -128;
- EXPECT_TRUE(orc_rt::has_single_bit(static_cast<uint8_t>(kValueS8)));
-
- static const int16_t kValueS16 = -32768;
- EXPECT_TRUE(orc_rt::has_single_bit(static_cast<uint16_t>(kValueS16)));
-
- // Dense sweep and power-of-two boundaries.
- for (unsigned V : {0x00U, 0x03U, 0x05U, 0x06U, 0x07U, 0x09U, 0x0aU, 0x0bU,
- 0x0cU, 0x0dU, 0x0eU, 0x0fU})
- EXPECT_FALSE(orc_rt::has_single_bit(V)) << "V = " << V;
- for (unsigned V : {0x01U, 0x02U, 0x04U, 0x08U, 0x10U})
- EXPECT_TRUE(orc_rt::has_single_bit(V)) << "V = " << V;
-
- for (unsigned V : {0x20U, 0x40U, 0x80U, 0x40000000U}) {
- EXPECT_FALSE(orc_rt::has_single_bit(V - 1)) << "V = " << V;
- EXPECT_TRUE(orc_rt::has_single_bit(V)) << "V = " << V;
- EXPECT_FALSE(orc_rt::has_single_bit(V + 1)) << "V = " << V;
- }
-}
-
-TEST(BitTest, Rotl) {
- EXPECT_EQ(0x53U, orc_rt::rotl<uint8_t>(0x53, 0));
- EXPECT_EQ(0x4dU, orc_rt::rotl<uint8_t>(0x53, 2));
- EXPECT_EQ(0xa6U, orc_rt::rotl<uint8_t>(0x53, 9));
- EXPECT_EQ(0x9aU, orc_rt::rotl<uint8_t>(0x53, -5));
-
- EXPECT_EQ(0xabcdU, orc_rt::rotl<uint16_t>(0xabcd, 0));
- EXPECT_EQ(0xf36aU, orc_rt::rotl<uint16_t>(0xabcd, 6));
- EXPECT_EQ(0xaf36U, orc_rt::rotl<uint16_t>(0xabcd, 18));
- EXPECT_EQ(0xf36aU, orc_rt::rotl<uint16_t>(0xabcd, -10));
-
- EXPECT_EQ(0xdeadbeefU, orc_rt::rotl<uint32_t>(0xdeadbeef, 0));
- EXPECT_EQ(0x7ddfbd5bU, orc_rt::rotl<uint32_t>(0xdeadbeef, 17));
- EXPECT_EQ(0x5b7ddfbdU, orc_rt::rotl<uint32_t>(0xdeadbeef, 41));
- EXPECT_EQ(0xb6fbbf7aU, orc_rt::rotl<uint32_t>(0xdeadbeef, -22));
-
- EXPECT_EQ(0x12345678deadbeefULL,
- orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, 0));
- EXPECT_EQ(0xf56df77891a2b3c6ULL,
- orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, 35));
- EXPECT_EQ(0x8d159e37ab6fbbc4ULL,
- orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, 70));
- EXPECT_EQ(0xb7dde2468acf1bd5ULL,
- orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, -19));
-}
-
-TEST(BitTest, Rotr) {
- EXPECT_EQ(0x53U, orc_rt::rotr<uint8_t>(0x53, 0));
- EXPECT_EQ(0xd4U, orc_rt::rotr<uint8_t>(0x53, 2));
- EXPECT_EQ(0xa9U, orc_rt::rotr<uint8_t>(0x53, 9));
- EXPECT_EQ(0x6aU, orc_rt::rotr<uint8_t>(0x53, -5));
-
- EXPECT_EQ(0xabcdU, orc_rt::rotr<uint16_t>(0xabcd, 0));
- EXPECT_EQ(0x36afU, orc_rt::rotr<uint16_t>(0xabcd, 6));
- EXPECT_EQ(0x6af3U, orc_rt::rotr<uint16_t>(0xabcd, 18));
- EXPECT_EQ(0x36afU, orc_rt::rotr<uint16_t>(0xabcd, -10));
-
- EXPECT_EQ(0xdeadbeefU, orc_rt::rotr<uint32_t>(0xdeadbeef, 0));
- EXPECT_EQ(0xdf77ef56U, orc_rt::rotr<uint32_t>(0xdeadbeef, 17));
- EXPECT_EQ(0x77ef56dfU, orc_rt::rotr<uint32_t>(0xdeadbeef, 41));
- EXPECT_EQ(0xbbf7ab6fU, orc_rt::rotr<uint32_t>(0xdeadbeef, -22));
-
- EXPECT_EQ(0x12345678deadbeefULL,
- orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, 0));
- EXPECT_EQ(0x1bd5b7dde2468acfULL,
- orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, 35));
- EXPECT_EQ(0xbc48d159e37ab6fbULL,
- orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, 70));
- EXPECT_EQ(0xb3c6f56df77891a2ULL,
- orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, -19));
-}
+//===- bit-test.cpp -------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for orc-rt's bit.h APIs.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt/support/bit.h"
+#include "gtest/gtest.h"
+
+#include <cstdint>
+
+#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
+#define IS_BIG_ENDIAN
+#elif defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && \
+ BYTE_ORDER == LITTLE_ENDIAN
+#define IS_LITTLE_ENDIAN
+#endif
+
+#if !defined(BYTE_ORDER) && defined(_MSC_VER)
+#define IS_LITTLE_ENDIAN
+#endif
+
+
+using namespace orc_rt;
+
+TEST(BitTest, endian) {
+#if defined(IS_BIG_ENDIAN)
+ EXPECT_EQ(endian::native, endian::big);
+#elif defined(IS_LITTLE_ENDIAN)
+ EXPECT_EQ(endian::native, endian::little);
+#else
+ ADD_FAILURE() << "BYTE_ORDER is neither BIG_ENDIAN nor LITTLE_ENDIAN.";
+#endif
+}
+
+TEST(BitTest, byte_swap_32) {
+ unsigned char Seq[] = {0x01, 0x23, 0x45, 0x67};
+ uint32_t X = 0;
+ memcpy(&X, Seq, sizeof(X));
+ auto Y = byteswap(X);
+
+ static_assert(sizeof(Seq) == sizeof(X),
+ "sizeof(char[4]) != sizeof(uint32_t) ?");
+ static_assert(std::is_same_v<decltype(X), decltype(Y)>,
+ "byte_swap return type doesn't match input");
+
+#if defined(IS_BIG_ENDIAN)
+ EXPECT_EQ(X, uint32_t(0x01234567));
+ EXPECT_EQ(Y, uint32_t(0x67452301));
+#elif defined(IS_LITTLE_ENDIAN)
+ EXPECT_EQ(X, uint32_t(0x67452301));
+ EXPECT_EQ(Y, uint32_t(0x01234567));
+#else
+ ADD_FAILURE() << "BYTE_ORDER is neither BIG_ENDIAN nor LITTLE_ENDIAN.";
+#endif
+}
+
+TEST(BitTest, byte_swap_64) {
+ unsigned char Seq[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF};
+ uint64_t X = 0;
+ memcpy(&X, Seq, sizeof(X));
+ auto Y = byteswap(X);
+
+ static_assert(sizeof(Seq) == sizeof(X),
+ "sizeof(char[8]) != sizeof(uint64_t) ?");
+ static_assert(std::is_same_v<decltype(X), decltype(Y)>,
+ "byte_swap return type doesn't match input");
+
+#if defined(IS_BIG_ENDIAN)
+ EXPECT_EQ(X, uint64_t(0x0123456789ABCDEF));
+ EXPECT_EQ(Y, uint64_t(0xEFCDAB8967452301));
+#elif defined(IS_LITTLE_ENDIAN)
+ EXPECT_EQ(X, uint64_t(0xEFCDAB8967452301));
+ EXPECT_EQ(Y, uint64_t(0x0123456789ABCDEF));
+#else
+ ADD_FAILURE() << "BYTE_ORDER is neither BIG_ENDIAN nor LITTLE_ENDIAN.";
+#endif
+}
+
+TEST(BitTest, CountlZero) {
+ uint8_t Z8 = 0;
+ uint16_t Z16 = 0;
+ uint32_t Z32 = 0;
+ uint64_t Z64 = 0;
+ EXPECT_EQ(8, orc_rt::countl_zero(Z8));
+ EXPECT_EQ(16, orc_rt::countl_zero(Z16));
+ EXPECT_EQ(32, orc_rt::countl_zero(Z32));
+ EXPECT_EQ(64, orc_rt::countl_zero(Z64));
+
+ uint8_t NZ8 = 42;
+ uint16_t NZ16 = 42;
+ uint32_t NZ32 = 42;
+ uint64_t NZ64 = 42;
+ EXPECT_EQ(2, orc_rt::countl_zero(NZ8));
+ EXPECT_EQ(10, orc_rt::countl_zero(NZ16));
+ EXPECT_EQ(26, orc_rt::countl_zero(NZ32));
+ EXPECT_EQ(58, orc_rt::countl_zero(NZ64));
+
+ EXPECT_EQ(8, orc_rt::countl_zero(0x00F000FFu));
+ EXPECT_EQ(8, orc_rt::countl_zero(0x00F12345u));
+ for (unsigned i = 0; i <= 30; ++i) {
+ EXPECT_EQ(int(31 - i), orc_rt::countl_zero(1u << i));
+ }
+
+ EXPECT_EQ(8, orc_rt::countl_zero(0x00F1234500F12345ULL));
+ EXPECT_EQ(1, orc_rt::countl_zero(1ULL << 62));
+ for (unsigned i = 0; i <= 62; ++i) {
+ EXPECT_EQ(int(63 - i), orc_rt::countl_zero(1ULL << i));
+ }
+}
+
+TEST(BitTest, BitWidth) {
+ EXPECT_EQ(0, orc_rt::bit_width(uint8_t(0)));
+ EXPECT_EQ(0, orc_rt::bit_width(uint16_t(0)));
+ EXPECT_EQ(0, orc_rt::bit_width(uint32_t(0)));
+ EXPECT_EQ(0, orc_rt::bit_width(uint64_t(0)));
+
+ EXPECT_EQ(1, orc_rt::bit_width(uint8_t(1)));
+ EXPECT_EQ(1, orc_rt::bit_width(uint16_t(1)));
+ EXPECT_EQ(1, orc_rt::bit_width(uint32_t(1)));
+ EXPECT_EQ(1, orc_rt::bit_width(uint64_t(1)));
+
+ EXPECT_EQ(2, orc_rt::bit_width(uint8_t(2)));
+ EXPECT_EQ(2, orc_rt::bit_width(uint16_t(2)));
+ EXPECT_EQ(2, orc_rt::bit_width(uint32_t(2)));
+ EXPECT_EQ(2, orc_rt::bit_width(uint64_t(2)));
+
+ EXPECT_EQ(2, orc_rt::bit_width(uint8_t(3)));
+ EXPECT_EQ(2, orc_rt::bit_width(uint16_t(3)));
+ EXPECT_EQ(2, orc_rt::bit_width(uint32_t(3)));
+ EXPECT_EQ(2, orc_rt::bit_width(uint64_t(3)));
+
+ EXPECT_EQ(3, orc_rt::bit_width(uint8_t(4)));
+ EXPECT_EQ(3, orc_rt::bit_width(uint16_t(4)));
+ EXPECT_EQ(3, orc_rt::bit_width(uint32_t(4)));
+ EXPECT_EQ(3, orc_rt::bit_width(uint64_t(4)));
+
+ EXPECT_EQ(7, orc_rt::bit_width(uint8_t(0x7f)));
+ EXPECT_EQ(15, orc_rt::bit_width(uint16_t(0x7fff)));
+ EXPECT_EQ(31, orc_rt::bit_width(uint32_t(0x7fffffffu)));
+ EXPECT_EQ(63, orc_rt::bit_width(uint64_t(0x7fffffffffffffffull)));
+
+ EXPECT_EQ(8, orc_rt::bit_width(uint8_t(0x80)));
+ EXPECT_EQ(16, orc_rt::bit_width(uint16_t(0x8000)));
+ EXPECT_EQ(32, orc_rt::bit_width(uint32_t(0x80000000u)));
+ EXPECT_EQ(64, orc_rt::bit_width(uint64_t(0x8000000000000000ull)));
+
+ EXPECT_EQ(8, orc_rt::bit_width(uint8_t(0xff)));
+ EXPECT_EQ(16, orc_rt::bit_width(uint16_t(0xffff)));
+ EXPECT_EQ(32, orc_rt::bit_width(uint32_t(0xffffffffu)));
+ EXPECT_EQ(64, orc_rt::bit_width(uint64_t(0xffffffffffffffffull)));
+}
+
+TEST(BitTest, HasSingleBit) {
+ EXPECT_FALSE(orc_rt::has_single_bit(0U));
+ EXPECT_FALSE(orc_rt::has_single_bit(0ULL));
+
+ EXPECT_FALSE(orc_rt::has_single_bit(~0U));
+ EXPECT_FALSE(orc_rt::has_single_bit(~0ULL));
+
+ EXPECT_TRUE(orc_rt::has_single_bit(1U));
+ EXPECT_TRUE(orc_rt::has_single_bit(1ULL));
+
+ static const int8_t kValueS8 = -128;
+ EXPECT_TRUE(orc_rt::has_single_bit(static_cast<uint8_t>(kValueS8)));
+
+ static const int16_t kValueS16 = -32768;
+ EXPECT_TRUE(orc_rt::has_single_bit(static_cast<uint16_t>(kValueS16)));
+
+ // Dense sweep and power-of-two boundaries.
+ for (unsigned V : {0x00U, 0x03U, 0x05U, 0x06U, 0x07U, 0x09U, 0x0aU, 0x0bU,
+ 0x0cU, 0x0dU, 0x0eU, 0x0fU})
+ EXPECT_FALSE(orc_rt::has_single_bit(V)) << "V = " << V;
+ for (unsigned V : {0x01U, 0x02U, 0x04U, 0x08U, 0x10U})
+ EXPECT_TRUE(orc_rt::has_single_bit(V)) << "V = " << V;
+
+ for (unsigned V : {0x20U, 0x40U, 0x80U, 0x40000000U}) {
+ EXPECT_FALSE(orc_rt::has_single_bit(V - 1)) << "V = " << V;
+ EXPECT_TRUE(orc_rt::has_single_bit(V)) << "V = " << V;
+ EXPECT_FALSE(orc_rt::has_single_bit(V + 1)) << "V = " << V;
+ }
+}
+
+TEST(BitTest, Rotl) {
+ EXPECT_EQ(0x53U, orc_rt::rotl<uint8_t>(0x53, 0));
+ EXPECT_EQ(0x4dU, orc_rt::rotl<uint8_t>(0x53, 2));
+ EXPECT_EQ(0xa6U, orc_rt::rotl<uint8_t>(0x53, 9));
+ EXPECT_EQ(0x9aU, orc_rt::rotl<uint8_t>(0x53, -5));
+
+ EXPECT_EQ(0xabcdU, orc_rt::rotl<uint16_t>(0xabcd, 0));
+ EXPECT_EQ(0xf36aU, orc_rt::rotl<uint16_t>(0xabcd, 6));
+ EXPECT_EQ(0xaf36U, orc_rt::rotl<uint16_t>(0xabcd, 18));
+ EXPECT_EQ(0xf36aU, orc_rt::rotl<uint16_t>(0xabcd, -10));
+
+ EXPECT_EQ(0xdeadbeefU, orc_rt::rotl<uint32_t>(0xdeadbeef, 0));
+ EXPECT_EQ(0x7ddfbd5bU, orc_rt::rotl<uint32_t>(0xdeadbeef, 17));
+ EXPECT_EQ(0x5b7ddfbdU, orc_rt::rotl<uint32_t>(0xdeadbeef, 41));
+ EXPECT_EQ(0xb6fbbf7aU, orc_rt::rotl<uint32_t>(0xdeadbeef, -22));
+
+ EXPECT_EQ(0x12345678deadbeefULL,
+ orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, 0));
+ EXPECT_EQ(0xf56df77891a2b3c6ULL,
+ orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, 35));
+ EXPECT_EQ(0x8d159e37ab6fbbc4ULL,
+ orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, 70));
+ EXPECT_EQ(0xb7dde2468acf1bd5ULL,
+ orc_rt::rotl<uint64_t>(0x12345678deadbeefULL, -19));
+}
+
+TEST(BitTest, Rotr) {
+ EXPECT_EQ(0x53U, orc_rt::rotr<uint8_t>(0x53, 0));
+ EXPECT_EQ(0xd4U, orc_rt::rotr<uint8_t>(0x53, 2));
+ EXPECT_EQ(0xa9U, orc_rt::rotr<uint8_t>(0x53, 9));
+ EXPECT_EQ(0x6aU, orc_rt::rotr<uint8_t>(0x53, -5));
+
+ EXPECT_EQ(0xabcdU, orc_rt::rotr<uint16_t>(0xabcd, 0));
+ EXPECT_EQ(0x36afU, orc_rt::rotr<uint16_t>(0xabcd, 6));
+ EXPECT_EQ(0x6af3U, orc_rt::rotr<uint16_t>(0xabcd, 18));
+ EXPECT_EQ(0x36afU, orc_rt::rotr<uint16_t>(0xabcd, -10));
+
+ EXPECT_EQ(0xdeadbeefU, orc_rt::rotr<uint32_t>(0xdeadbeef, 0));
+ EXPECT_EQ(0xdf77ef56U, orc_rt::rotr<uint32_t>(0xdeadbeef, 17));
+ EXPECT_EQ(0x77ef56dfU, orc_rt::rotr<uint32_t>(0xdeadbeef, 41));
+ EXPECT_EQ(0xbbf7ab6fU, orc_rt::rotr<uint32_t>(0xdeadbeef, -22));
+
+ EXPECT_EQ(0x12345678deadbeefULL,
+ orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, 0));
+ EXPECT_EQ(0x1bd5b7dde2468acfULL,
+ orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, 35));
+ EXPECT_EQ(0xbc48d159e37ab6fbULL,
+ orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, 70));
+ EXPECT_EQ(0xb3c6f56df77891a2ULL,
+ orc_rt::rotr<uint64_t>(0x12345678deadbeefULL, -19));
+}
diff --git a/orc-rt/test/unit/tools/OptionParserTest.cpp b/orc-rt/test/unit/tools/OptionParserTest.cpp
index 8af7b1d122059..1e3ba49fed5b7 100644
--- a/orc-rt/test/unit/tools/OptionParserTest.cpp
+++ b/orc-rt/test/unit/tools/OptionParserTest.cpp
@@ -1,166 +1,165 @@
-//===- OptionParserTest.cpp -----------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt-internal/tools/OptionParser.h"
-#include "orc-rt/support/Error.h"
-#include "llvm/Testing/Support/Error.h"
-#include "gtest/gtest.h"
-
-using namespace orc_rt;
-
-class OptionParserTest : public ::testing::Test {
-protected:
- std::string Host;
- int Port = 0;
- bool Verbose = false;
- bool Help = false;
- OptionParser Parser;
-
- void SetUp() override {
- Parser.addValue("host", "Hostname", std::string("localhost"), Host,
- OptionParser::OptionKind::Value, 'h');
- Parser.addFlag("help", "Display this help message", false, Help, '?');
- Parser.addValue("port", "Port number", 8080, Port,
- OptionParser::OptionKind::Value, 'p');
- Parser.addFlag("verbose", "Enable verbose logging", false, Verbose, 'v');
- }
-};
-
-TEST_F(OptionParserTest, NoopTest) {
- OptionParser Parser;
- const char *Argv[] = {""};
- auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
- EXPECT_FALSE(!!Err);
-}
-
-TEST_F(OptionParserTest, ValueRequired) {
- const char *Argv[] = {"--host"};
- auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
- if (!Err) {
- ADD_FAILURE() << "--host requires a value, shouldn't succeed.";
- } else {
- orc_rt::consumeError(std::move(Err));
- }
-}
-
-TEST_F(OptionParserTest, UnknownOption) {
- const char *Argv[] = {"--unknown=foo"};
- auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
- if (!Err) {
- ADD_FAILURE() << "unknown option, shouldn't succeed.";
- } else {
- orc_rt::consumeError(std::move(Err));
- }
-}
-
-TEST_F(OptionParserTest, InvalidInteger) {
- const char *Argv[] = {"--port=not_a_number"};
- auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
- if (!Err) {
- ADD_FAILURE() << "Invalid integer, shouldn't succeed.";
- } else {
- orc_rt::consumeError(std::move(Err));
- }
-}
-
-TEST_F(OptionParserTest, ParseFullConfiguration) {
- const char *Argv[] = {"--host=example.com", "--port=8080", "--verbose=true"};
- cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
- EXPECT_EQ(Host, "example.com");
- EXPECT_EQ(Port, 8080);
- EXPECT_EQ(Verbose, true);
-}
-
-TEST_F(OptionParserTest, ShortFlagClustering) {
- const char *Argv[] = {"-v?"};
- cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
- EXPECT_TRUE(Verbose);
- EXPECT_TRUE(Help);
-}
-
-TEST_F(OptionParserTest, ShortFlagWithValue) {
- const char *Argv[] = {"-p", "1234", "-hlocalhost"};
- cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
- EXPECT_EQ(Port, 1234);
- EXPECT_EQ(Host, "localhost");
-}
-
-TEST_F(OptionParserTest, ClusterWithValueAtEnd) {
- const char *Argv[] = {"-vp9999"};
- cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
- EXPECT_TRUE(Verbose);
- EXPECT_EQ(Port, 9999);
-}
-
-TEST_F(OptionParserTest, DoubleDashTerminatesOptionParsing) {
- const char *Argv[] = {"-v", "--", "-p", "1234"};
- cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
-
- EXPECT_TRUE(Verbose);
- EXPECT_EQ(Port, 8080); // Should remain default
- ASSERT_EQ(Parser.positionals().size(), 2u);
- EXPECT_EQ(Parser.positionals()[0], "-p");
- EXPECT_EQ(Parser.positionals()[1], "1234");
-}
-
-TEST_F(OptionParserTest, ParseAsMainWithEmptyArgsSucceeds) {
- const char *Argv[] = {"appname"};
- auto Err = Parser.parseAsMainArgs(std::size(Argv), const_cast<char **>(Argv));
- EXPECT_FALSE(!!Err);
-}
-
-TEST_F(OptionParserTest, ParseAsMainWithRegularArgsSucceeds) {
- const char *Argv[] = {"appname", "-v", "--", "-p", "1234"};
- cantFail(Parser.parseAsMainArgs(std::size(Argv), const_cast<char **>(Argv)));
-
- EXPECT_TRUE(Verbose);
- EXPECT_EQ(Port, 8080); // Should remain default
- ASSERT_EQ(Parser.positionals().size(), 2u);
- EXPECT_EQ(Parser.positionals()[0], "-p");
- EXPECT_EQ(Parser.positionals()[1], "1234");
-}
-
-TEST_F(OptionParserTest, ParseAsMainWithEmplyListFails) {
- const char *Argv[] = {};
- auto Err = Parser.parseAsMainArgs(0, const_cast<char **>(Argv));
-
- EXPECT_TRUE(!!Err);
- consumeError(std::move(Err));
-}
-
-TEST_F(OptionParserTest, PrintHelpAlignmentWithShortFlags) {
- std::string LogFile;
- Parser.addValue("log-file", "Path to log", std::string("out.log"), LogFile);
-
- std::string Result = Parser.formatHelp("appname");
-
- auto GetColumn = [&](std::string_view SearchTerm) -> size_t {
- size_t Pos = Result.find(SearchTerm);
- if (Pos == std::string::npos)
- return 0;
- size_t LineStart = Result.rfind('\n', Pos);
- return (LineStart == std::string::npos) ? Pos : (Pos - LineStart - 1);
- };
-
- size_t PortDescCol = GetColumn("Port number");
- size_t LogDescCol = GetColumn("Path to log");
- size_t VerbDescCol = GetColumn("Enable verbose");
-
- ASSERT_NE(PortDescCol, 0u);
- EXPECT_EQ(PortDescCol, LogDescCol)
- << "Descriptions should align even if short flag is missing";
- EXPECT_EQ(LogDescCol, VerbDescCol);
-
- size_t LogFlagPos = Result.find("--log-file");
- size_t PortFlagPos = Result.find("--port");
-
- size_t LogFlagCol = (LogFlagPos - Result.rfind('\n', LogFlagPos) - 1);
- size_t PortFlagCol = (PortFlagPos - Result.rfind('\n', PortFlagPos) - 1);
-
- EXPECT_EQ(LogFlagCol, PortFlagCol);
-}
+//===- OptionParserTest.cpp -----------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt-internal/tools/OptionParser.h"
+#include "orc-rt/support/Error.h"
+#include "llvm/Testing/Support/Error.h"
+#include "gtest/gtest.h"
+
+using namespace orc_rt;
+
+class OptionParserTest : public ::testing::Test {
+protected:
+ std::string Host;
+ int Port = 0;
+ bool Verbose = false;
+ bool Help = false;
+ OptionParser Parser;
+
+ void SetUp() override {
+ Parser.addValue("host", "Hostname", std::string("localhost"), Host,
+ OptionParser::OptionKind::Value, 'h');
+ Parser.addFlag("help", "Display this help message", false, Help, '?');
+ Parser.addValue("port", "Port number", 8080, Port,
+ OptionParser::OptionKind::Value, 'p');
+ Parser.addFlag("verbose", "Enable verbose logging", false, Verbose, 'v');
+ }
+};
+
+TEST_F(OptionParserTest, NoopTest) {
+ OptionParser Parser;
+ const char *Argv[] = {""};
+ auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
+ EXPECT_FALSE(!!Err);
+}
+
+TEST_F(OptionParserTest, ValueRequired) {
+ const char *Argv[] = {"--host"};
+ auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
+ if (!Err) {
+ ADD_FAILURE() << "--host requires a value, shouldn't succeed.";
+ } else {
+ orc_rt::consumeError(std::move(Err));
+ }
+}
+
+TEST_F(OptionParserTest, UnknownOption) {
+ const char *Argv[] = {"--unknown=foo"};
+ auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
+ if (!Err) {
+ ADD_FAILURE() << "unknown option, shouldn't succeed.";
+ } else {
+ orc_rt::consumeError(std::move(Err));
+ }
+}
+
+TEST_F(OptionParserTest, InvalidInteger) {
+ const char *Argv[] = {"--port=not_a_number"};
+ auto Err = Parser.parse(std::begin(Argv), std::end(Argv));
+ if (!Err) {
+ ADD_FAILURE() << "Invalid integer, shouldn't succeed.";
+ } else {
+ orc_rt::consumeError(std::move(Err));
+ }
+}
+
+TEST_F(OptionParserTest, ParseFullConfiguration) {
+ const char *Argv[] = {"--host=example.com", "--port=8080", "--verbose=true"};
+ cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+ EXPECT_EQ(Host, "example.com");
+ EXPECT_EQ(Port, 8080);
+ EXPECT_EQ(Verbose, true);
+}
+
+TEST_F(OptionParserTest, ShortFlagClustering) {
+ const char *Argv[] = {"-v?"};
+ cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+ EXPECT_TRUE(Verbose);
+ EXPECT_TRUE(Help);
+}
+
+TEST_F(OptionParserTest, ShortFlagWithValue) {
+ const char *Argv[] = {"-p", "1234", "-hlocalhost"};
+ cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+ EXPECT_EQ(Port, 1234);
+ EXPECT_EQ(Host, "localhost");
+}
+
+TEST_F(OptionParserTest, ClusterWithValueAtEnd) {
+ const char *Argv[] = {"-vp9999"};
+ cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+ EXPECT_TRUE(Verbose);
+ EXPECT_EQ(Port, 9999);
+}
+
+TEST_F(OptionParserTest, DoubleDashTerminatesOptionParsing) {
+ const char *Argv[] = {"-v", "--", "-p", "1234"};
+ cantFail(Parser.parse(std::begin(Argv), std::end(Argv)));
+
+ EXPECT_TRUE(Verbose);
+ EXPECT_EQ(Port, 8080); // Should remain default
+ ASSERT_EQ(Parser.positionals().size(), 2u);
+ EXPECT_EQ(Parser.positionals()[0], "-p");
+ EXPECT_EQ(Parser.positionals()[1], "1234");
+}
+
+TEST_F(OptionParserTest, ParseAsMainWithEmptyArgsSucceeds) {
+ const char *Argv[] = {"appname"};
+ auto Err = Parser.parseAsMainArgs(std::size(Argv), const_cast<char **>(Argv));
+ EXPECT_FALSE(!!Err);
+}
+
+TEST_F(OptionParserTest, ParseAsMainWithRegularArgsSucceeds) {
+ const char *Argv[] = {"appname", "-v", "--", "-p", "1234"};
+ cantFail(Parser.parseAsMainArgs(std::size(Argv), const_cast<char **>(Argv)));
+
+ EXPECT_TRUE(Verbose);
+ EXPECT_EQ(Port, 8080); // Should remain default
+ ASSERT_EQ(Parser.positionals().size(), 2u);
+ EXPECT_EQ(Parser.positionals()[0], "-p");
+ EXPECT_EQ(Parser.positionals()[1], "1234");
+}
+
+TEST_F(OptionParserTest, ParseAsMainWithEmptyListFails) {
+ auto Err = Parser.parseAsMainArgs(0, nullptr);
+
+ EXPECT_TRUE(!!Err);
+ consumeError(std::move(Err));
+}
+
+TEST_F(OptionParserTest, PrintHelpAlignmentWithShortFlags) {
+ std::string LogFile;
+ Parser.addValue("log-file", "Path to log", std::string("out.log"), LogFile);
+
+ std::string Result = Parser.formatHelp("appname");
+
+ auto GetColumn = [&](std::string_view SearchTerm) -> size_t {
+ size_t Pos = Result.find(SearchTerm);
+ if (Pos == std::string::npos)
+ return 0;
+ size_t LineStart = Result.rfind('\n', Pos);
+ return (LineStart == std::string::npos) ? Pos : (Pos - LineStart - 1);
+ };
+
+ size_t PortDescCol = GetColumn("Port number");
+ size_t LogDescCol = GetColumn("Path to log");
+ size_t VerbDescCol = GetColumn("Enable verbose");
+
+ ASSERT_NE(PortDescCol, 0u);
+ EXPECT_EQ(PortDescCol, LogDescCol)
+ << "Descriptions should align even if short flag is missing";
+ EXPECT_EQ(LogDescCol, VerbDescCol);
+
+ size_t LogFlagPos = Result.find("--log-file");
+ size_t PortFlagPos = Result.find("--port");
+
+ size_t LogFlagCol = (LogFlagPos - Result.rfind('\n', LogFlagPos) - 1);
+ size_t PortFlagCol = (PortFlagPos - Result.rfind('\n', PortFlagPos) - 1);
+
+ EXPECT_EQ(LogFlagCol, PortFlagCol);
+}
>From 4504f54e6dad1e055e6614023427fb37d106b7af Mon Sep 17 00:00:00 2001
From: Jared Wyles <jared.wyles at gmail.com>
Date: Fri, 18 Sep 2026 14:59:24 +1000
Subject: [PATCH 3/3] [orc-rt] Implement Windows target triple detection
---
.../lib/bedrock/sys/windows/TargetTriple.cpp | 8 +-
.../unit/bedrock/sys/TargetTripleTest.cpp | 119 +++++++++---------
2 files changed, 68 insertions(+), 59 deletions(-)
diff --git a/orc-rt/lib/bedrock/sys/windows/TargetTriple.cpp b/orc-rt/lib/bedrock/sys/windows/TargetTriple.cpp
index 465a24afc82f8..7a5db97b98f7b 100644
--- a/orc-rt/lib/bedrock/sys/windows/TargetTriple.cpp
+++ b/orc-rt/lib/bedrock/sys/windows/TargetTriple.cpp
@@ -10,6 +10,12 @@
namespace orc_rt::sys {
-std::string detectTargetTriple() noexcept { return {}; }
+std::string detectTargetTriple() noexcept {
+#if defined(_M_X64)
+ return "x86_64-pc-windows-msvc";
+#else
+#error "Unsupported Windows architecture"
+#endif
+}
} // namespace orc_rt::sys
diff --git a/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp b/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp
index 647518dfb0a44..b94f68d60be1f 100644
--- a/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp
+++ b/orc-rt/test/unit/bedrock/sys/TargetTripleTest.cpp
@@ -1,58 +1,61 @@
-//===- TargetTripleTest.cpp -----------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// Tests for orc-rt's bedrock/sys/TargetTriple.h APIs.
-//
-//===----------------------------------------------------------------------===//
-
-#include "orc-rt-internal/bedrock/sys/TargetTriple.h"
-#include "gtest/gtest.h"
-
-#include <algorithm>
-
-using namespace orc_rt;
-#ifndef _WIN32
-TEST(TargetTripleTest, NotEmpty) {
- EXPECT_FALSE(sys::detectTargetTriple().empty());
-}
-
-TEST(TargetTripleTest, HasValidStructure) {
- auto Triple = sys::detectTargetTriple();
- // A valid triple has 2 hyphens (arch-vendor-os) or 3 (arch-vendor-os-env).
- auto NumHyphens = std::count(Triple.begin(), Triple.end(), '-');
- EXPECT_GE(NumHyphens, 2);
- EXPECT_LE(NumHyphens, 3);
-}
-
-TEST(TargetTripleTest, ArchMatchesCompileTarget) {
- auto Triple = sys::detectTargetTriple();
-#if defined(__arm64e__)
- EXPECT_EQ(Triple.substr(0, 7), "arm64e-");
-#elif defined(__APPLE__) && (defined(__arm64__) || defined(__aarch64__))
- EXPECT_EQ(Triple.substr(0, 6), "arm64-");
-#elif defined(__aarch64__) || defined(_M_ARM64)
- EXPECT_EQ(Triple.substr(0, 8), "aarch64-");
-#elif defined(__x86_64h__)
- EXPECT_EQ(Triple.substr(0, 8), "x86_64h-");
-#elif defined(__x86_64__) || defined(_M_X64)
- EXPECT_EQ(Triple.substr(0, 7), "x86_64-");
-#endif
-}
-
-TEST(TargetTripleTest, OSMatchesCompileTarget) {
- auto Triple = sys::detectTargetTriple();
-#if defined(__APPLE__)
- EXPECT_NE(Triple.find("-apple-"), std::string::npos);
-#elif defined(__linux__)
- EXPECT_NE(Triple.find("-linux-"), std::string::npos);
-#endif
-}
-#endif
-TEST(TargetTripleTest, CachedResultIsIdempotent) {
- EXPECT_EQ(sys::detectTargetTriple(), sys::detectTargetTriple());
-}
+//===- TargetTripleTest.cpp -----------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests for orc-rt's bedrock/sys/TargetTriple.h APIs.
+//
+//===----------------------------------------------------------------------===//
+
+#include "orc-rt-internal/bedrock/sys/TargetTriple.h"
+#include "gtest/gtest.h"
+
+#include <algorithm>
+
+using namespace orc_rt;
+
+TEST(TargetTripleTest, NotEmpty) {
+ EXPECT_FALSE(sys::detectTargetTriple().empty());
+}
+
+TEST(TargetTripleTest, HasValidStructure) {
+ auto Triple = sys::detectTargetTriple();
+ // A valid triple has 2 hyphens (arch-vendor-os) or 3 (arch-vendor-os-env).
+ auto NumHyphens = std::count(Triple.begin(), Triple.end(), '-');
+ EXPECT_GE(NumHyphens, 2);
+ EXPECT_LE(NumHyphens, 3);
+}
+
+TEST(TargetTripleTest, ArchMatchesCompileTarget) {
+ auto Triple = sys::detectTargetTriple();
+#if defined(__arm64e__)
+ EXPECT_EQ(Triple.substr(0, 7), "arm64e-");
+#elif defined(__APPLE__) && (defined(__arm64__) || defined(__aarch64__))
+ EXPECT_EQ(Triple.substr(0, 6), "arm64-");
+#elif defined(__aarch64__) || defined(_M_ARM64)
+ EXPECT_EQ(Triple.substr(0, 8), "aarch64-");
+#elif defined(__x86_64h__)
+ EXPECT_EQ(Triple.substr(0, 8), "x86_64h-");
+#elif defined(__x86_64__) || defined(_M_X64)
+ EXPECT_EQ(Triple.substr(0, 7), "x86_64-");
+#endif
+}
+
+TEST(TargetTripleTest, OSMatchesCompileTarget) {
+ auto Triple = sys::detectTargetTriple();
+
+ #if defined(__APPLE__)
+ EXPECT_NE(Triple.find("-apple-"), std::string::npos);
+ #elif defined(__linux__)
+ EXPECT_NE(Triple.find("-linux-"), std::string::npos);
+ #elif defined(_WIN32)
+ EXPECT_NE(Triple.find("-windows-"), std::string::npos);
+ #endif
+}
+
+TEST(TargetTripleTest, CachedResultIsIdempotent) {
+ EXPECT_EQ(sys::detectTargetTriple(), sys::detectTargetTriple());
+}
More information about the llvm-commits
mailing list