bit.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/ADT/bit.h - C++20 <bit> ----------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file implements the C++20 <bit> header.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ADT_BIT_H
  19. #define LLVM_ADT_BIT_H
  20. #include "llvm/Support/Compiler.h"
  21. #include <cstring>
  22. #include <type_traits>
  23. namespace llvm {
  24. // This implementation of bit_cast is different from the C++17 one in two ways:
  25. // - It isn't constexpr because that requires compiler support.
  26. // - It requires trivially-constructible To, to avoid UB in the implementation.
  27. template <
  28. typename To, typename From,
  29. typename = std::enable_if_t<sizeof(To) == sizeof(From)>
  30. #if (__has_feature(is_trivially_constructible) && defined(_LIBCPP_VERSION)) || \
  31. (defined(__GNUC__) && __GNUC__ >= 5)
  32. ,
  33. typename = std::enable_if_t<std::is_trivially_constructible<To>::value>
  34. #elif __has_feature(is_trivially_constructible)
  35. ,
  36. typename = std::enable_if_t<__is_trivially_constructible(To)>
  37. #else
  38. // See comment below.
  39. #endif
  40. #if (__has_feature(is_trivially_copyable) && defined(_LIBCPP_VERSION)) || \
  41. (defined(__GNUC__) && __GNUC__ >= 5)
  42. ,
  43. typename = std::enable_if_t<std::is_trivially_copyable<To>::value>,
  44. typename = std::enable_if_t<std::is_trivially_copyable<From>::value>
  45. #elif __has_feature(is_trivially_copyable)
  46. ,
  47. typename = std::enable_if_t<__is_trivially_copyable(To)>,
  48. typename = std::enable_if_t<__is_trivially_copyable(From)>
  49. #else
  50. // This case is GCC 4.x. clang with libc++ or libstdc++ never get here. Unlike
  51. // llvm/Support/type_traits.h's is_trivially_copyable we don't want to
  52. // provide a good-enough answer here: developers in that configuration will hit
  53. // compilation failures on the bots instead of locally. That's acceptable
  54. // because it's very few developers, and only until we move past C++11.
  55. #endif
  56. >
  57. inline To bit_cast(const From &from) noexcept {
  58. To to;
  59. std::memcpy(&to, &from, sizeof(To));
  60. return to;
  61. }
  62. } // namespace llvm
  63. #endif
  64. #ifdef __GNUC__
  65. #pragma GCC diagnostic pop
  66. #endif