DPC++ Runtime
Runtime libraries for oneAPI DPC++
bit_cast.hpp
Go to the documentation of this file.
1 //==---------------- bit_cast.hpp - SYCL bit_cast --------------------------==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #pragma once
10 
11 #include <type_traits> // for is_trivially_copyable, enable_if_t
12 
13 // std::bit_cast is first choice, __builtin_bit_cast second.
14 // memcpy fallback of last resort, not constexpr :-(
15 
16 // MSVC 2019 Update 9 or later (aka Visual Studio 2019 v 16.8.1)
17 #if defined(_MSC_VER) && _MSC_VER >= 1928
18 #define __SYCL_HAS_BUILTIN_BIT_CAST 1
19 #elif defined(__has_builtin)
20 #define __SYCL_HAS_BUILTIN_BIT_CAST __has_builtin(__builtin_bit_cast)
21 #else
22 #define __SYCL_HAS_BUILTIN_BIT_CAST 0
23 #endif
24 
25 #if __cplusplus >= 202002L
26 #include <version> // defines __cpp_lib_bit_cast
27 #endif
28 
29 #if __cpp_lib_bit_cast
30 // first choice std::bit_cast
31 #include <bit>
32 #define __SYCL_BITCAST_IS_CONSTEXPR 1
33 #elif __SYCL_HAS_BUILTIN_BIT_CAST
34 // second choice __builtin_bit_cast
35 #define __SYCL_BITCAST_IS_CONSTEXPR 1
36 #else
37 // fallback memcpy
38 #include <sycl/detail/memcpy.hpp>
39 #endif
40 
41 namespace sycl {
42 inline namespace _V1 {
43 
44 template <typename To, typename From>
45 #if defined(__SYCL_BITCAST_IS_CONSTEXPR)
46 constexpr
47 #endif
48  std::enable_if_t<sizeof(To) == sizeof(From) &&
49  std::is_trivially_copyable<From>::value &&
50  std::is_trivially_copyable<To>::value,
51  To>
52  bit_cast(const From &from) noexcept {
53 #if __cpp_lib_bit_cast
54  // first choice std::bit_cast
55  return std::bit_cast<To>(from);
56 #elif __SYCL_HAS_BUILTIN_BIT_CAST
57  // second choice __builtin_bit_cast
58  return __builtin_bit_cast(To, from);
59 #else
60  // fallback memcpy
61  static_assert(std::is_trivially_default_constructible<To>::value,
62  "To must be trivially default constructible");
63  To to;
64  sycl::detail::memcpy(&to, &from, sizeof(To));
65  return to;
66 #endif
67 }
68 
69 } // namespace _V1
70 } // namespace sycl
std::enable_if_t< sizeof(To)==sizeof(From) &&std::is_trivially_copyable< From >::value &&std::is_trivially_copyable< To >::value, To > bit_cast(const From &from) noexcept
Definition: bit_cast.hpp:52
Definition: access.hpp:18
_Abi const simd< _Tp, _Abi > & noexcept
Definition: simd.hpp:1324