1 //===-- llvm/ADT/bit.h - C++20 <bit> ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the C++20 <bit> header.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_BIT_H
15 #define LLVM_ADT_BIT_H
17 #include "llvm/Support/Compiler.h"
19 #include <type_traits>
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
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
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.
51 inline To bit_cast(const From &from) noexcept {
53 std::memcpy(&to, &from, sizeof(To));