PointerUnion.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- 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 defines the PointerUnion class, which is a discriminated union of
  16. /// pointer types.
  17. ///
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_ADT_POINTERUNION_H
  20. #define LLVM_ADT_POINTERUNION_H
  21. #include "llvm/ADT/DenseMapInfo.h"
  22. #include "llvm/ADT/PointerIntPair.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/Support/PointerLikeTypeTraits.h"
  25. #include <algorithm>
  26. #include <cassert>
  27. #include <cstddef>
  28. #include <cstdint>
  29. namespace llvm {
  30. namespace pointer_union_detail {
  31. /// Determine the number of bits required to store integers with values < n.
  32. /// This is ceil(log2(n)).
  33. constexpr int bitsRequired(unsigned n) {
  34. return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
  35. }
  36. template <typename... Ts> constexpr int lowBitsAvailable() {
  37. return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
  38. }
  39. /// Find the first type in a list of types.
  40. template <typename T, typename...> struct GetFirstType {
  41. using type = T;
  42. };
  43. /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
  44. /// for the template arguments.
  45. template <typename ...PTs> class PointerUnionUIntTraits {
  46. public:
  47. static inline void *getAsVoidPointer(void *P) { return P; }
  48. static inline void *getFromVoidPointer(void *P) { return P; }
  49. static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
  50. };
  51. template <typename Derived, typename ValTy, int I, typename ...Types>
  52. class PointerUnionMembers;
  53. template <typename Derived, typename ValTy, int I>
  54. class PointerUnionMembers<Derived, ValTy, I> {
  55. protected:
  56. ValTy Val;
  57. PointerUnionMembers() = default;
  58. PointerUnionMembers(ValTy Val) : Val(Val) {}
  59. friend struct PointerLikeTypeTraits<Derived>;
  60. };
  61. template <typename Derived, typename ValTy, int I, typename Type,
  62. typename ...Types>
  63. class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
  64. : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
  65. using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
  66. public:
  67. using Base::Base;
  68. PointerUnionMembers() = default;
  69. PointerUnionMembers(Type V)
  70. : Base(ValTy(const_cast<void *>(
  71. PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
  72. I)) {}
  73. using Base::operator=;
  74. Derived &operator=(Type V) {
  75. this->Val = ValTy(
  76. const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
  77. I);
  78. return static_cast<Derived &>(*this);
  79. };
  80. };
  81. }
  82. /// A discriminated union of two or more pointer types, with the discriminator
  83. /// in the low bit of the pointer.
  84. ///
  85. /// This implementation is extremely efficient in space due to leveraging the
  86. /// low bits of the pointer, while exposing a natural and type-safe API.
  87. ///
  88. /// Common use patterns would be something like this:
  89. /// PointerUnion<int*, float*> P;
  90. /// P = (int*)0;
  91. /// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
  92. /// X = P.get<int*>(); // ok.
  93. /// Y = P.get<float*>(); // runtime assertion failure.
  94. /// Z = P.get<double*>(); // compile time failure.
  95. /// P = (float*)0;
  96. /// Y = P.get<float*>(); // ok.
  97. /// X = P.get<int*>(); // runtime assertion failure.
  98. /// PointerUnion<int*, int*> Q; // compile time failure.
  99. template <typename... PTs>
  100. class PointerUnion
  101. : public pointer_union_detail::PointerUnionMembers<
  102. PointerUnion<PTs...>,
  103. PointerIntPair<
  104. void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
  105. pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
  106. 0, PTs...> {
  107. static_assert(TypesAreDistinct<PTs...>::value,
  108. "PointerUnion alternative types cannot be repeated");
  109. // The first type is special because we want to directly cast a pointer to a
  110. // default-initialized union to a pointer to the first type. But we don't
  111. // want PointerUnion to be a 'template <typename First, typename ...Rest>'
  112. // because it's much more convenient to have a name for the whole pack. So
  113. // split off the first type here.
  114. using First = TypeAtIndex<0, PTs...>;
  115. using Base = typename PointerUnion::PointerUnionMembers;
  116. public:
  117. PointerUnion() = default;
  118. PointerUnion(std::nullptr_t) : PointerUnion() {}
  119. using Base::Base;
  120. /// Test if the pointer held in the union is null, regardless of
  121. /// which type it is.
  122. bool isNull() const { return !this->Val.getPointer(); }
  123. explicit operator bool() const { return !isNull(); }
  124. /// Test if the Union currently holds the type matching T.
  125. template <typename T> bool is() const {
  126. return this->Val.getInt() == FirstIndexOfType<T, PTs...>::value;
  127. }
  128. /// Returns the value of the specified pointer type.
  129. ///
  130. /// If the specified pointer type is incorrect, assert.
  131. template <typename T> T get() const {
  132. assert(is<T>() && "Invalid accessor called");
  133. return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
  134. }
  135. /// Returns the current pointer if it is of the specified pointer type,
  136. /// otherwise returns null.
  137. template <typename T> T dyn_cast() const {
  138. if (is<T>())
  139. return get<T>();
  140. return T();
  141. }
  142. /// If the union is set to the first pointer type get an address pointing to
  143. /// it.
  144. First const *getAddrOfPtr1() const {
  145. return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
  146. }
  147. /// If the union is set to the first pointer type get an address pointing to
  148. /// it.
  149. First *getAddrOfPtr1() {
  150. assert(is<First>() && "Val is not the first pointer");
  151. assert(
  152. PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==
  153. this->Val.getPointer() &&
  154. "Can't get the address because PointerLikeTypeTraits changes the ptr");
  155. return const_cast<First *>(
  156. reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
  157. }
  158. /// Assignment from nullptr which just clears the union.
  159. const PointerUnion &operator=(std::nullptr_t) {
  160. this->Val.initWithPointer(nullptr);
  161. return *this;
  162. }
  163. /// Assignment from elements of the union.
  164. using Base::operator=;
  165. void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
  166. static inline PointerUnion getFromOpaqueValue(void *VP) {
  167. PointerUnion V;
  168. V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
  169. return V;
  170. }
  171. };
  172. template <typename ...PTs>
  173. bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
  174. return lhs.getOpaqueValue() == rhs.getOpaqueValue();
  175. }
  176. template <typename ...PTs>
  177. bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
  178. return lhs.getOpaqueValue() != rhs.getOpaqueValue();
  179. }
  180. template <typename ...PTs>
  181. bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
  182. return lhs.getOpaqueValue() < rhs.getOpaqueValue();
  183. }
  184. // Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
  185. // # low bits available = min(PT1bits,PT2bits)-1.
  186. template <typename ...PTs>
  187. struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
  188. static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
  189. return P.getOpaqueValue();
  190. }
  191. static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
  192. return PointerUnion<PTs...>::getFromOpaqueValue(P);
  193. }
  194. // The number of bits available are the min of the pointer types minus the
  195. // bits needed for the discriminator.
  196. static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
  197. PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
  198. };
  199. // Teach DenseMap how to use PointerUnions as keys.
  200. template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
  201. using Union = PointerUnion<PTs...>;
  202. using FirstInfo =
  203. DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
  204. static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
  205. static inline Union getTombstoneKey() {
  206. return Union(FirstInfo::getTombstoneKey());
  207. }
  208. static unsigned getHashValue(const Union &UnionVal) {
  209. intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
  210. return DenseMapInfo<intptr_t>::getHashValue(key);
  211. }
  212. static bool isEqual(const Union &LHS, const Union &RHS) {
  213. return LHS == RHS;
  214. }
  215. };
  216. } // end namespace llvm
  217. #endif // LLVM_ADT_POINTERUNION_H
  218. #ifdef __GNUC__
  219. #pragma GCC diagnostic pop
  220. #endif