PointerUnion.h 11 KB

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