Andrew Scull | 0372a57 | 2018-11-16 15:47:06 +0000 | [diff] [blame^] | 1 | //===-- llvm/ADT/bit.h - C++20 <bit> ----------------------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements the C++20 <bit> header. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #ifndef LLVM_ADT_BIT_H |
| 15 | #define LLVM_ADT_BIT_H |
| 16 | |
| 17 | #include "llvm/Support/Compiler.h" |
| 18 | #include <cstring> |
| 19 | #include <type_traits> |
| 20 | |
| 21 | namespace llvm { |
| 22 | |
| 23 | // This implementation of bit_cast is different from the C++17 one in two ways: |
| 24 | // - It isn't constexpr because that requires compiler support. |
| 25 | // - It requires trivially-constructible To, to avoid UB in the implementation. |
| 26 | template <typename To, typename From |
| 27 | , typename = typename std::enable_if<sizeof(To) == sizeof(From)>::type |
| 28 | #if (__has_feature(is_trivially_constructible) && defined(_LIBCPP_VERSION)) || \ |
| 29 | (defined(__GNUC__) && __GNUC__ >= 5) |
| 30 | , typename = typename std::is_trivially_constructible<To>::type |
| 31 | #elif __has_feature(is_trivially_constructible) |
| 32 | , typename = typename std::enable_if<__is_trivially_constructible(To)>::type |
| 33 | #else |
| 34 | // See comment below. |
| 35 | #endif |
| 36 | #if (__has_feature(is_trivially_copyable) && defined(_LIBCPP_VERSION)) || \ |
| 37 | (defined(__GNUC__) && __GNUC__ >= 5) |
| 38 | , typename = typename std::enable_if<std::is_trivially_copyable<To>::value>::type |
| 39 | , typename = typename std::enable_if<std::is_trivially_copyable<From>::value>::type |
| 40 | #elif __has_feature(is_trivially_copyable) |
| 41 | , typename = typename std::enable_if<__is_trivially_copyable(To)>::type |
| 42 | , typename = typename std::enable_if<__is_trivially_copyable(From)>::type |
| 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 isPodLike we don't want to provide a |
| 46 | // 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 | |
| 57 | } // namespace llvm |
| 58 | |
| 59 | #endif |