PointerUnion.h 10.0 KB

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