bit.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //===-- llvm/ADT/bit.h - C++20 <bit> ----------------------------*- C++ -*-===//
  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. // This file implements the C++20 <bit> header.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_ADT_BIT_H
  13. #define LLVM_ADT_BIT_H
  14. #include "llvm/Support/Compiler.h"
  15. #include <cstring>
  16. #include <type_traits>
  17. namespace llvm {
  18. // This implementation of bit_cast is different from the C++17 one in two ways:
  19. // - It isn't constexpr because that requires compiler support.
  20. // - It requires trivially-constructible To, to avoid UB in the implementation.
  21. template <
  22. typename To, typename From,
  23. typename = std::enable_if_t<sizeof(To) == sizeof(From)>
  24. #if (__has_feature(is_trivially_constructible) && defined(_LIBCPP_VERSION)) || \
  25. (defined(__GNUC__) && __GNUC__ >= 5)
  26. ,
  27. typename = std::enable_if_t<std::is_trivially_constructible<To>::value>
  28. #elif __has_feature(is_trivially_constructible)
  29. ,
  30. typename = std::enable_if_t<__is_trivially_constructible(To)>
  31. #else
  32. // See comment below.
  33. #endif
  34. #if (__has_feature(is_trivially_copyable) && defined(_LIBCPP_VERSION)) || \
  35. (defined(__GNUC__) && __GNUC__ >= 5)
  36. ,
  37. typename = std::enable_if_t<std::is_trivially_copyable<To>::value>,
  38. typename = std::enable_if_t<std::is_trivially_copyable<From>::value>
  39. #elif __has_feature(is_trivially_copyable)
  40. ,
  41. typename = std::enable_if_t<__is_trivially_copyable(To)>,
  42. typename = std::enable_if_t<__is_trivially_copyable(From)>
  43. #else
  44. // This case is GCC 4.x. clang with libc++ or libstdc++ never get here. Unlike
  45. // llvm/Support/type_traits.h's is_trivially_copyable we don't want to
  46. // provide a good-enough answer here: developers in that configuration will hit
  47. // compilation failures on the bots instead of locally. That's acceptable
  48. // because it's very few developers, and only until we move past C++11.
  49. #endif
  50. >
  51. inline To bit_cast(const From &from) noexcept {
  52. To to;
  53. std::memcpy(&to, &from, sizeof(To));
  54. return to;
  55. }
  56. } // namespace llvm
  57. #endif